gpt4 book ai didi

elasticsearch - 如何在 Elasticsearch 中聚合数组中匹配的字段

转载 作者:行者123 更新时间:2023-12-03 02:03:05 28 4
gpt4 key购买 nike

我的对象带有名为属性的数组。属性本身就是对象,由字段属性和值(以及此处不重要的两个其他字段)组成。

我想找到某个属性的所有值。

我当前的方法是对properties.attribute使用过滤查询,然后对properties.value进行聚合。但是,这很短,因为聚合使用定义的所有属性,而不仅是使用搜索到的properties.attribute的属性。

有没有一种方法可以将聚合“空间”限制为仅properties.attribute匹配的属性?

为了完整起见,在这里找到很多值的curl调用,我只会对“farbe”(颜色)感兴趣:

curl -XGET 'http://localhost:9200/pwo/Product/_search?size=0&pretty=true' -d '{
"query": {
"filtered": {
"query": { "match_all" : { } },
"filter": {
"bool": {
"must": { "term": { "properties.attribute": "farbe" } }
}
}
}
},
"aggregations": {
"properties": {
"terms": { "field": "properties.value" }
}
}
}'

最佳答案

如果我正确理解的话,nested aggregationfilter aggregation的组合似乎可以满足您的要求。

不过,您必须使用nested type设置映射。

作为一个玩具示例,我建立了一个简单的索引,如下所示:

PUT /test_index
{
"settings": {
"number_of_shards": 1
},
"mappings": {
"doc": {
"properties": {
"properties": {
"type": "nested",
"properties": {
"attribute": {
"type": "string"
},
"value": {
"type": "string"
}
}
}
}
}
}
}

(请注意,这有点令人困惑,因为在这种情况下,“属性”既是关键字又是属性定义。)

现在,我可以索引一些文档:
POST /test_index/doc/_bulk
{"index":{"_id":1}}
{"properties":[{"attribute":"lorem","value":"Donec a diam lectus."},{"attribute":"ipsum","value":"Sed sit amet ipsum mauris."}]}
{"index":{"_id":2}}
{"properties":[{"attribute":"dolor","value":"Donec et mollis dolor."},{"attribute":"sit","value":"Donec sed odio eros."}]}
{"index":{"_id":3}}
{"properties":[{"attribute":"amet","value":"Vivamus fermentum semper porta."}]}

然后,我可以对 "properties.value"过滤的 "properties.attribute"进行汇总,如下所示:
POST /test_index/_search?search_type=count
{
"aggs": {
"nested_properties": {
"nested": {
"path": "properties"
},
"aggs": {
"filtered_by_attribute": {
"filter": {
"terms": {
"properties.attribute": [
"lorem",
"amet"
]
}
},
"aggs": {
"value_terms": {
"terms": {
"field": "properties.value"
}
}
}
}
}
}
}
}

在这种情况下返回:
{
"took": 3,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"failed": 0
},
"hits": {
"total": 3,
"max_score": 0,
"hits": []
},
"aggregations": {
"nested_properties": {
"doc_count": 5,
"filtered_by_attribute": {
"doc_count": 2,
"value_terms": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "a",
"doc_count": 1
},
{
"key": "diam",
"doc_count": 1
},
{
"key": "donec",
"doc_count": 1
},
{
"key": "fermentum",
"doc_count": 1
},
{
"key": "lectus",
"doc_count": 1
},
{
"key": "porta",
"doc_count": 1
},
{
"key": "semper",
"doc_count": 1
},
{
"key": "vivamus",
"doc_count": 1
}
]
}
}
}
}
}

这是我一起使用的代码:

http://sense.qbox.io/gist/1e0c58aae54090fadfde8856f4f6793b68de0167

关于elasticsearch - 如何在 Elasticsearch 中聚合数组中匹配的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30055958/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com