【问题标题】:ElasticSearch - string concat aggregation?ElasticSearch - 字符串连接聚合?
【发布时间】:2016-09-24 22:38:04
【问题描述】:

我有以下简单的映射:

"element": {
  "dynamic": "false",
  "properties": {
    "id": { "type": "string", "index": "not_analyzed" },
    "group": { "type": "string", "index": "not_analyzed" },
    "type": { "type": "string", "index": "not_analyzed" }
  }
} 

这基本上是一种存储Group对象的方法:

{
  id : "...",
  elements : [
    {id: "...", type: "..."},
    ...
    {id: "...", type: "..."}
  ] 
}

我想知道有多少不同的组共享同一组元素类型(有序,包括重复)。

一个明显的解决方案是将架构更改为:

"element": {
  "dynamic": "false",
  "properties": {
    "group": { "type": "string", "index": "not_analyzed" },
    "concatenated_list_of_types": { "type": "string", "index": "not_analyzed" }
  }
} 

但是,由于要求,我们需要能够从 group by (aggregation) 中排除某些类型 :(

文档的所有字段都是 mongo id,所以在 SQL 中我会这样做:

SELECT COUNT(id), concat_value FROM (
    SELECT GROUP_CONCAT(type_id), group_id 
    FROM table
    WHERE type_id != 'some_filtered_out_type_id' 
    GROUP BY group_id
) T GROUP BY concat_value  

在具有给定映射的 Elastic 中,过滤掉它真的很容易,假设我们有一个连接值,计算它也不是问题。不用说,sum 聚合不适用于字符串。

我怎样才能让它工作? :)

谢谢!

【问题讨论】:

    标签: elasticsearch aggregation concat


    【解决方案1】:

    最后我通过scripting 和更改映射解决了这个问题。

    {
      "mappings": {
        "group": {
          "dynamic": "false",
          "properties": {
            "id": { "type": "string", "index": "not_analyzed" },
            "elements": { "type": "string", "index": "not_analyzed" }
          }
        }
      }
    }
    

    数组(ScriptDocValues.Strings)中的重复元素仍然存在一些问题,由于某种原因会去除重复数据,但这里有一个按字符串 concat 计数的聚合:

    {
      "aggs": {
        "path": {
          "scripted_metric": {
            "map_script": "key = doc['elements'].join('-'); _agg[key] = _agg[key] ? _agg[key] + 1 : 1",
            "combine_script": "_agg",
            "reduce_script": "_aggs.collectMany { it.entrySet() }.inject( [:] ) { result, e -> result << [ (e.key):e.value + ( result[ e.key ] ?: 0 ) ]}"
          }
        }
      }
    }
    

    结果如下:

      "aggregations" : {
        "path" : {
          "value" : {
            "5639abfb5cba47087e8b457e" : 362,
            "568bfc495cba47fc308b4567" : 3695,
            "5666d9d65cba47701c413c53" : 14,
            "5639abfb5cba47087e8b4571-5639abfb5cba47087e8b457b" : 1,
            "570eb97abe529e83498b473d" : 1
          }
        }
      }
    

    【讨论】:

    猜你喜欢
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 2011-02-20
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    相关资源
    最近更新 更多