在用户界面上,我需要显示自动完成建议,该建议为我提供包含搜索术语的术语。例如如果我搜索
per
,我可能会得到以下建议:Peru
、Perry
、Casper
、Naperville
、Cooperstown
等。
搜索框用于搜索/过滤正在使用/显示为城市术语聚合的字段。该字段类型为数组,因此一个文档可以有多个城市。自动建议应仅包含可用/结果文档中的城市。
我知道使用术语聚合的过滤器功能和正确的正则表达式。 https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html#_filtering_values_4
但我正在寻找elasticsearch中可用的更好的解决方案,它可以为我提供最快的结果。
您最好的选择是使用
wildcard field
Elasticsearch 引入的新关键字数据类型。如需了解更多信息,请查看 Elastic 关于通配符字段的官方文档这里。此关键字字段类型针对通配符查询进行了优化。
我想
terms
聚合是你的情况下最好的方法。您应该将搜索文本 per
转换为正则表达式 (P|(.+p))er.*
映射
PUT /autocomplete_suggestions
{
"mappings": {
"properties": {
"city": {
"type": "keyword"
}
}
}
}
文件
PUT /autocomplete_suggestions/_bulk
{"create":{"_id":1}}
{"city":["Perry","Moscow"]}
{"create":{"_id":2}}
{"city":["Casper","Cooperstown"]}
{"create":{"_id":3}}
{"city":["Vologda","Kostroma"]}
{"create":{"_id":4}}
{"city":["Naperville","Penza"]}
使用
regexp
查询作为过滤器的聚合查询,以及 include
参数来过滤数组中的城市
GET /autocomplete_suggestions/_search?filter_path=aggregations.by_city.buckets.key
{
"query": {
"regexp": {
"city": {
"value": "(P|(.+p))er.*"
}
}
},
"aggs": {
"by_city": {
"terms": {
"field": "city",
"include": "(P|(.+p))er.*"
}
}
}
}
回应
{
"aggregations" : {
"by_city" : {
"buckets" : [
{
"key" : "Casper"
},
{
"key" : "Cooperstown"
},
{
"key" : "Naperville"
},
{
"key" : "Perry"
}
]
}
}
}
您可以使用 ngram 代替正则表达式查询