elasticsearch - ElasticSearch 查询不返回数组的完全匹配
问题描述
我有一个关于 Elasticsearch 数组查询的问题。在我的例子中,自定义属性的结构是一个对象数组,每个对象包含inner_name
和value
,值的类型是混合的(可以是字符串、数字、数组、Date..等),其中一种类型是多复选框,它应该将数组作为输入。映射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"
]
}
}
]
}
}
}
例如,它返回两个文档,它应该只返回第一个!我的查询有什么问题?有没有另一种方法来编写查询?
解决方案
如果您的任何值存在于文档中,则弹性搜索术语查询会尝试匹配任何值,请考虑使用运算符而OR
不是AND
您想要的运算符。有两种解决方案
- 在您的布尔必须查询中使用多个
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"
}
}
]
}
}
}
- 将匹配查询与运算符
AND
和whitespace
分析器一起使用。如果您的条款包含空格,这将不起作用
{
"query": {
"bool": {
"must": [
{
"match": {
"custom_attributes.attributes.inner_name": "attr2"
}
},
{
"match": {
"custom_attributes.attributes.value": {
"query": "val1 val2 val3 val4",
"operator": "and",
"analyzer": "whitespace"
}
}
}
]
}
}
}
推荐阅读
- html - 从 PDF 中的 HTML 背景颜色创建 PDF
- regex - 如何使用 Mule 中的表达式组件将以下 OBJECT(o) 替换为有效载荷中的空格?
- html - 为什么浏览器会在 svg 元素周围添加填充,我该如何防止它?
- bash - 将 TXT 文件读入变量失败
- python - 使用多索引 Pandas 移动行
- go - 使用 xml.NewDecoder(xmlFile) 在 Go/Golang 中解析大型 XML 文件时如何实现进度计数器?
- java - 如何使用 Java 时间库将符合 ISO 标准的字符串解析为日期
- r - 使用 R 中的递归将十进制转换为二进制
- python - 在 Azure 中存储服务主体凭据以使用 Python 对 Key Vault 进行身份验证
- selenium - 相机在 selenium 项目中并行打开的 2 个 chrome 浏览器中不起作用