您可以使用脚本化指标聚合 https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-scripted-metric-aggregation.html with a 减少脚本 https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-scripted-metric-aggregation.html#_scope_of_scripts.
设置一些测试数据:
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() http://docs.groovy-lang.org/latest/html/groovy-jdk/java/util/Collection.html,但我还不太热衷于寻找这样的解决方案。而且我不能说这个聚合的性能有多好,你必须自己测试一下。