Bool过滤器和SHOULD和MUST组合

时间:2014-11-03 13:14:57

标签: elasticsearch

我对bool查询中的用法应该有点混淆。当你在SHOULD和MUST子句中有几个过滤器时,它们可以放在同一级别还是应该嵌套?

下面是我的数据的简化版本以及我测试的两个查询,第一个是失败的,后者是失败的。在实际操作中,我必须有许多过滤器。

我开始相信,如果想要组合几个SHOULD和MUST过滤器,那么外层过滤器必须始终是应该的。这是正确的假设吗?如果我想使用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"

这是失败的查询:

{
  "query": {
    "filtered": {
      "query": {
        "match_all": {}
      },
      "filter": {
        "bool": {
          "must": {
            "terms": {
              "location": [
                "germany"
              ]
            }
          },
          "should": {
            "terms": {
              "valueType": [
                "integer"
              ]
            }
          }
        }
      }
    }
  }
}

这是我的WORKING查询返回ID 2和3:

{
  "query": {
    "bool": {
      "should": [
        {
          "terms": {
            "location": [
              "germany"
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "terms": {
                  "valueType": [
                    "integer"
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  }
}

非常感谢。

1 个答案:

答案 0 :(得分:0)

首先需要了解过滤器的含义。

复合过滤器:

must条款是必需的(和)
  should子句是可选的(或)

因此,在第一个区块中,您正在检查term中的must(和)。所以这个术语必须是结果集。并且(或)cond 2可能会或可能不会在结果集中。

{
   "query": {
      "filtered": {
         "query": {
            "match_all": {}
         },
         "filter": {
            "bool": {  
               "must": {
                   ....... Cond 1
               },
               "should": {
                   ....... Cond 2
               }
            }
         }
      }
   }
}

在您的工作场景中,您正在查询工作,因为应该检查Cond 1或Cond 2。

{
   "query": {
      "bool": {
         "should": [   // OR 
            {
              ...... Cond 1
            },
            {
              ...... Cond 2
            }
         ]
      }
   }
}