2016-09-23 166 views
3

我有以下简单的映射:ElasticSearch - 字符串concat聚合?

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

但是,由于要求,我们需要能够通过(聚集):(

从组中排除某些类型该文件的所有字段都蒙戈的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 

弹性与给定的映射它真的很容易过滤掉,它也不是一个问题算一个假设我们有一个分值。不用说,总和聚合不适用于字符串。

我该如何得到这个工作? :)

谢谢!

回答

1

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

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

还存在一些问题,由于某种原因在数组重复的元素(ScriptDocValues.Strings)剔除了DUP的,但在这里是通过字符串连接计数聚合:

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