Elasticsearch 管理文档

ES支持近实时的索引、更新、查询、删除文档,近实时就意味着刚刚索引的数据须要1秒钟后才能搜索到,这也是与传统的SQL数据库不一样的地方。html

更多的ES文档资料参考:Elasticsearch官方文档翻译数据库

索引/替换文档

以前已经试过如何索引一个文档了,这里再复习一下:curl

curl -XPUT 'localhost:9200/customer/external/1?pretty' -d '
{
  "name": "John Doe"
}'

上面的例子中,建立了一个索引为customer,类型为external,id为1的文档。url

当再次执行命令:spa

curl -XPUT 'localhost:9200/customer/external/1?pretty' -d '
{
  "name": "Jane Doe"
}'

以前的第一个文档就被覆盖掉了。翻译

 

若是指定新的文档id,那么旧的文档仍然存在:code

curl -XPUT 'localhost:9200/customer/external/2?pretty' -d '
{
  "name": "Jane Doe"
}'

 

索引的时候ID是可选的,若是不指定ID,ES会随机生成一个ID,并使用这个ID索引文档数据。htm

curl -XPOST 'localhost:9200/customer/external?pretty' -d '
{
  "name": "Jane Doe"
}'

须要注意的是,若是不指定ID,那么须要使用POST命令,而不是PUT。blog

更新文档

除了索引和替换文档,ES还支持更新文档。更新文档实际上是先删除旧的文档,再索引新的文档。索引

若是想要更新文档内容,能够按照下面的方式进行:

curl -XPOST 'localhost:9200/customer/external/1/_update?pretty' -d '
{
  "doc": { "name": "Jane Doe" }
}'

因为是先删除再索引,所以能够额外增长新的字段:

curl -XPOST 'localhost:9200/customer/external/1/_update?pretty' -d '
{
  "doc": { "name": "Jane Doe", "age": 20 }
}'

固然也支持使用脚本进行更新:

curl -XPOS
T 'localhost:9200/customer/external/1/_update?pretty' -d ' { "script" : "ctx._source.age += 5" }'

其中ctx._source表明了当前的文档,上面的意思 是 在当前文档的基础上age加5.

删除文档

删除文档就很简单了,只须要指定文档的索引、类型、ID就好了:

curl -XDELETE 'localhost:9200/customer/external/2?pretty'

 

批量操做

除了索引、替换、更新和删除,ES为了减小来回的响应信息,能够一次性执行多个命令,最后统一返回执行结果。

例如:

curl -XPOST 'localhost:9200/customer/external/_bulk?pretty' -d '
{"index":{"_id":"1"}}
{"name": "John Doe" }
{"index":{"_id":"2"}}
{"name": "Jane Doe" }
'

上面的命令能够同时插入两条数据。

_bulk命令不单单支持单个命令执行多条,还只是多种不一样的命令执行多条。

curl -XPOST 'localhost:9200/customer/external/_bulk?pretty' -d '
{"update":{"_id":"1"}}
{"doc": { "name": "John Doe becomes Jane Doe" } }
{"delete":{"_id":"2"}}
'

上面的命令中,先更新id为1的文档,再删除id为2的文档。

 

若是bulk中的某一个命令执行出错,那么会继续执行后面的命令,最后在命令返回时,会返回每一个命令的执行结果。

相关文章
相关标签/搜索