gpt4 book ai didi

elasticsearch - ElasticSearch查询未返回数组的完全匹配

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

我有一个关于Elasticsearch数组查询的问题。在我的情况下,自定义属性的结构是一个对象数组,每个对象包含inner_namevalue,值的类型混合(可以是字符串,数字,数组,Date..etc),并且其中一个类型是multi -checkbox,应将数组作为输入。映射custom_attributes如下:

"attributes" : {
"properties" : {
"_id" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"inner_name" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"value" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
},

我使用 mongoosastic将MongoDB索引到ES的位置,因此自定义属性的结构如下:
[
{
customer_name: "customerX",
"custom_attributes" : [
{
"group" : "xyz",
"attributes" : [
{
"inner_name" : "attr1",
"value" : 123,
},
{
"inner_name" : "attr2",
"value" : [
"Val1",
"Val2",
"Val3",
"Val4"
]
}
]
}
]
},
{
customer_name: "customerY",
"custom_attributes" : [
{
"group" : "xyz",
"attributes" : [
{
"inner_name" : "attr2",
"value" : [
"Val1",
"Val2"
]
}
]
}
]
}
]

我想执行一个查询,其中所有值都必须在数组中。但是,以下查询的问题在于,只要它包含数组中的任何值,它都会返回文档。这是查询:
{
"query": {
"bool": {
"must": [
{
"match": {
"custom_attributes.attributes.inner_name": "attr2"
}
},
{
"terms": {
"custom_attributes.attributes.value": [
"val1",
"val2",
"val3",
"val4"
]
}
}
]
}
}
}

例如,它返回两个文档,在这里它应该仅返回第一个!我的查询出了什么问题?还有另一种写查询的方法吗?

最佳答案

Elasticsearch字词查询会尝试匹配文档中是否存在您的任何值,请考虑将运算符设为OR而不是所需的AND。有两种解决方案

  • 在bool必须查询中使用多个term查询,这将提供所需的AND功能
  • {
    "query": {
    "bool": {
    "must": [
    {
    "match": {
    "custom_attributes.attributes.inner_name": "attr2"
    }
    },
    {
    "term": {
    "custom_attributes.attributes.value": "val1"
    }
    },
    {
    "term": {
    "custom_attributes.attributes.value": "val2"
    }
    },
    {
    "term": {
    "custom_attributes.attributes.value": "val3"
    }
    },
    {
    "term": {
    "custom_attributes.attributes.value": "val4"
    }
    }
    ]
    }
    }
    }
  • 将匹配查询与运算符ANDwhitespace分析器一起使用。如果您的字词包含空格
  • ,则 不会起作用
    {
    "query": {
    "bool": {
    "must": [
    {
    "match": {
    "custom_attributes.attributes.inner_name": "attr2"
    }
    },
    {
    "match": {
    "custom_attributes.attributes.value": {
    "query": "val1 val2 val3 val4",
    "operator": "and",
    "analyzer": "whitespace"
    }
    }
    }
    ]
    }
    }
    }

    关于elasticsearch - ElasticSearch查询未返回数组的完全匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59118140/

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