简介

es所有查询会触发相关度计算, 对于那些不需要相关度得分的场景下. es以过滤器的形式提供另一种查询.
过滤器类似查询, 但是他们更快, 主要有以下原因

  • 过滤器不会计算相关度的得分,所以它们在计算上更快一些。
  • 过滤器可以被缓存到内存中,这使得在重复的搜索查询上,其要比相应的查询快出许多。

可以将一个查询(像是match_all,match,bool等)和一个过滤器结合起来。我们 以范围过滤器为例,它允许我们通过一个区间的值来过滤文档这通常被用在数字和日期的过滤上。 下面这个例子使用一个被过滤的查询,其返回price值是在200到1000之间(闭区间)的书。

  1. POST /book/_search
  2. {
  3. "query": {
  4. "bool": {
  5. "must": {
  6. "match_all": {}
  7. },
  8. "filter": {
  9. "range": {
  10. "price": {
  11. "gte": 200,
  12. "lte": 1000
  13. }
  14. }
  15. }
  16. }
  17. }
  18. }
  19. POST /book/_search
  20. {
  21. "query": {
  22. "bool": {
  23. "must": {
  24. "match_all": {}
  25. },
  26. "filter": {
  27. "term": {
  28. "price": "320.45"
  29. }
  30. }
  31. }
  32. }
  33. }

上面的例子,被过滤的查询包含一个match_all查询(查询部分)和一个过滤器(filter部分)。
我们可以在查询部分中放入其他查询,在filter部分放入其它过滤器

filter和bool过滤查询

  1. POST /products/_bulk
  2. {"index":{"_id":1}}
  3. {"price":10,"productID":"SD1002136"}
  4. {"index":{"_id":2}}
  5. {"price":20,"productID":"SD2678421"}
  6. {"index":{"_id":3}}
  7. {"price":30,"productID":"SD8897573"}
  8. {"index":{"_id":4}}
  9. {"price":30,"productID":"SD4535233"}
  1. select product from products where (price = 20 or productID= "SD1002136") and (price != 30);
  2. # 查询价格等于20的或者productIDSD1002136的商品,排除价格30元的

类似的,elasticsearch也有and,or,not这样的组合条件的查询方式
格式如下

  1. {
  2. "bool": {
  3. "must":[],
  4. "should":[],
  5. "must_not":[],
  6. }
  7. }

must条件必须满足,相当于and
should:条件可以满足也可以不满足,相当于or
must_not:条件不需要,相当于not

  1. GET /products/_search
  2. {
  3. "query": {
  4. "bool": {
  5. "filter": {
  6. "bool": {
  7. "should": [
  8. {"term": {"price": 20}},
  9. {"term": {"productID": "SD1002136"}}
  10. ],
  11. "must_not": {
  12. "term": {"price": 30}
  13. }
  14. }
  15. }
  16. }
  17. }
  18. }

范围查询

  1. gt > 大于
  2. lt < 小于
  3. gte >= 大于等于
  4. lte <= 小于等于
  5. # formto也行
  6. POST /book/_search
  7. {
  8. "query": {
  9. "bool": {
  10. "must": {
  11. "match_all": {}
  12. },
  13. "filter": {
  14. "range": {
  15. "price": {
  16. "from": 200,
  17. "to": 1000
  18. }
  19. }
  20. }
  21. }
  22. }
  23. }

嵌套查询

  1. GET /book/_search
  2. {
  3. "query": {
  4. "bool": {
  5. "filter": {
  6. "bool": {
  7. "should": [
  8. {"term": {"price": 320.45}},
  9. { "bool": {
  10. "must": [
  11. {"term": {"name": "solr"}}
  12. ]
  13. }}
  14. ]
  15. }
  16. }
  17. }
  18. }
  19. }