我对布尔查询中“应该”和“必须”的用法有点困惑。当 SHOULD 和 MUST 子句中有多个过滤器时,它们可以放在同一级别还是应该嵌套?
下面是我的数据和我测试的两个查询的简化版本,第一个失败,后者工作。在实际实践中,我有很多“必须”和“应该”的过滤器。
我开始相信,如果想要组合多个 SHOULD 和 MUST 过滤器,那么外部过滤器必须始终是 SHOULD。这是一个正确的假设吗?如果我想使用 MUST_NOT,它应该放在这个上下文中的哪里?
我的数据:
_index,_type,_id,_score,_source.id,_source.type,_source.valueType,_source.sentence,_source.location
"test","var","0","1","0","study","text","Lorem text is jumbled","spain"
"test","var","1","1","1","study","text","bla bla bla","spain"
"test","var","2","1","2","schema","decimal","ipsum","germany"
"test","var","3","1","3","study","integer","lorem","france"
Run Code Online (Sandbox Code Playgroud)
这是失败的查询:
{
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"bool": {
"must": {
"terms": {
"location": [
"germany"
]
}
},
"should": {
"terms": {
"valueType": [
"integer"
]
}
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的 WORKING 查询,返回 ID 2 和 3:
{
"query": {
"bool": {
"should": [
{
"terms": {
"location": [
"germany"
]
}
},
{
"bool": {
"must": [
{
"terms": {
"valueType": [
"integer"
]
}
}
]
}
}
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
非常感谢。
首先需要了解过滤器的含义。
复合过滤器:
must
子句是必需的(并且)
should
子句是可选的(或)
因此,在第一个块中,您正在签term
入must
(和)。所以这个词必须在结果集中。和 should(or) cond 2 可能会也可能不会在结果集中。
{
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"bool": {
"must": {
....... Cond 1
},
"should": {
....... Cond 2
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
在您的工作场景中,您正在查询工作,因为应该检查 Cond 1 或 Cond 2。
{
"query": {
"bool": {
"should": [ // OR
{
...... Cond 1
},
{
...... Cond 2
}
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14768 次 |
最近记录: |