Post filter

原文链接 : https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-post-filter.html

译文链接 : http://www.apache.wiki/pages/editpage.action?pageId=4883094

贡献者 : ping

在已经计算了聚合之后,post_filter 应用于搜索请求的最后的搜索命中。 其目的最好通过例子解释:

想象一下,你卖的有以下属性的衬衫:

  1. PUT /shirts
  2. {
  3. "mappings": {
  4. "item": {
  5. "properties": {
  6. "brand": { "type": "keyword"},
  7. "color": { "type": "keyword"},
  8. "model": { "type": "keyword"}
  9. }
  10. }
  11. }
  12. }
  13. PUT /shirts/item/1?refresh
  14. {
  15. "brand": "gucci",
  16. "color": "red",
  17. "model": "slim"
  18. }

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

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

  1. GET /shirts/_search
  2. {
  3. "query": {
  4. "bool": {
  5. "filter": [
  6. { "term": { "color": "red" }},
  7. { "term": { "brand": "gucci" }}
  8. ]
  9. }
  10. }
  11. }

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

这可以通过 terms aggregation 来完成:

  1. GET /shirts/_search
  2. {
  3. "query": {
  4. "bool": {
  5. "filter": [
  6. { "term": { "color": "red" }},
  7. { "term": { "brand": "gucci" }}
  8. ]
  9. }
  10. },
  11. "aggs": {
  12. "models": {
  13. "terms": { "field": "model" }
  14. }
  15. }
  16. }

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

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

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

  1. GET /shirts/_search
  2. {
  3. "query": {
  4. "bool": {
  5. "filter": {
  6. "term": { "brand": "gucci" }
  7. }
  8. }
  9. },
  10. "aggs": {
  11. "colors": {
  12. "terms": { "field": "color" }
  13. },
  14. "color_red": {
  15. "filter": {
  16. "term": { "color": "red" }
  17. },
  18. "aggs": {
  19. "models": {
  20. "terms": { "field": "model" }
  21. }
  22. }
  23. }
  24. },
  25. "post_filter": {
  26. "term": { "color": "red" }
  27. }
  28. }

|

|

  1. 主查询现在查找 Gucci 的所有衬衫,而不考虑颜色。

| |

|

  1. colors agg 返回 Gucci 的衬衫的流行颜色。

| |

|

  1. color_red agg 将模型子聚合限制为红色 Gucci 衬衫。

| |

| 最后,post_filter 从搜索命中中除去红色以外的颜色。 |