在elasticsearch 5.6中对多值和嵌套字段使用聚合时遇到了一个非常特殊的问题,我的索引映射如下:
{
"my_index": {
"mappings": {
"my_type": {
"properties": {
"my_field": {
"type": "nested",
"properties": {
"name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"country": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
}
}
}
}
}
}
我的数据是这样的:
"my_field": [
{"name": "apple", "country": "USA"},
{"name": "alibaba", "country": "CHINA"}
]
要求是:我得到一个查询词,例如apple,我用这个查询词搜索文件名,最后,我想聚合名称为查询词apple的国家。我的查询如下所示:
{"query": {
"nested": {"path": "my_field", "query": {"bool": {"should": [{"match": {"my_field.name.keyword": "apple"}}]}}}},
"aggs": {"m_agg": {"nested": {"path": "my_field"},
"aggs": {"m1_agg": {"terms": {"field": "my_field.country.keyword"}}}}}}
所以输入是apple,预期结果是
"aggregations" : {
"m_agg" : {
"doc_count" : 1,
"m1_agg" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "USA",
"doc_count" : 1
}
]
}
}
}
但弹性搜索返回结果:
"aggregations" : {
"m_agg" : {
"doc_count" : 2,
"m1_agg" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "USA",
"doc_count" : 1
},
{
"key" : "CHINA",
"doc_count" : 1
}
]
}
}
}
如何更改查询 DSL 以获得预期结果?