ElasticSearch 实战:ES查询索引文档的6种方法

在Elasticsearch中,查询索引文档的方法多种多样,这里列举了6种常见的查询方法,其中包括:

  1. 简单查询(String Query)

    • 这是最基本的全文搜索,只需在URL后面附加查询字符串即可。例如,对索引my_index中的所有文档执行模糊匹配查询:
    GET my_index/_search
    {
      "query": {
        "match": {
          "field_name": "your_search_term"
        }
      }
    }
    
  2. Match Query

    • 类似于简单查询,但提供了更多的控制选项,比如精确匹配、模糊匹配等。例如:
    GET my_index/_search
    {
      "query": {
        "match": {
          "title": {
            "query": "search term",
            "operator": "and" // or "or" for a more relaxed matching
          }
        }
      }
    }
    
  3. Term Query

    • 用于精确匹配字段的特定值,尤其是在非分析字段上。
    GET my_index/_search
    {
      "query": {
        "term": {
          "status.keyword": "active" // 使用.keyword后缀避免对非分析字段进行分词
        }
      }
    }
    
  4. Bool Query

    • 复合查询,允许组合多个查询条件,包括must(必须满足)、should(最好满足)、must_not(必须不满足)等子句。
    GET my_index/_search
    {
      "query": {
        "bool": {
          "must": [
            { "match": { "title": "search term" } },
            { "range": { "date": { "gte": "2022-01-01" } } }
          ],
          "must_not": [
            { "term": { "status": "archived" } }
          ]
        }
      }
    }
    
  5. Range Query

    • 用于查询字段值在某个范围内的文档。
    GET my_index/_search
    {
      "query": {
        "range": {
          "age": {
            "gte": 18,
            "lte": 65
          }
        }
      }
    }
    
  6. Aggregation Queries

    • 聚合查询不是用来寻找特定文档的,而是用来做数据汇总统计。例如,计算某个字段的不同值的数量,或者按字段值分组统计数据。
    GET my_index/_search
    {
      "aggs": {
        "age_buckets": {
          "terms": {
            "field": "age",
            "size": 10
          }
        }
      }
    }
    

以上是Elasticsearch中几种基本的查询方式,实际上还有更多的查询类型和组合方式,如Wildcard Query、Prefix Query、Fuzzy Query、Regexp Query等等,可以根据实际需求选择合适的查询方法。

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值