From d844663f86c64aab678e1c9fe6ca5be089f95514 Mon Sep 17 00:00:00 2001 From: asahi Date: Tue, 29 Oct 2024 20:03:05 +0800 Subject: [PATCH] =?UTF-8?q?=E9=98=85=E8=AF=BBes=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- elastic search/elastic search.md | 123 +++++++++++++++++++++++++++++++ 1 file changed, 123 insertions(+) diff --git a/elastic search/elastic search.md b/elastic search/elastic search.md index 597aa6d..f4615bf 100644 --- a/elastic search/elastic search.md +++ b/elastic search/elastic search.md @@ -484,6 +484,129 @@ DELETE /my-explicit-mappings-books 删除索引将会永久删除其document、shards、元数据。 +### 全文本搜索和过滤 +如下示例展示了如何实现cook blog的搜索功能。 +#### 创建索引 +创建`cooking_blog`索引 +``` +PUT /cooking_blog +``` + +为索引定义mapping: +``` +PUT /cooking_blog/_mapping +{ + "properties": { + "title": { + "type": "text", + "analyzer": "standard", + "fields": { + "keyword": { + "type": "keyword", + "ignore_above": 256 + } + } + }, + "description": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword" + } + } + }, + "author": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword" + } + } + }, + "date": { + "type": "date", + "format": "yyyy-MM-dd" + }, + "category": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword" + } + } + }, + "tags": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword" + } + } + }, + "rating": { + "type": "float" + } + } +} +``` + +上述mapping定义含义如下: +- 对于`text`类型的field,如果analyzer没有指定,那么会默认使用`standard` analyzer +- 在上述示例中,使用了`multi fields`,将字段既作为`text`来进行全文搜索,又作为`keyword`来进行聚合和排序。在该字段上,既支持全文搜索,又支持青雀匹配和过滤。如果使用dynamic mapping,那么multi-fields将会自动被创建。 +- `ignore_above`不会索引`keyword`field中超过256个字符长度的值。默认情况下,keyword field其ignore_above的值为256 + +> #### multi-field +> 对同一个字段按不同的方式进行索引有时候很必要,对于multi-fields,一个字符串类型字段可以被映射到`text`类型用于全文索引,也可以被映射到`keyword`类型用作排序和聚合。 +> +> 示例如下: +> ``` +> PUT my-index-000001 +> { +> "mappings": { +> "properties": { +> "city": { +> "type": "text", +> "fields": { +> "raw": { +> "type": "keyword" +> } +> } +> } +> } +> } +> } +> +> PUT my-index-000001/_doc/1 +> { +> "city": "New York" +> } +> +> PUT my-index-000001/_doc/2 +> { +> "city": "York" +> } +> +> GET my-index-000001/_search +> { +> "query": { +> "match": { +> "city": "york" +> } +> }, +> "sort": { +> "city.raw": "asc" +> }, +> "aggs": { +> "Cities": { +> "terms": { +> "field": "city.raw" +> } +> } +> } +> } +> ``` + +#### 将blog示例添加到索引中