gpt4 book ai didi

Elasticsearch 。具有重复值的嵌套字段的术语聚合

转载 作者:行者123 更新时间:2023-12-02 22:38:02 26 4
gpt4 key购买 nike

我对 Elasticsearch 中的嵌套聚合有一些疑问。我有嵌套字段的映射:

POST my_index/ my_type / _mapping
{
"properties": {
"name": {
"type": "keyword"
},
"nested_fields": {
"type": "nested",
"properties": {
"key": {
"type": "keyword"
},
"value": {
"type": "keyword"
}
}
}
}
}

然后我将一个文档添加到索引中:

POST my_index/ my_type
{
"name":"object1",
"nested_fields":[
{
"key": "key1",
"value": "value1"

},
{
"key": "key1",
"value": "value2"
}
]
}

如您所见,在我的嵌套数组中我有两个项目,它们具有相似的 key 字段,但不同的 value 字段。然后我想做这样的查询:

GET / my_index / my_type / _search
{
"query": {
"nested": {
"path": "nested_fields",
"query": {
"bool": {
"must": [
{
"term": {
"nested_fields.key": {
"value": "key1"
}
}
},
{
"terms": {
"nested_fields.value": [
"value1",
"value2"
]
}
}
]
}
}
}
},
"aggs": {
"agg_nested_fields": {
"nested": {
"path": "nested_fields"
},
"aggs": {
"agg_nested_fields_key": {
"terms": {
"field": "nested_fields.key",
"size": 10
}
}
}
}
}
}

如您所见,我想找到所有文档,这些文档在 nested_field 数组中至少有一个对象,并且 key 属性等于 key1 和提供的值之一(value1value2)。然后我想按 nested_fields.key 对创建的文档进行分组。但是我有这样的 react

{
"took": 13,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 0.87546873,
"hits": [
{
"_index": "my_index",
"_type": "my_type",
"_id": "AVuLNXxiryKmA7VEwOfV",
"_score": 0.87546873,
"_source": {
"name": "object1",
"nested_fields": [
{
"key": "key1",
"value": "value1"
},
{
"key": "key1",
"value": "value2"
}
]
}
}
]
},
"aggregations": {
"agg_nested_fields": {
"doc_count": 2,
"agg_nested_fields_key": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "key1",
"doc_count": 2
}
]
}
}
}
}

正如您从响应中看到的那样,我命中了一次(这是正确的),但是该文档在聚合中被计算了两次(参见 doc_count: 2),因为它有两个项目带有 ' nested_fields 数组中的 key1' 值。如何在聚合中获得正确的计数?

最佳答案

您将不得不使用 reverse_nested嵌套聚合内的 aggs 以返回根文档的聚合计数。

{
"query": {
"nested": {
"path": "nested_fields",
"query": {
"bool": {
"must": [{
"term": {
"nested_fields.key": {
"value": "key1"
}
}
},
{
"terms": {
"nested_fields.value": [
"value1",
"value2"
]
}
}
]
}
}
}
},
"aggs": {
"agg_nested_fields": {
"nested": {
"path": "nested_fields"
},
"aggs": {
"agg_nested_fields_key": {
"terms": {
"field": "nested_fields.key",
"size": 10
},
"aggs": {
"back_to_root": {
"reverse_nested": {
"path": "_source"
}
}
}
}
}
}
}
}

关于 Elasticsearch 。具有重复值的嵌套字段的术语聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43519258/

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