zoukankan      html  css  js  c++  java
  • Elasticsearch 管理文档

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

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

    索引/替换文档

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

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

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

    当再次执行命令:

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

    之前的第一个文档就被覆盖掉了。

    如果指定新的文档id,那么旧的文档仍然存在:

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

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

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

    需要注意的是,如果不指定ID,那么需要使用POST命令,而不是PUT。

    更新文档

    除了索引和替换文档,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中的某一个命令执行出错,那么会继续执行后面的命令,最后在命令返回时,会返回每个命令的执行结果。

  • 相关阅读:
    POJ 2251 Dungeon Master
    HDU 3085 Nightmare Ⅱ
    CodeForces 1060 B Maximum Sum of Digits
    HDU 1166 敌兵布阵(树状数组)
    HDOJ 2050 折线分割平面
    HDU 5879 Cure
    HDU 1878 欧拉回路
    HDU 6225 Little Boxes
    ZOJ 2971 Give Me the Number
    HDU 2680 Choose the best route
  • 原文地址:https://www.cnblogs.com/xing901022/p/4963542.html
Copyright © 2011-2022 走看看