ElasticSearch查询语法

时间:2025-05-13 15:12:09

一.查询关键字

、term查询

term query会去倒排索引中寻找确切的term,它并不知道分词器的存在,这种查询适合keyword、numeric、date等明确值的

GET test_index1/_search
{
  "query": {
    "term": {
      "name": "zhangsan"
    }
  }
}

查询

match query 知道分词器的存在,会对field进行分词操作,然后再查询

GET test_index1/_search
{
  "query": {
    "match": {
      "title":  "my ss"
    }
  }
}

match和term区别可以理解为term是精确查询,这边match模糊查询;

会对my ss分词为两个单词

对认为这是一个单词

匹配查询

GET test_index1/_search
{
    "query":{
        "terms":{
            "name":["张三","王五"]
        }
    }
}

4.多条件查询语法

bool 过滤

bool 过滤可以用来合并多个过滤条件查询结果的布尔逻辑,它包含一下操作符:

  • must 多个查询条件的完全匹配,相当于 and。
  • must_not 多个查询条件的相反匹配,相当于 not。
  • should 至少有一个查询条件匹配, 相当于 or。

and查询 name=zhangsan,并且describe=xiangxixinxi

GET test_index1/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "name": "zhangsan"
          }
        },
        {
          "term": {
            "describe": "xiangxixinxi"
          }
        }
      ]
    }
  }
}

or查询 name=zhangsan,或describe=xiangxixinxi1

GET test_index1/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "name": "zhangsan"
          }
        },
        {
          "term": {
            "describe": "xiangxixinxi1"
          }
        }
      ]
    }
  }
}

权重查询

es查询无指定排序情况下,分值越大越靠前

GET test_index1/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "name": {
              "term": "zhangsan",
              "boost": 1
            }
          }
        },
        {
          "term": {
            "name": {
              "term": "lisi",
              "boost": 2
            }
          }
        }
      ]
    }
  }
}

name=lisi的条件设置boost=2,权重是条件里最大的,匹配name=lisi的分数会乘以2,排在第一位