# 3.5.1.查询和过滤上下文

查询子句的行为取决于它是在查询上下文还是过滤器上下文中使用：

## 查询上下文

在查询上下文中使用的查询子句回答了问题“此文档与此查询子句匹配程度如何？”除了决定文档是否匹配之外，查询子句还计算一个得分（ `_score`）表示文档相对于其他文档的匹配程度。

每当将查询子句传递给 query 参数（例如，search API中的 query 参数）时，查询上下文都有效。

## 过滤上下文

在过滤器上下文中，查询子句回答问题“此文档是否匹配此查询子句？”答案是一个简单的是或否——不计算得分。 过滤器上下文主要用于过滤结构化数据，例如：

* 此 `timestamp`是否在2015年至2016年的范围内？
* status 字段是否设置为 "`published`"&#x20;

常用的过滤器将由Elasticsearch自动缓存，以加快性能。

无论什么情况下将查询子句传递给过滤器参数时，过滤器上下文都有效，例如：bool 查询中的`filter`或 must\_not 参数, constant\_score 查询中的过滤器参数，或聚合 filter。

下面是在搜索API中的查询和过滤器上下文中使用的查询子句的示例。 此查询将匹配满足以下所有条件的文档：

* title 字段包含单词 search
* content 字段包含单词 elasticsearch。
* status 字段包含 pulished 的确切字词。
* publish\_date 字段包含从2015年1月1日起的所有日期。

```
GET /_search
{
  "query": { ①
    "bool": { ②
      "must": [
        { "match": { "title":   "Search"        }}, ③
        { "match": { "content": "Elasticsearch" }}  ④
      ],
      "filter": [ ⑤
        { "term":  { "status": "published" }}, ⑥
        { "range": { "publish_date": { "gte": "2015-01-01" }}} ⑦
      ]
    }
  }
}
```

| ①   | query 参数表示查询上下文。                                      |
| --- | ----------------------------------------------------- |
| ②③④ | 在查询上下文中使用 bool 和两个匹配子句，这意味着它们用于评估每个文档匹配的程度。           |
| ⑤   | filter 参数指示过滤器上下文。                                    |
| ⑥⑦  | term 和 range 子句在过滤器上下文中使用。 他们将过滤掉不匹配的文档，但不会影响匹配文档的分数。 |

> 注意 :
>
> 在查询上下文中使用查询子句，用于影响匹配文档的分数（即文档匹配的程度）的条件，在过滤器上下文中使用所有其他查询子句。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xiaoxiami.gitbook.io/elasticsearch/ji-chu/35query-dsldslfang-shi-cha-8be229/cha-xun-he-guo-lv-shang-xia-wen.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
