49.filter、query比较

主要知识点

1filterquery用在同一次查询中的语法

2、filter与query使用场景对比

3、二都的性能比较

   

一、filterquery示例

1、先准备数据

PUT /company/employee/1

{

"address": {

"country": "china",

"province": "guangdong",

"city": "guangzhou"

},

"name": "jack",

"age": 27,

"join_date": "2017-01-01"

}

PUT /company/employee/2

{

"address":{

"conutry":"china",

"province":"shichuan",

"city":"chendu"

},

"name":"tom",

"age":32,

"join_date":"2017-01-01"

}

   

PUT /company/employee/3

{

"address":{

"conutry":"china",

"province":"shichuan",

"city":"wenjiang"

},

"name":"lili",

"age":27,

"join_date":"2016-01-01"

}

   

2、搜索请求:

年龄必须大于等于30,同时join_date必须是2017-01-01

   

3、书写搜索语句:

GET /company/employee/_search

{

"query": {

"bool": {

"must": [

{"match": {

"join_date": "2017-01-01"

}}

],

"filter": {

"range": {

"age": {

"gt": 30

}

}

}

}

}

}

执行结果:

{

"took": 40,

"timed_out": false,

"_shards": {

"total": 5,

"successful": 5,

"failed": 0

},

"hits": {

"total": 1,

"max_score": 1,

"hits": [

{

"_index": "company",

"_type": "employee",

"_id": "2",

"_score": 1,

"_source": {

"address": {

"conutry": "china",

"province": "shichuan",

"city": "chendu"

},

"name": "tom",

"age": 32,

"join_date": "2017-01-01"

}

}

]

}

}

二、filterquery使用场景对比

   

1filter,仅仅只是按照搜索条件过滤出需要的数据而已,不计算任何相关度分数,搜索结果的相关度对filter手结果没有任何影响,query,会去计算每个document相对于搜索条件的相关度,并按照相关度进行排序。

2、一般来说,如果在进行搜索时,需要将最匹配搜索条件的数据先返回(对相关度有要求),那么用query;如果只是要根据一些条件筛选出一部分数据,不关注其排序,那么用filter

3、在实际使用过程中,一般是querryfilter结合使用,先用query搜索出数据并按相关度返回,用filter进行过渡,对于一部分搜索条件,希望越符合这些搜索条件的document越排在前面返回,那么这些搜索条件要放在query中;对于另一部分搜索条件,如果不希望这些搜索条件来影响document排序,那么就放在filter中。

   

三、filterquery性能对比

1filter,不需要计算相关度分数,不需要按照相关度分数进行排序,同时还有内置的自动cache最常使用filter的数据的方法,性能较query

2query,相反,要计算相关度分数,按照分数进行排序,而且无法cache结果,性能较低。

原文地址:https://www.cnblogs.com/liuqianli/p/8471420.html