gpt4 book ai didi

elasticsearch - 如何过滤应查询的嵌套对象?

转载 作者:行者123 更新时间:2023-12-03 00:53:38 24 4
gpt4 key购买 nike

我的映射如下,我正在做 bool(boolean) 查询名称和其他属性,如下所示,但是我需要的是我想在响应时按CustomerId过滤CustomerPrices。
每个产品都有相同的CustomerId,以便进行扩展;

product1 -CustomerPrice( CustomerId :1234 -Price:4) 
CustomerPrice( CustomerId :567-Price:5)
.
.
Product2 - CustomerPrice(CustomerId :1234 -Price:8)
CustomerPrice(CustomerId :567-Price:10)
.
.

因此,据此,当我查询Product1时,响应应该仅具有customerId的customerId:1234
{
"Product": {
"properties": {
"CustomerPrices": {
"type": "nested",
"properties": {
"Price": {
"store": true,
"type": "float"
},
"CustomerId": {
"type": "integer"
}
}
},
"Name": {
"index": "not_analyzed",
"store": true,
"type": "string"
}
}
}
}

我尝试了以下查询,但这并未过滤嵌套对象。我猜它会过滤产品对象,因为所有产品都有customerId:1234
   "query":{
"bool":{
"should":[
{
"multi_match":{
"type":"best_fields",
"query":"product 1",
"fields":[
"Name^7"]
}
},
{
"multi_match":{
"type":"best_fields",
"query":"product 1",
"operator":"and",
"fields":[
"Code^10",
"ShortDescription^6"]
}
},
{
"nested":{
"query":{
"term":{
"CustomerPrices.CustomerId":{
"value":1234
}
}
},
"path":"CustomerPrices"
}
}]
}
},

最佳答案

我花了一些时间在您的问题上,因为这很有趣,这是如何实现的,而我目前发现的唯一解决方案是依赖inner_hits,它提供了匹配所在的确切嵌套对象。我还停用了不再使用的_source。

因此,考虑到您的映射并拥有2种产品,例如:

PUT product/Product/product1
{
"CustomerPrices": [
{
"CustomerId": 1234,
"Price": 4
},
{
"CustomerId": 567,
"Price": 5
}
],
"Name": "John"
}

PUT product/Product/product2
{
"CustomerPrices": [
{
"CustomerId": 1234,
"Price": 8
},
{
"CustomerId": 567,
"Price": 10
}
],
"Name": "Bob"
}

运行以下查询时:(必须用于查看1个结果,也应使用)
GET product/_search
{
"_source": false,
"query": {
"bool": {
"must": [
{ "match": { "Name": "Bob"}}
],
"filter": [
{
"nested" : {
"path" : "CustomerPrices",
"score_mode" : "avg",
"query" : {
"bool" : {
"should" : [
{ "match" : {"CustomerPrices.CustomerId" : 1234}}
]
}
},
"inner_hits": {}
}
}
]
}
}
}

我能够得到结果,其中仅显示ID为1234的客户的“价格”:
{
"took": 5,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 0.2876821,
"hits": [
{
"_index": "product",
"_type": "Product",
"_id": "product2",
"_score": 0.2876821,
"inner_hits": {
"CustomerPrices": {
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "product",
"_type": "Product",
"_id": "product2",
"_nested": {
"field": "CustomerPrices",
"offset": 0
},
"_score": 1,
"_source": {
"CustomerId": 1234,
"Price": 8
}
}
]
}
}
}
}
]
}
}

仅拥有匹配的嵌套对象,找不到返回文档部分结果的正式方法。也许我们需要告知Elasticsearch家伙要考虑一些后续版本的内容。希望对您有帮助。

关于elasticsearch - 如何过滤应查询的嵌套对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48750696/

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