如何在 Elasticsearch 中将 terms query 和 bool query 复合在一起

How to compound terms query and bool query together in Elasticsearch

最初,我会在 bool 查询中添加一个 filter。但是,当我转向 terms filter 时,documents 表示现在应该用 terms query 代替。所以我的理解是我们需要构造一个同时包含 terms querybool query 的复合查询。如果我是正确的,我应该如何编写查询?

注:我用elasticsearch的Python API.

现在有两种上下文:query context and filter context。查询上下文中的任何查询子句都会影响匹配文档的分数,即文档与查询的匹配程度,而过滤器上下文中的任何查询子句都会确定文档是否匹配并且不会影响分数。

所以在下面的查询中我标记了两个上下文:

{
  "query": { 
    "bool": { 
      "must": [
        { "match": { "field1":   "terms1"}},              <------query context
      ],
      "filter": [ 
        { "terms":  { "someId": [3242, 12343, 1234] }},   <-------inside filter block every query clause will act as filter (filter context)
      ]
    }
  }
}

因此,要将字词查询用作过滤器,您需要执行以下步骤:

  1. 创建布尔查询说 boolQuery
  2. 创建术语查询 termsQuery
  3. termsQuery 添加到 boolQuery 的过滤器。
  4. 设置boolQuery为查询。

翻译如下:

{
  "query": {
    "bool": {
      "filter": [
        {
          "terms": {
            "field1": ["terms1", "term2", "terms3"]
          }
        }
      ]
    }
  }
}