Elasticsearch学习笔记(一) DSL语句

1. index

1.1 查询所有index

GET /_cat/indices?v

1.2 新增index

#新增一个名为pigg的index
PUT /pigg

1.3 删除index

#删除pigg这个index,产线千万别这么做,删了就完了
DELETE /pigg

2. document

2.1 新增document

PUT /pigg/_doc/1
{
  "name": "三爷",
  "age": 29,
  "hometown": "盐城",
  "gender": "male"
}

PUT /pigg/_doc/2
{
  "name": "珣爷",
  "age": 28,
  "hometown": "徐州",
  "gender": "female"
}

PUT /pigg/_doc/3
{
  "name": "米可",
  "age": 1,
  "hometown": "苏州",
  "gender": "female"
}

2.2 查询document

2.2.1 查询index的所有document

GET /pigg/_search

2.2.1 根据id查询document

GET /pigg/_doc/1?pretty

返回结果:

{
  "_index": "pigg",
  "_type": "_doc",
  "_id": "1",
  "_version": 4,
  "found": true,
  "_source": {
    "name": "三爷",
    "age": 29,
    "hometown": "盐城",
    "gender": "male"
  }
}

2.2.2 用sort排序查询

#对age进行倒序查询
GET /pigg/_search
{
  "query": {"match_all": {}},
  "sort": [
    {
      "age": {
        "order": "desc"
      }
    }
  ]
}

2.2.3 用from和size分页查询

#查询前2条数据, from是从0开始的
GET /pigg/_search
{
  "query": {"match_all": {}},
  "sort": [
    {
      "age": {
        "order": "desc"
      }
    }
  ],
  "from": 0,
  "size": 2
}

2.3 修改document

2.3.1 用put替换document

查询当前pigg表里id=1的文档

GET /pigg/_doc/1?pretty

返回如下:

{
  "_index": "pigg",
  "_type": "_doc",
  "_id": "1",
  "_version": 4,
  "found": true,
  "_source": {
    "name": "三爷",
    "age": 29,
    "hometown": "盐城",
    "gender": "male"
  }
}

用put方式更新id=1的文档

PUT /pigg/_doc/1
{
  "name": "盐城三爷"
}

再次查询id=1的文档

{
  "_index": "pigg",
  "_type": "_doc",
  "_id": "1",
  "_version": 5,
  "found": true,
  "_source": {
    "name": "盐城三爷"
  }
}

通过上面发现用put是替换了整个文档,而不是更新name这一个字段

2.3.2 用post更新document

先恢复id=1的文档为一开始的数据,然后执行如下语句
修改name,并新增interesting这个字段

POST /pigg/_doc/1/_update?pretty
{
  "doc":{
      "name": "盐城冬冬",
      "interesting": "watching TV"
  }
}

再次查询id=1的文档

{
  "_index": "pigg",
  "_type": "_doc",
  "_id": "1",
  "_version": 8,
  "found": true,
  "_source": {
    "name": "盐城冬冬",
    "age": 29,
    "hometown": "盐城",
    "gender": "male",
    "interesting": "watching TV"
  }
}

这时发现用post更新的是文档的局部字段,原来有的字段更新,没有的字段则新增这个字段

2.3.3 用script更新document

查询当前id=1的人的age是29,现在要对age加1

POST /pigg/_doc/1/_update
{
  "script": "ctx._source.age += 1"
}

再次查询id=1的文档,发现age已经是30了

{
  "_index": "pigg",
  "_type": "_doc",
  "_id": "1",
  "_version": 9,
  "found": true,
  "_source": {
    "name": "盐城冬冬",
    "age": 30,
    "hometown": "盐城",
    "gender": "male",
    "interesting": "watching TV"
  }
}

2.4 删除document

DELETE /pigg/_doc/1

猜你喜欢

转载自blog.csdn.net/winterking3/article/details/82896738