> For the complete documentation index, see [llms.txt](https://xiaoxiami.gitbook.io/elasticsearch/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://xiaoxiami.gitbook.io/elasticsearch/ji-chu/33-apis/343sou-suo-apis-search-apis/request-body-searchwei-wan-621029/post-filter.md).

# Post filter

在已经计算了聚合之后，post\_filter 应用于搜索请求的最后的搜索命中。 其目的最好通过例子解释：

想象一下你正在出售的衬衫,有以下属性:

```
PUT /shirts
{
    "mappings": {
        "item": {
            "properties": {
                "brand": { "type": "keyword"},
                "color": { "type": "keyword"},
                "model": { "type": "keyword"}
            }
        }
    }
}

PUT /shirts/item/1?refresh
{
    "brand": "gucci",
    "color": "red",
    "model": "slim"
}
```

想象一下，用户已经指定了两个过滤器：

颜色：红色，品牌：gucci 。 你只想在搜索结果中显示 Gucci 制作的红色衬衫。 通常你会使用布尔查询：

```
GET /shirts/_search
{
  "query": {
    "bool": {
      "filter": [
        { "term": { "color": "red"   }},
        { "term": { "brand": "gucci" }}
      ]
    }
  }
}
```

但是，您还希望使&#x7528;***faceted navigation***&#x6765;显示用户可以单击的其他选项的列表。 也许你有一个模型字段，允许用户将搜索结果限制为红色的 Gucci T恤或连衣裙。

这可以通过 [`terms` aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html)来完成：

```
GET /shirts/_search
{
  "query": {
    "bool": {
      "filter": [
        { "term": { "color": "red"   }},
        { "term": { "brand": "gucci" }}
      ]
    }
  },
  "aggs": {
    "models": {
      "terms": { "field": "model" } ①
    }
  }
}
```

| ① | 返回 Gucci 最受欢迎的红色衬衫款式。 |
| - | --------------------- |

但也许你也想告诉用户有多少 Gucci 衬衫可用其他颜色。 如果只是在颜色字段上添加术语聚合，则只会返回红色，因为您的查询只返回 Gucci 的红色衬衫。

相反，您希望在聚合期间包括所有颜色的衬衫，然后仅将颜色过滤器应用于搜索结果。 这是 post\_filter 的目的：

```
GET /shirts/_search
{
  "query": {
    "bool": {
      "filter": {
        "term": { "brand": "gucci" } ①
      }
    }
  },
  "aggs": {
    "colors": {
      "terms": { "field": "color" } ②
    },
    "color_red": {
      "filter": {
        "term": { "color": "red" } ③
      },
      "aggs": {
        "models": {
          "terms": { "field": "model" } ④
        }
      }
    }
  },
  "post_filter": {
    "term": { "color": "red" } ⑤
  }
}
```

| ①  | 主查询现在查找 Gucci 的所有衬衫，而不考虑颜色。          |
| -- | ------------------------------------ |
| ②  | colors agg 返回 Gucci 的衬衫的流行颜色。        |
| ③④ | color\_red agg 将模型子聚合限制为红色 Gucci 衬衫。 |
| ⑤  | 最后，post\_filter 从搜索命中中除去红色以外的颜色。     |
