假设它是下面我的索引的映射,我想创建一个弹性聚合查询来计算
test
数组属性的每个元素的文档数量
"mappings": {
"properties": {
"code": {
"type": "keyword"
},
"details": {
"type": "nested",
"properties": {
"name": {
"type": "text",
"analyzer": "html_stripper"
},
"elts": {
"type": "integer"
}
}
}
}
},
[
{
"code": "test",
"details": [
{"name": "test", "elts": [1,2,3,4]}
]
},
{
"code": "test2",
"details": [
{"name": "test2", "elts": [1,2,4]}
]
}
]
我已经尝试过这个查询
POST /my-index/_search
{
"size": 0,
"aggs": {
"unique_count": {
"terms": {
"field": "details.elts"
}
}
}
}
但是它不起作用。下面是结果
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 3,
"relation": "eq"
},
"max_score": null,
"hits": []
},
"aggregations": {
"lterms#unique_count": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": []
}
}
}
我期待的是一个像水桶一样的东西
[
{
"key": "1",
"doc_count": 2
},
{
"key": "2",
"doc_count": 2
},
{
"key": "3",
"doc_count": 1
},
{
"key": "4",
"doc_count": 2
}
]
您应该通过
nested
聚合来包装聚合以访问嵌套文档
POST /my-index/_search?filter_path=aggregations
{
"aggs": {
"inside_details": {
"nested": {
"path": "details"
},
"aggs": {
"unique_count": {
"terms": {
"field": "details.elts",
"order": {
"_key": "asc"
}
}
}
}
}
}
}
回应
{
"aggregations" : {
"inside_details" : {
"doc_count" : 2,
"unique_count" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : 1,
"doc_count" : 2
},
{
"key" : 2,
"doc_count" : 2
},
{
"key" : 3,
"doc_count" : 1
},
{
"key" : 4,
"doc_count" : 2
}
]
}
}
}
}