elasticsearch - ES聚合内部查询

标签 elasticsearch latency elasticsearch-5

我不想运行多个非常相似的“必须匹配”查询,而是想运行具有多个聚合的单个查询。

我知道如何在单个查询中放置多个聚合,但是有可能有一个范围查询,有点像单个聚合中的子查询?

我只想计算每个查询的文档数量(在这种情况下为汇总)

例如,我想将以下查询合并为一个,只是为了计算每个查询的文档数:

{
  "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/

相关文章:

elasticsearch - ElasticSearch 5:插入数据时发生MapperParserException

amazon-web-services - 如何配置 Winlogbeat 连接到 AWS elasticsearch

grails - 无法反序列化来自流的异常响应 - Grails ElasticSearch

elasticsearch - 按字段值对文档进行分组

performance - 延迟和响应时间有什么区别?

elasticsearch - bucket_selector中的_bucket_count-管道聚合

elasticsearch - 聚合嵌套类型属性-使用NEST

.net - 使用NEST在Elasticsearch中检索未知数量的文档

游戏中的网络问题

java - AppEngine 中的服务和前端分离导致延迟