【问题标题】:Elasticsearch - combine fields from multiple documentsElasticsearch - 组合来自多个文档的字段
【发布时间】:2016-04-21 09:45:47
【问题描述】:

假设我有一堆这样的文件:

{
    "foo" : [1, 2, 3]
}

{
    "foo" : [3, 4, 5]
}

对于针对这些文档运行的查询,我正在寻找一种方法来返回 foo 的所有值的数组(理想情况下是唯一值,但可以重复):

{
    "foo" : [1, 2, 3, 3, 4, 5]
}

我已经研究了聚合 API,但我不知道如何实现这一点,如果可能的话。我当然可以在代码中手动编译结果,但是我可以拥有数千个文档,并且以这种方式获得结果会更干净。

【问题讨论】:

    标签: arrays elasticsearch merge aggregate


    【解决方案1】:

    您可以将Scripted Metric Aggregationreduce_script 一起使用。

    设置一些测试数据:

    curl -XPUT http://localhost:9200/testing/foo/1 -d '{ "foo" : [1, 2, 3] }'
    curl -XPUT http://localhost:9200/testing/foo/2 -d '{ "foo" : [4, 5, 6] }'
    

    现在试试这个聚合:

    curl -XGET "http://localhost:9200/testing/foo/_search" -d'
    {
      "size": 0,
      "aggs": {
        "fooreduced": {
          "scripted_metric": {
            "init_script": "_agg[\"result\"] = []",
            "map_script":  "_agg.result.add(doc[\"foo\"].values)",
            "reduce_script": "reduced = []; for (a in _aggs) { for (entry in a) { word = entry.key; reduced += entry.value } }; return reduced.flatten().sort()"
    
          }
        }
      }
    }'
    

    调用将返回:

    {
      "took": 50,
      "timed_out": false,
      "_shards": {
        "total": 6,
        "successful": 6,
        "failed": 0
      },
      "hits": {
        "total": 2,
        "max_score": 0,
        "hits": []
      },
      "aggregations": {
        "fooreduced": {
          "value": [
            1,
            2,
            3,
            4,
            5,
            6
          ]
        }
      }
    }
    

    可能有一个没有.flatten() 的解决方案,但我不太喜欢 groovy(还)找到这样的解决方案。而且这个聚合的性能有多好我也说不准,你自己去测试吧。

    【讨论】:

      猜你喜欢
      • 2016-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      • 2020-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多