gpt4 book ai didi

elasticsearch - Elasticsearch按数组字段中的对象中的多个字段过滤

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

目标是过滤具有多个价格的产品。

数据如下所示:

{
"name":"a",
"price":[
{
"membershipLevel":"Gold",
"price":"5"
},
{
"membershipLevel":"Silver",
"price":"50"
},
{
"membershipLevel":"Bronze",
"price":"100"
}
]
}

我想按 membershipLevelprice进行过滤。例如,如果我是白银成员(member)并且查询价格范围为0-10,则不应显示该产品,但是如果我是金牌成员(member),则应显示产品“a”。 Elasticsearch支持这种查询吗?

最佳答案

您需要为nested使用 price 数据类型,并为您的用例使用 nested query

请参阅以下映射,样本文档,查询和响应:

对应:

PUT my_price_index
{
"mappings": {
"properties": {
"name":{
"type":"text"
},
"price":{
"type":"nested",
"properties": {
"membershipLevel":{
"type":"keyword"
},
"price":{
"type":"double"
}
}
}
}
}
}

样本文件:
POST my_price_index/_doc/1
{
"name":"a",
"price":[
{
"membershipLevel":"Gold",
"price":"5"
},
{
"membershipLevel":"Silver",
"price":"50"
},
{
"membershipLevel":"Bronze",
"price":"100"
}
]
}

查询:
POST my_price_index/_search
{
"query": {
"nested": {
"path": "price",
"query": {
"bool": {
"must": [
{
"term": {
"price.membershipLevel": "Gold"
}
},
{
"range": {
"price.price": {
"gte": 0,
"lte": 10
}
}
}
]
}
},
"inner_hits": {} <---- Do note this.
}
}
}

上面的查询意味着,我想返回 price.price0 to 10中的 price.membershipLevel范围的所有文档作为 Gold

注意,我已经使用了 inner_hits。原因是尽管是嵌套文档,但ES作为响应将返回整个文档集,而不是仅返回适用于查询子句的特定文档。

为了找到匹配的确切嵌套文档,您需要使用 inner_hits

以下是响应的返回方式。

响应:
{
"took" : 128,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 1.9808291,
"hits" : [
{
"_index" : "my_price_index",
"_type" : "_doc",
"_id" : "1",
"_score" : 1.9808291,
"_source" : {
"name" : "a",
"price" : [
{
"membershipLevel" : "Gold",
"price" : "5"
},
{
"membershipLevel" : "Silver",
"price" : "50"
},
{
"membershipLevel" : "Bronze",
"price" : "100"
}
]
},
"inner_hits" : {
"price" : {
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 1.9808291,
"hits" : [
{
"_index" : "my_price_index",
"_type" : "_doc",
"_id" : "1",
"_nested" : {
"field" : "price",
"offset" : 0
},
"_score" : 1.9808291,
"_source" : {
"membershipLevel" : "Gold",
"price" : "5"
}
}
]
}
}
}
}
]
}
}

希望这可以帮助!

关于elasticsearch - Elasticsearch按数组字段中的对象中的多个字段过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60620921/

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