我是Elasticsearch的新手,我想提供“键入时搜索”功能。每个字段要搜索的文本不超过50个字符。搜索应找到包含搜索文本的所有文档。类似于“通配符”àla'* query *'。但这是非常昂贵的。
这就是为什么我尝试根据本文https://www.elastic.co/guide/en/elasticsearch/reference/current/search-analyzer.html的描述进行操作。在我的情况下,唯一的区别是我想使用“ n-gram”分析器而不是“ edge n-gram”分析器。
我创建了以下自定义分析器:
"settings": {
"index": {
"max_ngram_diff": "50",
[...]
"analysis": {
"filter": {
"3-50-grams-filter": {
"type": "ngram",
"min_gram": "3",
"max_gram": "50"
}
},
"analyzer": {
"index-3-50-grams-analyzer": {
"filter": [
"lowercase",
"3-50-grams-filter"
],
"type": "custom",
"tokenizer": "keyword"
},
"search-3-50-grams-analyzer": {
"filter": [
"lowercase"
],
"type": "custom",
"tokenizer": "keyword"
}
我创建了以下映射:
"mappings": {
dynamic": "strict",
properties": {
"my-field": {
"type": "text",
"fields": {
"my-field": {
"type": "text",
"analyzer": "index-3-50-grams-analyzer",
"search_analyzer": "search-3-50-grams-analyzer"
},
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
发布以下数据:
{
"my-field": "1107811#1OMAH0RN03D2"
}
发送到Analyze-API:
{
"text" : "1107811#1OMAH0RN03D2",
"field" : "my-field"
}
获得以下结果:
{
"tokens": [
{
"token": "1107811",
"start_offset": 0,
"end_offset": 7,
"type": "<NUM>",
"position": 0
},
{
"token": "1omah0rn03d2",
"start_offset": 8,
"end_offset": 20,
"type": "<ALPHANUM>",
"position": 1
}
]
}
这样的查询找到文档:
"query": {
"match": {
"my-field": {
"query": "1OMAH0RN03D2"
}
}
}
...但是这样的查询不会(只是删除了第一个字符):
"query": {
"match": {
"my-field": {
"query": "OMAH0RN03D2"
}
}
}
...并且使用显式search_analyzer进行的查询也不会(如果我再删除一个字符):
"query": {
"match": {
"my-field": {
"query": "MAH0RN03D2",
"analyzer": "search-3-50-grams-analyzer"
}
}
}
有人知道导致这种现象的原因吗?
不确定,但是我尝试了您的示例文档和索引设置,它对我来说很好用,下面是我逐步完成的工作。