ElasticSearch(八)【过滤查询】

古城微笑少年丶 2024-04-06 10:35 164阅读 0赞

八、过滤查询


上一篇文章《ElasticSearch - 扩展词、停用词配置》

过滤查询,其实准确来说,ES中的查询操作分为2种:查询(query)过滤(filter)。查询即是之前提到的query查询,它 (查询)默认会计算每个返回文档的得分,然后根据得分排序。而过滤(filter)只会筛选出符合的文档,并不计算得分,而且它可以缓存文档。所以,单从性能考虑,过滤比查询更快。 换句话说,过滤适合在大范围筛选数据,而查询则适合精确匹配数据。一般应用时, 应先使用过滤操作过滤数据,然后使用查询匹配数据

在这里插入图片描述

注意

  • 在执行 filter 和 query 时,先执行 filter 在执行 query
  • Elasticsearch 会自动缓存经常使用的过滤器,以加快性能

常见过滤类型

  • term:单个关键词
  • terms:多个关键词
  • range:范围
  • exists:存在
  • ids:多个id

term类型

  1. GET /product/_search
  2. {
  3. "query": {
  4. "bool": {
  5. "must": [
  6. {
  7. "term": {
  8. "description": {
  9. "value": "blog"
  10. }
  11. }}
  12. ],
  13. "filter": [
  14. {
  15. "term":
  16. {
  17. "description": "blog"}
  18. }
  19. ]
  20. }
  21. }
  22. }

terms类型

  1. GET /product/_search
  2. {
  3. "query": {
  4. "bool": {
  5. "must": [
  6. {
  7. "match_all": {
  8. }
  9. }
  10. ],
  11. "filter": [
  12. {
  13. "terms": {
  14. "description": [
  15. "blog",
  16. "vinjcent"
  17. ]
  18. }
  19. }
  20. ]
  21. }
  22. }
  23. }

range类型

  1. GET /product/_search
  2. {
  3. "query": {
  4. "bool": {
  5. "must": [
  6. {
  7. "match_all": {
  8. }
  9. }
  10. ],
  11. "filter": [
  12. {
  13. "range": {
  14. "price": {
  15. "gte": 0,
  16. "lte": 20
  17. }
  18. }}
  19. ]
  20. }
  21. }
  22. }

exists类型,过滤存在指定字段,获取字段不为空的索引记录使用

  1. GET /product/_search
  2. {
  3. "query": {
  4. "bool": {
  5. "must": [
  6. {
  7. "match_all": {
  8. }
  9. }
  10. ],
  11. "filter": [
  12. {
  13. "exists": {
  14. # 存在某个字段
  15. "field": "aaa"
  16. }
  17. }
  18. ]
  19. }
  20. }
  21. }

ids类型,过滤含有指定字段的索引记录

  1. GET /product/_search
  2. {
  3. "query": {
  4. "bool": {
  5. "must": [
  6. {
  7. "term": {
  8. "description": {
  9. "value": "blog"
  10. }
  11. }
  12. }
  13. ],
  14. "filter": [
  15. {
  16. "ids": {
  17. "values": [
  18. "1","2"
  19. ]
  20. }
  21. }
  22. ]
  23. }
  24. }
  25. }

下一篇文章《ElasticSearch - SpringBoot整合》

发表评论

表情:
评论列表 (有 0 条评论,164人围观)

还没有评论,来说两句吧...

相关阅读