一、基础知识
有2种方式过滤查询结果
- 用带filter语句的boolean查询
对搜索结果和聚合同时生效 - 使用post-filter
只对搜索结果生效,不对聚合生效
查询使用文档数据在文章末尾
二、查询演示
- 2.1 boolean filter search
参数
{
"query": {
"bool": {
"filter": [
{
"term": {
"color": "red"
}
},
{
"term": {
"brand": "dior"
}
}
]
}
},
"aggs": {
"models": {
"terms": {
"field": "model"
}
}
}
}
响应(hits和聚合中的文档数量一致)
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 3,
"relation": "eq"
},
"max_score": 0,
"hits": [
{
"_index": "shirt",
"_id": "2",
"_score": 0,
"_source": {
"brand": "dior",
"color": "red",
"model": "cillum"
}
},
{
"_index": "shirt",
"_id": "5",
"_score": 0,
"_source": {
"brand": "dior",
"color": "red",
"model": "Jimmy"
}
},
{
"_index": "shirt",
"_id": "6",
"_score": 0,
"_source": {
"brand": "dior",
"color": "red",
"model": "Toom"
}
}
]
},
"aggregations": {
"models": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "Jimmy",
"doc_count": 1
},
{
"key": "Toom",
"doc_count": 1
},
{
"key": "cillum",
"doc_count": 1
}
]
}
}
}
- 2.2 post_filter search
参数
{
"query": {
"bool": {
"filter": {
"term": { "brand": "dior" }
}
}
},
"aggs": {
"colors": {
"terms": { "field": "color" }
}
},
"post_filter": {
"term": { "color": "red" }
}
}
响应(聚合中显示有4个文档,hits被过滤掉了一个)
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 3,
"relation": "eq"
},
"max_score": 0,
"hits": [
{
"_index": "shirt",
"_id": "2",
"_score": 0,
"_source": {
"brand": "dior",
"color": "red",
"model": "cillum"
}
},
{
"_index": "shirt",
"_id": "5",
"_score": 0,
"_source": {
"brand": "dior",
"color": "red",
"model": "Jimmy"
}
},
{
"_index": "shirt",
"_id": "6",
"_score": 0,
"_source": {
"brand": "dior",
"color": "red",
"model": "Toom"
}
}
]
},
"aggregations": {
"colors": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "red",
"doc_count": 3
},
{
"key": "greed",
"doc_count": 1
}
]
}
}
}
三、测试数据
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 6,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "shirt",
"_id": "2",
"_score": 1,
"_source": {
"brand": "dior",
"color": "red",
"model": "cillum"
}
},
{
"_index": "shirt",
"_id": "3",
"_score": 1,
"_source": {
"brand": "gucci",
"color": "yellow",
"model": "Excepteur ullamco"
}
},
{
"_index": "shirt",
"_id": "4",
"_score": 1,
"_source": {
"brand": "gucci",
"color": "gray",
"model": "ut sit ad dolore magna"
}
},
{
"_index": "shirt",
"_id": "1",
"_score": 1,
"_source": {
"brand": "dior",
"color": "greed",
"model": "culpa qui do non"
}
},
{
"_index": "shirt",
"_id": "5",
"_score": 1,
"_source": {
"brand": "dior",
"color": "red",
"model": "Jimmy"
}
},
{
"_index": "shirt",
"_id": "6",
"_score": 1,
"_source": {
"brand": "dior",
"color": "red",
"model": "Toom"
}
}
]
}
}