gpt4 book ai didi

elasticsearch - ElasticSearch-筛选,分组并计算每个组的结果

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

我是ElasticSearch的新手,需要帮助解决以下问题:

我有一组包含多个产品的文档。我想通过“Apple”过滤产品属性product_brand并获取与过滤器匹配的产品数量。但是,结果应按文档ID分组,该ID也是文档本身的一部分(test_id)。

示例文件:

"test" : {
"test_id" : 19988,
"test_name" : "Test",
},
"products" : [
{
"product_id" : 1,
"product_brand" : "Apple"
},
{
"product_id" : 2,
"product_brand" : "Apple"
},
{
"product_id" : 3,
"product_brand" : "Samsung"
}
]

结果应为:
{
"key" : 19988,
"count" : 2
},

在SQL中,它看起来近似如下:
SELECT test_id, COUNT(product_id) 
FROM `test`
WHERE product_brand = 'Apple'
GROUP BY test_id;

我该如何实现?

最佳答案

我认为这应该使您更接近:

GET /test/_search
{
"_source": {
"includes": [
"test.test_id",
"_score"
]
},
"query": {
"function_score": {
"query": {
"match": {
"products.product_brand.keyword": "Apple"
}
},
"functions": [
{
"script_score": {
"script": {
"source": "def matches=0; def products = params['_source']['products']; for(p in products){if(p.product_brand == params['brand']){matches++;}} return matches;",
"params": {
"brand": "Apple"
}
}
}
}
]
}
}
}

这种方法使用了function_score,但是如果您希望获得不同的评分,也可以将其应用于脚本字段。上面的内容仅适用于带有子产品对象且品牌文字完全设置为“Apple”的文档。

您只需要控制两个apples实例的输入即可。或者,您可以对function_score查询中的所有内容进行匹配,并仅关注分数。您的输出可能如下所示:
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 2,
"hits": [
{
"_index": "test",
"_type": "doc",
"_id": "AV99vrBpgkgblFY6zscA",
"_score": 2,
"_source": {
"test": {
"test_id": 19988
}
}
}
]
}
}

我使用的索引中的映射如下所示:
{
"test": {
"mappings": {
"doc": {
"properties": {
"products": {
"properties": {
"product_brand": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"product_id": {
"type": "long"
}
}
},
"test": {
"properties": {
"test_id": {
"type": "long"
},
"test_name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
}
}
}
}
}

关于elasticsearch - ElasticSearch-筛选,分组并计算每个组的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47080712/

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