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"
}
想象一下,用户已经指定了两个过滤器:
color:red 和 brand:gucci.。您只想在搜索结果中显示Gucci制造的红色衬衫。通常你会用一个bool查询:
GET /shirts/_search
{
"query": {
"bool": {
"filter": [
{ "term": { "color": "red" }},
{ "term": { "brand": "gucci" }}
]
}
}
}
但是,您也可以使用多面导航来显示用户可以点击的其他选项的列表。也许你有一个model字段,允许用户将他们的搜索结果限制在红色的Gucci t-shirts或dress-shirts上。
这可以用术语聚合来完成:
GET /shirts/_search
{
"query": {
"bool": {
"filter": [
{ "term": { "color": "red" }},
{ "term": { "brand": "gucci" }}
]
}
},
"aggs": {
"models": {
"terms": { "field": "model" } 【1】
}
}
}
【1】返回Gucci最受欢迎的红色衬衫款式。
但也许您也想告诉用户Gucci衬衫有多少其他颜色。如果您只是在颜色字段中添加术语聚合,则只会返回颜色为红色,因为您的查询只返回Gucci的红色衬衫。
相反,您要在聚合期间包括所有颜色的衬衫,然后将颜色过滤器应用于搜索结果。这是post_filter的目的:
GET /shirts/_search
{
"query": {
"bool": {
"filter": {
"term": { "brand": "gucci" } 【1】
}
}
},
"aggs": {
"colors": {
"terms": { "field": "color" } 【2】
},
"color_red": {【3】
"filter": {
"term": { "color": "red" }
},
"aggs": {
"models": {
"terms": { "field": "model" }
}
}
}
},
"post_filter": { 【5】
"term": { "color": "red" }
}
}
【1】主要查询现在找到Gucci的所有衬衫,不管颜色如何。
【2】color聚合返回Gucci衬衫流行的颜色。
【3】color_red agg将模型子聚合限制为红色Gucci衬衫。
【4】最后,post_filter从搜索匹配中除去红色以外的颜色。