gpt4 book ai didi

Elasticsearch : filter on scripted sum of filtered nested field

转载 作者:行者123 更新时间:2023-12-02 23:27:23 24 4
gpt4 key购买 nike

我正在尝试使用 elasticsearch 做一些事情,但在任何地方都找不到答案。

得到一个嵌套对象产品:

 "products": {
"include_in_root": true,
"type": "nested",
"properties": {
"date": {
"format": "strict_date_optional_time||epoch_millis",
"type": "date"
},
"type": {
"index": "not_analyzed",
"type": "string"
},
"cat4": {
"index": "not_analyzed",
"type": "string"
},
"geo": {
"type": "geo_point"
},
"baseprice": {
"type": "long"
},
"cat2": {
"index": "not_analyzed",
"type": "string"
},
"cat3": {
"index": "not_analyzed",
"type": "string"
},
"feeltemp": {
"type": "long"
},
"cat1": {
"index": "not_analyzed",
"type": "string"
},
"price": {
"type": "double"
},
"qty": {
"index": "not_analyzed",
"type": "string"
},
"name": {
"index": "not_analyzed",
"type": "string"
},
"weather": {
"index": "not_analyzed",
"type": "string"
},
"id": {
"index": "not_analyzed",
"type": "string"
},
"stock": {
"type": "long"
},
"brand": {
"index": "not_analyzed",
"type": "string"
}
}
}

例如,我只想在 type='cartadd' 和 cat1="test"时查询它们。

问题,如果带有嵌套过滤器的查询:
{
"query": {
"bool": {
"filter": [
{
"nested": {
"path": "products",
"filter": {
"bool": {
"must": [
{
"script": {
"script": "sum=0;for(obj in _source.products) {sum = sum + 1 }; sum>=1;"
}
},
{
"term": {
"products.type": "view"
}
}
]
}
}
}
}
]
}
}
}

这不算什么。

如果我删除嵌套操作:
{
"query": {
"bool": {
"filter": {
"bool": {
"must": [
{
"script": {
"script": "sum=0;for(obj in _source.products) {if(obj.type=='cartadd') {sum = sum + obj.price }}; sum>=2;"
}
}
]
}
}
}
}
}

它可以工作并计算对象。但我不能再过滤嵌套对象了。

您是否看到,我在 groovy 脚本中添加了一个 if 条件,但是我可以动态添加更多条件。

有人知道我该怎么做吗?

非常感谢 !

最佳答案

您需要移动script nested 之外的过滤器查询,因为它在 products 上运行这是父文档的一个字段(不是嵌套的):

{
"query": {
"bool": {
"filter": [
{
"script": {
"script": "sum=0;for(obj in _source.products) {sum = sum + 1 }; sum>=1;"
}
},
{
"nested": {
"path": "products",
"filter": {
"term": {
"products.type": "view"
}
}
}
}
]
}
}
}

此外,一个好主意是添加一个名为 nbProducts 的新字段。在包含产品对象数量的父文档中。这将允许您摆脱该脚本并执行如下简单查询:
{
"query": {
"bool": {
"filter": [
{
"range": {
"nbProducts": {
"gte": 1
}
}
},
{
"nested": {
"path": "products",
"filter": {
"term": {
"products.type": "view"
}
}
}
}
]
}
}
}

关于 Elasticsearch : filter on scripted sum of filtered nested field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41260854/

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