mil*_*dky 12 unique aggregation elasticsearch
我遇到了一个问题,即弹性搜索无法通过在嵌套字段上使用术语聚合来返回唯一文档的数量.
这是我们模型的一个例子:
{
...,
"location" : [
{"city" : "new york", "state" : "ny"},
{"city" : "woodbury", "state" : "ny"},
...
],
...
}
Run Code Online (Sandbox Code Playgroud)
我想在状态字段上进行聚合,但是这个文档将在'ny'桶中计数两次,因为'ny'在文档中出现两次.
所以我想知道在哪里可以获取不同文档的数量.
制图:
people = {
:properties => {
:location => {
:type => 'nested',
:properties => {
:city => {
:type => 'string',
:index => 'not_analyzed',
},
:state => {
:type => 'string',
:index => 'not_analyzed',
},
}
},
:last_name => {
:type => 'string',
:index => 'not_analyzed'
}
}
}
Run Code Online (Sandbox Code Playgroud)
查询非常简单:
curl -XGET 'http://localhost:9200/people/_search?pretty&search_type=count' -d '{
"query" : {
"bool" : {
"must" : [
{"term" : {"last_name" : "smith"}}
]
}
},
"aggs" : {
"location" : {
"nested" : {
"path" : "location"
},
"aggs" : {
"state" : {
"terms" : {"field" : "location.state", "size" : 10}
}
}
}
}
}'
Run Code Online (Sandbox Code Playgroud)
响应:
{
"took" : 104,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"failed" : 0
},
"hits" : {
"total" : 1248513,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
"location" : {
"doc_count" : 2107012,
"state" : {
"buckets" : [ {
"key" : 6,
"key_as_string" : "6",
"doc_count" : 214754
}, {
"key" : 12,
"key_as_string" : "12",
"doc_count" : 168887
}, {
"key" : 48,
"key_as_string" : "48",
"doc_count" : 101333
} ]
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
doc_count远远大于命中总数.所以必须有重复.
谢谢!
And*_*fan 17
我认为你需要一个reverse_nested聚合,因为你想要基于嵌套值进行聚合,但实际上是计算ROOT文档,而不是嵌套文档
{
"query": {
"bool": {
"must": [
{
"term": {
"last_name": "smith"
}
}
]
}
},
"aggs": {
"location": {
"nested": {
"path": "location"
},
"aggs": {
"state": {
"terms": {
"field": "location.state",
"size": 10
},
"aggs": {
"top_reverse_nested": {
"reverse_nested": {}
}
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果,你会看到这样的事情:
"aggregations": {
"location": {
"doc_count": 6,
"state": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "ny",
"doc_count": 4,
"top_reverse_nested": {
"doc_count": 2
}
},
{
"key": "ca",
"doc_count": 2,
"top_reverse_nested": {
"doc_count": 2
}
}
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
而你正在寻找的是top_reverse_nested部分.这里有一点:如果我没有误会"doc_count": 6是NESTED文件计数,所以不要混淆这些数字,认为你在计算根文件,计数在嵌套文件上.因此,对于具有三个匹配的嵌套文档的文档,计数将为3,而不是1.
| 归档时间: |
|
| 查看次数: |
8822 次 |
| 最近记录: |