Ale*_*nko 5 concat aggregation elasticsearch
我有以下简单的映射:
"element": {
"dynamic": "false",
"properties": {
"id": { "type": "string", "index": "not_analyzed" },
"group": { "type": "string", "index": "not_analyzed" },
"type": { "type": "string", "index": "not_analyzed" }
}
}
Run Code Online (Sandbox Code Playgroud)
基本上,这是一种存储Group对象的方法:
{
id : "...",
elements : [
{id: "...", type: "..."},
...
{id: "...", type: "..."}
]
}
Run Code Online (Sandbox Code Playgroud)
我想找到多少个不同的组,它们共享同一组元素类型(有序的,包括重复的)。
一个明显的解决方案是将架构更改为:
"element": {
"dynamic": "false",
"properties": {
"group": { "type": "string", "index": "not_analyzed" },
"concatenated_list_of_types": { "type": "string", "index": "not_analyzed" }
}
}
Run Code Online (Sandbox Code Playgroud)
但是,由于要求,我们需要能够从(聚合)分组中排除某些类型:(
该文档的所有字段都是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
Run Code Online (Sandbox Code Playgroud)
在具有给定映射的Elastic中,过滤起来真的很容易,并且假设我们有一个简明的值,这也不是问题。不用说,总和汇总不适用于字符串。
我该如何工作?:)
谢谢!
最后,我通过脚本编写和更改映射解决了这个问题。
{
"mappings": {
"group": {
"dynamic": "false",
"properties": {
"id": { "type": "string", "index": "not_analyzed" },
"elements": { "type": "string", "index": "not_analyzed" }
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
由于某些原因,数组(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 ) ]}"
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果如下:
"aggregations" : {
"path" : {
"value" : {
"5639abfb5cba47087e8b457e" : 362,
"568bfc495cba47fc308b4567" : 3695,
"5666d9d65cba47701c413c53" : 14,
"5639abfb5cba47087e8b4571-5639abfb5cba47087e8b457b" : 1,
"570eb97abe529e83498b473d" : 1
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4515 次 |
| 最近记录: |