ElasticSearch--过滤查询

过滤查询

简介

准确来说,ES的查询操作分为2种:查询(query)过滤(filter)

  • 查询就是我们之前用的query查询,它(查询)默认会计算每个返回文档的得分,然后根据得分排序。
  • 过滤查询:先筛选出符合条件的文档,并且不计算得分,而且它可以缓存文档。

应用场景:

  • 过滤适合用在大范围筛选数据,而查询则适合精确匹配数据。
  • 一般情况下,我们应该先使用过滤操作过滤掉一部分数据,然后使用查询去精准匹配数据,提高查询效率

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vcvkdWGm-1655972090887)(ElasticSearch.assets/image-20211101113527794.png)]

使用

  • 过滤查询必须配合bool查询使用
GET /ems/emp/_search
{
  "query": {
    "bool": {
      "must": [
        {"match_all": {}} //查询条件
      ],
      "filter": {....} //过滤条件
  }
}

注意:

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

类型

term和terms

term过滤指定字段的一个关键词,term可以过滤指定多个关键词

GET /person/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match_all": {}
        }
      ],
      "filter": [
        {
          "term": {
            "sign": "聪明"
          }
        }
      ]
    }
  }
}
GET /person/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match_all": {}
        }
      ],
      "filter": [
        {
          "terms": {
            "sign": [
              "聪明",
              "愚蠢"
            ]
          }
        }
      ]
    }
  }
}

range

过滤指定字段的值的范围

GET /ems/emp/_search
{
  "query": {
    "bool": {
      "must": [
        {"term": {
          "name": {
            "value": "黄凯宇"
          }
        }}
      ],
      "filter": {
        "range": {
          "age": {
            "gte": 7,
            "lte": 20
          }
        }
      }
    }
  }
}

exists filter

过滤指定字段不为空的文档

GET /ems/emp/_search
{
  "query": {
    "bool": {
      "must": [
        {"term": {
          "name": {
            "value": "中国"
          }
        }}
      ],
      "filter": {
        "exists": {
          "field":"aaa"
        }
      }
    }
  }
}

ids filter

过滤指定ID数组中的文档

GET /ems/emp/_search
{
  "query": {
    "bool": {
      "must": [
        {"term": {
          "name": {
            "value": "中国"
          }
        }}
      ],
      "filter": {
        "ids": {
          "values": ["1","2","3"]
        }
      }
    }
  }
}

猜你喜欢

转载自blog.csdn.net/qq_50596778/article/details/125429348