Elasticsearch 聚合嵌套列表(数组)中的值
Elasticsearch aggregation on values in nested list (array)
我在 Elasticsearch 嵌套数据类型(数组)中存储了一些值,但没有使用 key/value 对。示例记录为:
{
"categories": [
"Category1",
"Category2"
],
"product_name": "productx"
}
现在我想 运行 聚合查询以找出可用类别的唯一列表。但是我看到的所有示例都指向具有 key/value 的映射。有什么方法可以按原样使用上面的模式,或者我是否需要将我的模式更改为这样的 运行 聚合查询
{
"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 嵌套数据类型(数组)中存储了一些值,但没有使用 key/value 对。示例记录为:
{
"categories": [
"Category1",
"Category2"
],
"product_name": "productx"
}
现在我想 运行 聚合查询以找出可用类别的唯一列表。但是我看到的所有示例都指向具有 key/value 的映射。有什么方法可以按原样使用上面的模式,或者我是否需要将我的模式更改为这样的 运行 聚合查询
{
"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
}
]
}
}
}
希望对您有所帮助!