Elasticsearch 修改数据

Indexing/Replacing Documents

插入或替换document。
ElastiSearch提供几乎实时的数据操作与搜索功能。它的数据在事务完成之后立即可用。

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

如果两次插入的_doc的值是一样的,那么ElasticSearch会覆盖这个文档的值,_version的值会+1.

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

索引时,ID部分是可选的,如果没有指定ID,那么ElasticSearch就会生成一个随机的ID。

!!没有ID的时候要使用POST!不是PUT

Updating Documents

无论什么时候,ElasticSearch的更新都不是真正的更新,而是删了旧文档,然后将更新后的内容应用到新文档之中。

更新例子:
注意是POST请求。

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

这个实例在更新名字的同时添加了一个名字为“age”的filed。

updates也可以使用一些类似的脚本言语。

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

ctx._source代表current source document(当前文档)的source。

还有一些SQL UPDATE-WHERE用法,参见docs_update_by_query API
https://www.elastic.co/guide/en/elasticsearch/reference/6.2/docs-update-by-query.html

Deleting Document

DELETE /customer/_doc/2?pretty

_delete_by_query API用于删除特定的查询匹配文档。
详情参见:
https://www.elastic.co/guide/en/elasticsearch/reference/6.2/docs-delete-by-query.html

Batch Processing批量处理

ElasticSearch提供_bulk API 用于批量处理。

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

这个例子index了两个customer

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

批量的更新操作和删除操作。

批量操作不会因为其中的一个操作失败而整个失败。如果它其中有一个失败,则继续处理其它的操作,它会返回每个操作的状态,可以用来检测某个特定的操作是否失败。

你可能感兴趣的:(Elasticsearch 修改数据)