Elasticsearch(ES)基础语法(笔记)(持续更新)

发布于:2025-07-31 ⋅ 阅读:(16) ⋅ 点赞:(0)

记住添加的时候记得带上唯一标识的字段,例如:数据库非业务主键字段id,uuid等,添加的字段不能凭空捏造,必须能在其他相应文档列表中的"_source"下能找到,否则依据该字段查询会找不到

一、查(重点)

1.查询全部

select * from user_info
GET /user_portrait/_search
{
   "query":
   {
     "match_all": 
     {
       
     }
   }
}
GET /user_portrait/_search

2.匹配查询(重点)

单个

//分词查询 如果单单输入'xiao',或者'ling'可能导致查询失败,查不到。
GET /user_portrait/_search
{
  "query":
  {
    "match": 
    {
      
        "uuid": "xiaoling"
      
    }
  }
}

多个(例如要查两个用户)

//分词查询 如果单单输入'xiao',或者'ling'可能导致查询失败,查不到。
GET /user_portrait/_search
{
  "query":
  {
    "match": 
    {
      
        "uuid": "xiaoling",
        "uuid": "lisi"
      
    }
  }
}

3.精确查询

select * from user_info where uuid= 'xiaoling'
GET /user_portrait/_search
{
  "query":
  {
    "term": 
    {
      
        "uuid": "xiaoling"
      
    }
  }
}

3.范围查询(gt/lt:大于/小于 gte/lte:大于等于/小于等于)(一般查询多条出来)

select  * from user_info where pass >= 123456
GET user_portrait/_search
{
  "query": 
  {
    "range": {
      
      "pass": {
        "gte": 123456
      }
    }
  }
}

4. bool 多条件复合查询

a.查询pass=123456并且uuid=‘xiaoling’

记得bool在最外面包裹着,否则must打不出,must就是=。多个等于条件在同一个must里面[  ]写就行.想写多少都行,满足查询条件即可

select * from user_info where pass=123456 and uuid = 'xiaoling' 
GET user_portrait/_search
{
  "query": 
  {
    "bool": 
    {
      "must": 
      [
        {
          "match": 
          {
            "uuid": "xiaoling"
            
          }
        },
                
        {
          "match": 
          {
            "lwsas": "100"
            
          }
        }
      ]
    }
  }
}

b.查询pass>=123456并且uuid!=‘zs’的,那么除zs外pass大于等于123456的都被查询出来

select * from user_info where pass >= 123456  and name != 'zs' 
GET user_portrait/_search
{
  "query": 
  {
    "bool": 
    {
      "must": 
      [
        {
          "range": 
          {
            "pass": {
              "gte": 123456
            }
            
          }
        }
      ],
      "must_not": 
      [
        {
          "match": 
          {
            "uuid": "zs"
          }
        }
      ]
    }
  }
}

should表示至少满足一个条件

5.匹配某字段是否为空

某字段为空的列表

user_portrait索引中,查找所有不包含uuid字段的文档列表

GET user_portrait/_search
{
  "query": 
  {
    "bool":
    {
      "must_not": [
        {
          "exists": 
          {
            "field": "uuid"
          }
        }
      ]
    }
  }
}

某字段不为空的列表

user_portrait索引中,查找所有包含uuid字段的文档列表

GET user_portrait/_search
{
  "query": 
  {
    "bool":
    {
      "must": [
        {
          "exists": 
          {
            "field": "uuid"
          }
        }
      ]
    }
  }
}

6.in查询(比如:查询uuid为zhangsan,lisi,zhaoliu的用户列表(因为uuid唯一性查询出来只有三条,那么一般情况下是列表数据记录或者文档存在多条))

select * from user_info where age in('zhangsan', 'lisi', 'zhaoliu')
GET user_portrait/_search
{
  "query": 
  {
    "terms": {
      "uuid": ["zhangsan","lisi","zhaoliu"]
    }
  }
}


网站公告

今日签到

点亮在社区的每一天
去签到