通常情况下,我们在搜索和创建索引时使用的是同一分析器,以确保我们搜索是的词根与倒排索引中的词根拥有相同的格式。
但是有时我们又会有意识的在搜索时使用不同的分析器,例如使用 edge_ngram 解析器自动解析。
默认情况下,查询将会使用字段映射时定义的分析器,但也能通过 search_analyzer 设置来进行修改:
curl -XPUT 'localhost:9200/my_index?pretty' -H 'Content-Type: application/json' -d'
{
"settings": {
"analysis": {
"filter": {
"autocomplete_filter": { #1
"type": "edge_ngram",
"min_gram": 1,
"max_gram": 20
}
},
"analyzer": {
"autocomplete": {
"type": "custom",
"tokenizer": "standard",
"filter": [
"lowercase",
"autocomplete_filter"
]
}
}
}
},
"mappings": {
"my_type": {
"properties": {
"text": {
"type": "text",
"analyzer": "autocomplete", #2
"search_analyzer": "standard" #3
}
}
}
}
}
'
curl -XPUT 'localhost:9200/my_index/my_type/1?pretty' -H 'Content-Type: application/json' -d'
{
"text": "Quick Brown Fox" #4
}
'
curl -XGET 'localhost:9200/my_index/_search?pretty' -H 'Content-Type: application/json' -d'
{
"query": {
"match": {
"text": {
"query": "Quick Br", #5
"operator": "and"
}
}
}
}
'
| 1 | Analysis 设置为传统的 autocomplete 分析器 |
| 2 3 | text 字段使用 autocomplete 分析器进行索引,但是使用 standard 分析器进行搜索。 |
| 4 | 这个字段将使用以下词根进行索引:[ q
, qu
, qui
, quic
, quick
, b
, br
, bro
, brow
, brown
, f
, fo
, fox
] |
| 5 | 查询搜索将同时使用两个词根:[ quick
, br
] |
可以通过查看 Index time search-as-you- type 获得此例的完整解释。
注意
同一索引相同名字的字段 search_analyzer 设置必须相同。他的值可以通过 PUT mapping API 进行覆盖修改。