我已经在Elasticsearch嵌套数据类型(数组)中存储了一些值,但是没有使用键/值对。记录示例为:
{
"categories": [
"Category1",
"Category2"
],
"product_name": "productx"
}
现在,我想运行聚合查询以查找可用类别的唯一列表。但是我看到的所有示例都指向具有键/值的映射。有什么办法可以按原样使用上述架构,还是需要将架构更改为类似形式才能运行聚合查询?
{
"categories": [
{"name": "Category1"},
{"name": "Category2"}
],
"product_name": "productx"
}
最佳答案
关于JSON结构,您需要退后一步,确定是否需要list
或key-value
对。
在您的示例中,我认为您不需要key-value
对,但是如果您还需要categories
的更多属性,那么可能需要通过了解您的域来澄清它。
就聚合而言,据我所知,aggregations
可以在任何有效的JSON结构上运行。
对于您提到的数据,您可以使用以下aggregation
查询。另外,我假设这些字段的类型为keyword
。
汇总查询
POST <your_index_name>/_search
{
"size": 0,
"aggs": {
"myaggs": {
"terms": {
"size": 100,
"script": {
"inline": """
def myString = "";
def list = new ArrayList();
for(int i=0; i<doc['categories'].length; i++){
myString = doc['categories'][i] + ", " + doc['product'].value;
list.add(myString);
}
return list;
"""
}
}
}
}
}
聚集响应
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 0,
"hits": []
},
"aggregations": {
"myaggs": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "category1, productx",
"doc_count": 1
},
{
"key": "category2, productx",
"doc_count": 1
}
]
}
}
}
希望能帮助到你!
关于elasticsearch - Elasticsearch对嵌套列表中的值的聚合(数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53330971/