多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# Post filter 原文链接 : [https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-post-filter.html](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-post-filter.html) 译文链接 : [http://www.apache.wiki/pages/editpage.action?pageId=4883094](http://www.apache.wiki/pages/editpage.action?pageId=488308) 贡献者 : [ping](/display/~wangyangting) 在已经计算了聚合之后,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" }} ] } } } ``` 但是,您还希望使用 **_faceted navigation_**  来显示用户可以单击的其他选项的列表。 也许你有一个模型字段,允许用户将搜索结果限制为红色的 Gucci T恤或连衣裙。 这可以通过 [`terms` aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html "Terms Aggregation") 来完成: ``` 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 从搜索命中中除去红色以外的颜色。 |