如果存在多个具有相同值的文档,则弹性搜索计数

时间:2016-08-19 11:27:15

标签: elasticsearch querydsl

如果一个字段的值在多个文档中相同,我想要文档的数量。如何编写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.我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以在terms字段上尝试简单的foo聚合,如下所示:

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

运行此功能后,您将获得

  • 表示密钥1:doc_count 2
  • for key 3:doc_count 2
  • 表示密钥1:doc_count 1

答案 1 :(得分:0)

我认为你不能只用ES开箱即可。在min_doc_count: 2 terms聚合后,您基本上需要一个桶数。

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

相关问题