filter 和 query 示例
PUT /employee/_doc/1
{
"address": {
"country": "china",
"province": "jiangsu",
"city": "nanjing"
},
"name": "tom",
"age": 30,
"join_date": "2016-01-01"
}
PUT /employee/_doc/2
{
"address": {
"country": "china",
"province": "shanxi",
"city": "xian"
},
"name": "marry",
"age": 35,
"join_date": "2015-01-01"
}
搜索请求:年龄必须大于等于 30,同时 join_date 必须是 2016-01-01
GET /employee/_search
{
"query": {
"bool": {
"must": [
{
"match": {"join_date": "2016-01-01"}
}
],
"filter": {
"range": {
"age": {"gte": 30}
}
}
}
}
}
{
"took" : 141,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "employee",
"_type" : "_doc",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"address" : {
"country" : "china",
"province" : "jiangsu",
"city" : "nanjing"
},
"name" : "tom",
"age" : 30,
"join_date" : "2016-01-01"
}
}
]
}
}
filter 与 query 对比大揭秘
filter:仅仅只是按照搜索条件过滤出需要的数据而已,比计算任何相关度分数,对相关度没有任何影响
query: 会计算每个 document 相对于搜索条件的相关度,并按照相关度进行排序
一般来说,如果是在进行搜索,需要将最匹配搜索条件的数据先返回,那么用 query。如果只是要根据一些条件筛选出一部分数据,不关注其排序,那么用 filter。