如果存在多个具有相同值的文档,则 Elasticsearch 计数

Elasticsearch count if more than one document with same value exists

如果一个字段的值在多个文档中相同,我想要文档计数。我如何编写 DSL 查询来执行此操作?

示例:

假设我有这些文件:

{ _id:1, foo:1}
{ _id:2, foo:1}
{ _id:3, foo:3}
{ _id:4, foo:2}
{ _id:5, foo:3}

如果在多个文档中找到相同的 foo 值,我需要计算文档数。在这里,我希望计数为 2。

更新

在 运行 之后查询为:

{
   "size": 0,
   "aggs": {
      "counts": {
          "terms": {
              "field": "foo"
          }
      }
   }
}

我得到了这个结果:

'aggregations':{
    'counts':{
        'buckets':[
             {'doc_count': 221,'key': '10284'},
             {'doc_count': 71,'key': '6486'},
             {'doc_count': 71,'key': '7395'}
         ],
        'doc_count_error_upper_bound': 0,
        'sum_other_doc_count': 0
    }
}

我想要另一个字段 total_count,它的值为 3,因为有 3 个键 doc_count 大于 1。我该怎么做?

您可以像这样在 foo 字段上尝试一个简单的 terms 聚合:

{
   "size": 0,
   "aggs": {
      "counts": {
          "terms": {
              "field": "foo"
          }
      }
   }
}

在 运行 之后,您将获得

  • 对于密钥 1:doc_count 2
  • 对于键 3:doc_count 2
  • 对于密钥 1:doc_count 1

我认为仅使用 ES 无法开箱即用。在 min_doc_count: 2 terms 聚合之后,您基本上需要一个存储桶计数。

在 ES 5 中,您将拥有:https://github.com/elastic/elasticsearch/issues/19553(对于 bucket_selector 聚合,将有一个可以使用的 _bucket_count 变量)。该变量是否也可以在其他脚本中使用还有待观察。