【问题标题】:Merge the results of two aggregations合并两个聚合的结果
【发布时间】:2019-03-22 21:53:58
【问题描述】:

我有一个 Elasticsearch 索引,其中包含具有以下字段的文档:

  • 作者
  • 贡献者

每个字段都可能包含多个用户 ID。

我想执行一个聚合,计算与每个用户(作为作者或贡献者)相关的文档总数。

我可以单独查询每个聚合,但如何组合它们?这是我的查询:

GET documents/_search
{
  "aggs": {
    "contributor": {
      "terms": {
        "field": "contributor"
      }
    },
    "author": {
      "terms": {
        "field": "author"
      }
    }
  }
}

现在,我得到了这个结果:

"aggregations": {
    "author": {
        "doc_count_error_upper_bound": 0,
        "sum_other_doc_count": 0,
        "buckets": [{
                "key": 2,
                "doc_count": 10
            },
            {
                "key": 1,
                "doc_count": 7
            },
            {
                "key": 5,
                "doc_count": 3
            }
        ]
    },
    "contributor": {
        "doc_count_error_upper_bound": 0,
        "sum_other_doc_count": 0,
        "buckets": [{
            "key": 5,
            "doc_count": 1
        }]
    }
}

但我想要一个聚合,返回用户 5 的 4 个文档的计数。

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    如果您可以更新您的映射并添加一个字段,这应该可以工作。请不要它可能真的很慢(字符串上的 agg 很慢,不应该过度使用)。请注意,如果作者 = 同一文档中的贡献者,则 agg 将不会计算 2 次出现(好消息)。

        {
          "mappings": {
            "test": {
              "properties": {
                "contributor": {
                  "type": "keyword",
                  "copy_to": "author_and_contributor"
                },
                "author": {
                  "type": "keyword",
                  "copy_to": "author_and_contributor"
                },
                "author_and_contributor": {
                  "type": "string",
                  "fielddata": true
                }
              }
            }
          }
    }
    
    {
      "size": 0,
      "aggs": {
        "author_contrib_agg": {
          "terms": {
            "field": "author_and_contributor"
          }
        }
      }
    }
    

    【讨论】:

    • 这是一个很好的解决方案!虽然我不得不说author_and_contributor 可以是keyword 类型,因此使用fielddata 消除了这个问题。 (用 ES6 测试。)
    猜你喜欢
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 2021-12-12
    • 2014-01-25
    • 2014-02-23
    • 2019-01-30
    • 1970-01-01
    相关资源
    最近更新 更多