ElasticSearch - 字符串连接聚合?

ElasticSearch - string concat aggregation?

我有以下简单映射:

"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" }
  }
} 

但是,由于要求,我们需要能够从分组(聚合)中排除某些类型:(

文档的所有字段都是 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 中,它很容易过滤掉,假设我们有一个连接值,计算起来也不成问题。不用说,总和聚合不适用于字符串。

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

谢谢!

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

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

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

{
  "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
      }
    }
  }