【发布时间】:2015-09-26 16:49:40
【问题描述】:
我正在努力使用弹性搜索过滤器。我有一个看起来像这样的company_office 类型:
{
"company_office_id": 1,
"is_headquarters": true,
"company": {
"name": "Some Company Inc"
},
"attribute_values": [
{
"attribute_id": 1,
"attribute_value": "attribute 1 value",
},
{
"attribute_id": 2,
"attribute_value": "ABC",
},
{
"attribute_id": 3,
"attribute_value": "DEF",
},
{
"attribute_id": 3,
"attribute_value": "HIJ",
}
]
}
让我们假设 attribute_value 是 not_analyzed - 所以我可以完全匹配它。
现在我想过滤多个attribute_id 和value 字段的组合。在 SQL 中是这样的:
SELECT *
FROM CompanyOffice c
JOIN Attributes a --omitting the ON here, just assume the join is valid
WHERE
c.is_headquarters = true AND
(
(a.attribute_id=2 AND a.attribute_value IN ('ABC')) OR
(a.attribute_id=3 AND a.attribute_value IN ('DEF','HIJ'))
)
所以我需要过滤特定字段 + id/value 的多个组合。
这是我尝试过的查询:
{
"query" : {
"filtered" : {
"filter" : {
"bool" : {
"must" : [
{ "term": {"is_headquarters": true } },
{"bool": {
"must":[
{"term": {"attribute_values.attribute_id": 1}},
{"bool": { "should": [{"term": {"attribute_values.attribute_value": "HIJ"}}]}}
]
}}
]
}
}
}
}
}
即使 company_office 没有任何 1/'HIJ' 的 id/value 配对,此查询也会返回结果。我的想法是,因为这个 bool 过滤器位于父 must 部分内,所以所有项目都必须为真:
{"bool": {
"must":[
{"term": {"attribute_values.attribute_id": 1}},
{"bool": { "should": [{"term": {"attribute_values.attribute_value": "HIJ"}}]}}
]
}}
鉴于问题开头提供的数据样本,为什么该查询会返回结果?是否有不同的方式来编写过滤器并完成我想要做的事情?
非常感谢您的帮助!
【问题讨论】:
标签: elasticsearch