我不想运行多个非常相似的“必须匹配”查询,而是想运行具有多个聚合的单个查询。
我知道如何在单个查询中放置多个聚合,但是有可能有一个范围查询,有点像单个聚合中的子查询?
我只想计算每个查询的文档数量(在这种情况下为汇总)
例如,我想将以下查询合并为一个,只是为了计算每个查询的文档数:
{
"size": 0,
"query": {
"bool": {
"must": [
{
"match": {
"foo": "bar"
}
},
{
"match": {
"type": "machine"
}
}
]
}
}
}
和:
{
"size": 0,
"query": {
"bool": {
"must": [
{
"match": {
"foo": "bar"
}
},
{
"match": {
"type": "human"
}
}
]
}
}
}
我要如何将两者结合?只是计算每个查询的文档数量?
最佳答案
如果您使用词条查询代替匹配查询,则可以使用。您将直接按该字段进行汇总。
POST index/_search
{
"size": 0,
"query": {
"bool": {
"must": [
{"match": {
"foo": "bar"
}},
{"terms": {
"type": [
"machine",
"human"
]
}}
]
}
}
, "aggs": {
"types": {
"terms": {
"field": "type"
}
}
}
}
结果看起来像这样
{
"took": 18,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 6,
"failed": 0
},
"hits": {
"total": 86967,
"max_score": 0,
"hits": []
},
"aggregations": {
"types": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "human",
"doc_count": 46501
},
{
"key": "machine",
"doc_count": 40466
}
]
}
}
}
要考虑的另一种选择是Multi Search API
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html
GET index/_msearch
{"size":0,"query":{"bool":{"must":[{"match":{"foo":"bar"}},{"match":{"type":"machine"}}]}}}
{"size":0,"query":{"bool":{"must":[{"match":{"foo":"bar"}},{"match":{"type":"human"}}]}}}
关于elasticsearch - ES聚合内部查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49634178/