基本操作

1 添加文档


数据库中有3条数据

PUT test3/_doc/3
{
   
  "name":"hong",
  "age":17,
  "birth":"1996-02-01"
}

2 (查)获取文档数据

1 根据id查询

GET   test3/_doc/3


2 带条件的查询

GET test3/_doc/_search?q=name:jing

3 (更新)Post _update , 推荐使用这种更新方式!

POST test3/_doc/1/_update
{
   
  "doc":{
   
    "name":"minmin"
  }
}

复杂查询操作

复杂查询

之前我们查询的语句是:

GET test3/_doc/_search?q=name:jing

现在我们想要更加复杂的查询,如何书写呢?

GET test3/_doc/_search
{
   
  "query": {
       查询的属性
    "match": {
      精确匹配的属性
      "name":"minmin"
    }
  }
}


自定义查询出的字段

之前是查询出数据库中数据的所有的字段,但是现在我们想要只是一条数据的一个字段,那么如何查询

我们先看查询出的数据格式

一条数据的所有字段都在_source属性里面。现在我们不想要这么多的字段,那么我们在查询的时候可以限制。现在需要查询具体的字段

GET test3/_doc/_search
{
   
  "query": {
   
    "match": {
   
      "name":"敏"
    }
  },
  "_source": ["name"]
}

排序


GET test3/_doc/_search
{
   
 
  "sort":[    排序属性
    {
      一个字典里面写一个要排序的字段
      "age":{
      根据这个字段进行排序
        "order":"asc"   设置升序还是降序
      }
    }
    ]
}

分页

GET test3/_doc/_search
{
   
  "from":1,   从第几个开始
  "size":2   返回几个数据
}

布尔值查询

must (and) 命令

must (and),所有的条件都要符合 ,相当于sql中的 where id = 1 and name = xxx

只有多个条件都符合之后才会查询出来 。

GET test3/_doc/_search
{
   
  "query": {
   
    "bool":{
   
      "must":[   list里面是多个对象
        {
          每一个对象里面都是精确匹配
          "match": {
   
          "name":"jing"
          }
        },
        {
      每一个对象里面是精确匹配
          "match": {
   
          "age":12
          }
        }
        
        ]
    }
    
  }
 
}

只有两个条件都一样了,才可以查询出来,这个就是must的作用

should(or)命令

should(or),所有的条件都要符合 where id = 1 or name = xxx


GET test3/_doc/_search
{
   
  "query": {
   
    "bool":{
   
      "should":[    这个是或者命令
        {
   
          "match": {
   
          "name":"jing"
          }
        },
        {
   
          "match": {
   
          "age":12
          }
        }
        
        ]
    }
    
  }
 
}

must_not (not)

GET test3/_doc/_search
{
   
  "query": {
   
    "bool":{
   
      "must_not":[   不是一下条件的查询出来
        {
   
          "match": {
   
          "name":"jing"
          }
        },
        {
   
          "match": {
   
          "age":12
          }
        }
        
        ]
    }
    
  }
 
}

过滤器 filter

GET test3/_doc/_search
{
   
  "query": {
   
    "bool":{
   
      "filter":{
     将过滤的条件写在这个里面
        "range":{
   
          "age":{
   
            "gt":15,
            "lt":17
          }
        }
      }
    }
    
  }
 
}
gt 大于
gte 大于等于
lt 小于
lte 小于等于!

高亮

GET test3/_doc/_search
{
   
  "query":{
   
    "match":{
   
      "name":"jing"
    }
    
  },
  "highlight":{
   
    "fields":{
   
      "name":{
   }
    }
  }
 
}

自定义高亮的方法

GET test3/_doc/_search
{
   
  "query":{
   
    "match":{
   
      "name":"jing"
    }
    
  },
  "highlight":{
   
    "pre_tags":"<p>",    自定义方法
    "post_tags":"</p>",
    "fields":{
   
      "name":{
   }
    }
  }
 
}