月光代碼園

記錄、分享、交流

导航

Elasticsearch学习笔记#3 更新/ID自动生成/更新时使用脚本函数script/删除数据/批处理命令_bulk

延续上篇

1.使用PUT更新数据

先执行创建数据命令

PUT /customer/_doc/1?pretty
{
  "name": "John Doe"
}

 再使用同样的命令,其中要把name的值修改一下,再执行

PUT /customer/_doc/1?pretty
{
  "name": "Jane Doe"
}

 结果

{
  "_index" : "customer",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 2,
  "result" : "updated",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 1,
  "_primary_term" : 1
}

 此时可以看见result的值为updated,新添加的数据将覆盖id=1的数据 

验证一下

GET /customer/_doc/1

 结果

{
  "_index" : "customer",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 2,
  "_seq_no" : 1,
  "_primary_term" : 1,
  "found" : true,
  "_source" : {
    "name" : "Jane Doe"
  }
}

2.新增数据时,不指定ID的情况

POST /customer/_doc?pretty
{
  "name": "Jane Doe"
}

 没有指定具体ID,结果

{
  "_index" : "customer",
  "_type" : "_doc",
  "_id" : "mH8AOWwBo4iimwza2_ez",
  "_version" : 1,
  "result" : "created",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 2,
  "_primary_term" : 1
}

  新建成功,系统会随机生成一个id

3.使用POST更新数据

POST /customer/_update/1?pretty
{
  "doc": { "name": "Jane Doe" }
}

 

POST /customer/_update/1?pretty
{
  "doc": { "name": "Jane Doe", "age": 20 }
}

结果

{
  "_index" : "customer",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 4,
  "result" : "updated",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 4,
  "_primary_term" : 1
}

4.在更新数据时使用简单的脚本

POST /customer/_update/1?pretty
{
  "script" : "ctx._source.age += 5"
}

age为第3个例子添加的字段,ctx._source和当前编辑的文档相关联

执行后查询该文档,结果为:

{
  "_index" : "customer",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 6,
  "_seq_no" : 6,
  "_primary_term" : 1,
  "found" : true,
  "_source" : {
    "name" : "Jane Doe",
    "age" : 25
  }
}

  age的值增加了5

5.删除数据

DELETE /customer/_doc/1?pretty

6.批处理命令

POST /customer/_bulk?pretty
{"index":{"_id":"1"}}
{"name": "John Doe" }
{"index":{"_id":"2"}}
{"name": "Jane Doe" }

 该命令先更新ID=1  name=John Doe的数据,再创建ID=2 name=Jane Doe的数据

POST /customer/_bulk?pretty
{"update":{"_id":"1"}}
{"doc": { "name": "John Doe becomes Jane Doe" } }
{"delete":{"_id":"2"}}

 该命令先更新id=1的数据,数据内容为name=John Doe becomes Jane Doe;再删除id=2的数据

posted on 2019-08-03 16:29  bangdikka  阅读(616)  评论(0编辑  收藏  举报