在elasticsearch中组合过滤器和must

Combining filter and must in elasticsearch

在 must 中添加查询过滤器与单独拥有查询过滤器和 must 有什么区别?

我需要对搜索应用过滤查询,但这两个查询中的任何一个对我来说都是一样的。我想知道有没有什么不同。

案例 1:

  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "field": {
              "value": "VALUE"
            }
          }
        },
        {
          "bool": {
            "filter": [
              {
                "script": {
                  "script": {
                    "source": """
                  return true;
                  
                """
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }

案例二:

  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "field": {
              "value": "VALUE"
            }
          }
        }
      ],
      "filter": [
              {
                "script": {
                  "script": {
                    "source": """
                  return true;
                  
                """
                  }
                }
              }
            ]
    }
  }

在我看来它们没有区别,但我需要参考。你好。

它们的工作方式完全相同,第二个是首选语法,因为它不像第一个那样嵌套并且更易于阅读。

两个查询将完全相同

请参阅有关 boolean query 的文档以了解有关您的结构的更多信息

must: The clause (query) must appear in matching documents and will contribute to the score.

filter: The clause (query) must appear in matching documents. However unlike must the score of the query will be ignored. Filter clauses are executed in filter context, meaning that scoring is ignored and clauses are considered for caching.

您的第一个查询的结构,其中组合了多个 bool 查询:

{
  "query": {
    "bool": {
      "must": [
        {
          "term": {},
          "bool": {
            "filter": {
              "script": {}
            }
          }
        }
      ]
    }
  }
}

包含单个 bool 查询的第二个查询的结构:

{
  "query": {
    "bool": {
      "must": [
        {
          "term": {}
        }
      ],
      "filter": [
        {
          "script": {}
        }
      ]
    }
  }
}

如您所见,在两个搜索查询中,只有同时满足术语查询和脚本查询条件时,文档才会匹配