我有一个书索引,其中包含一个标签数组(具有文本/关键字类型),我想为标签提供自动完成功能,以便用户键入“ro”,并返回“romance”或“rock and roll”。
这是我的映射:
/books {
...
tags: {
type: 'text',
field: {
keyword: {type: 'keyword'}
}
}
}
范例书
{ name: "foo", tags: ['romance', 'story', 'fiction'] }
我的标签汇总:
{
size: 0,
aggregations: {
options: {
terms: {
field: `tags.keyword`,
size: 20
}
}
}
如何只获得所有与“ro”匹配的不同标签?
最佳答案
只需尝试:
GET book/_search
{
"query": {
"prefix": {
"tags.keyword": "ro"
}
}, "size": 0,
"aggs": {
"options": {
"terms": {
"field": "tags.keyword",
"size": 20
}
}
}
}
但是对于您的用例,我建议您使用ngram过滤器构建自定义分析器,如下所示:
"tags": {
"type": "text",
"analyzer": "english_custom",
"fields": {
"suggester": {
"type": "text",
"analyzer": "autocomplete",
"search_analyzer": "standard"
},
"keyword":{
"type": "keyword" }
}
自动完成分析器应如下所示:
{"filter":{
....
"autocomplete_filter": {
"type": "edge_ngram",
"min_gram": 2,
"max_gram": 8
}
},
"analyzer": {
"autocomplete": {
"type": "custom",
"tokenizer": "standard",
"filter": [
"lowercase",
"autocomplete_filter"
]
}
}
编辑:
您可以在术语聚合中使用include子句吗?
GET /_search
{
"aggs" : {
"tags" : {
"terms" : {
"field" : "tags.keyword",
"include" : "ro.*"
}
}
}
}
关于elasticsearch - 如何在ES中搜索聚合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52510089/