gpt4 book ai didi

elasticsearch - 如何聚合 Elasticsearch 中的动态字段?

转载 作者:行者123 更新时间:2023-11-29 02:45:27 25 4
gpt4 key购买 nike

我正在尝试通过 elasticsearch 聚合动态字段(不同文档不同)。文档如下:

[{
"name": "galaxy note",
"price": 123,
"attributes": {
"type": "phone",
"weight": "140gm"
}
},{
"name": "shirt",
"price": 123,
"attributes": {
"type": "clothing",
"size": "m"
}
}]

如您所见,文档中的属性会发生变化。我想要实现的是聚合这些属性的字段,如下所示:

{
aggregations: {
types: {
buckets: [{key: 'phone', count: 123}, {key: 'clothing', count: 12}]
}
}
}

我正在尝试 aggregation elasticsearch 的功能可以实现这一点,但无法找到正确的方法。是否可以通过聚合来实现?或者我应该开始查看 facets , 认为它似乎被贬低了。

最佳答案

您必须将属性定义为嵌套在映射中,并将单个属性值的布局更改为固定布局 { key: DynamicKey, value: DynamicValue }

PUT /catalog
{
"settings" : {
"number_of_shards" : 1
},
"mappings" : {
"article": {
"properties": {
"name": {
"type" : "string",
"index" : "not_analyzed"
},
"price": {
"type" : "integer"
},
"attributes": {
"type": "nested",
"properties": {
"key": {
"type": "string"
},
"value": {
"type": "string"
}
}
}
}
}
}
}

你可能会像这样索引你的文章

POST /catalog/article
{
"name": "shirt",
"price": 123,
"attributes": [
{ "key": "type", "value": "clothing"},
{ "key": "size", "value": "m"}
]
}

POST /catalog/article
{
"name": "galaxy note",
"price": 123,
"attributes": [
{ "key": "type", "value": "phone"},
{ "key": "weight", "value": "140gm"}
]
}

毕竟你可以聚合嵌套的属性

GET /catalog/_search
{
"query":{
"match_all":{}
},
"aggs": {
"attributes": {
"nested": {
"path": "attributes"
},
"aggs": {
"key": {
"terms": {
"field": "attributes.key"
},
"aggs": {
"value": {
"terms": {
"field": "attributes.value"
}
}
}
}
}
}
}
}

然后以稍微不同的形式为您提供您请求的信息

[...]
"buckets": [
{
"key": "type",
"doc_count": 2,
"value": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "clothing",
"doc_count": 1
}, {
"key": "phone",
"doc_count": 1
}
]
}
},
[...]

关于elasticsearch - 如何聚合 Elasticsearch 中的动态字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24800545/

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