工作生活

ElasticSearch基础操作 - 修改数据

2019-07-03  本文已影响0人  SlowGO

当前使用的ES版本为 7.2

1. 文档替换

先添加一个文档,ID为1:

curl -X PUT "localhost:9200/customer/_doc/1?pretty" -H 'Content-Type: application/json' -d'
{
  "name": "John Doe"
}
'

再次执行上面的命令,ID还是1,只是name改变一下:

curl -X PUT "localhost:9200/customer/_doc/1?pretty" -H 'Content-Type: application/json' -d'
{
  "name": "Jane Doe"
}
'

查询ID为1的文档:

curl -X GET "localhost:9200/customer/_doc/1?pretty"

可以发现第二次的命令把第一次的文档覆盖了。

添加文档时ID可以不指定,让es自动生成:

curl -X POST "localhost:9200/customer/_doc?pretty" -H 'Content-Type: application/json' -d'
{
  "name": "Jane Doe"
}
'

指定ID时使用PUT,不指定ID使用POST

文档修改

修改ID为1的文档,把name改为Jane Done

curl -X POST "localhost:9200/customer/_update/1?pretty" -H 'Content-Type: application/json' -d'
{
  "doc": { "name": "Jane Doe" }
}
'

修改ID为1的文档,改name,并新添加age字段:

curl -X POST "localhost:9200/customer/_update/1?pretty" -H 'Content-Type: application/json' -d'
{
  "doc": { "name": "Jane Doe", "age": 20 }
}
'

查看文档:

curl -X GET "localhost:9200/

// 返回
customer/_doc/1?pretty"
{
  "_index" : "customer",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 3,
  "_seq_no" : 2,
  "_primary_term" : 1,
  "found" : true,
  "_source" : {
    "name" : "Jane Doe",
    "age" : 20
  }
}

修改时可以使用简单的脚本:

curl -X POST "localhost:9200/customer/_update/1?pretty" -H 'Content-Type: application/json' -d'
{
  "script" : "ctx._source.age += 5"
}
'

2. 删除文档

curl -X DELETE "localhost:9200/customer/_doc/2?pretty"

3. 批量处理

一次添加2个文档:

curl -X POST "localhost:9200/customer/_bulk?pretty" -H 'Content-Type: application/json' -d'
{"index":{"_id":"1"}}
{"name": "John Doe" }
{"index":{"_id":"2"}}
{"name": "Jane Doe" }
'

同时修改和删除:

curl -X POST "localhost:9200/customer/_bulk?pretty" -H 'Content-Type: application/json' -d'
{"update":{"_id":"1"}}
{"doc": { "name": "John Doe becomes Jane Doe" } }
{"delete":{"_id":"2"}}
'
上一篇下一篇

猜你喜欢

热点阅读