ElasticSearch

操作文档

2018-12-24  本文已影响2人  王勇1024

获取文档

为了从 Elasticsearch 中检索出文档 ,我们仍然使用相同的 _index , _type , 和 _id ,但是 HTTP 谓词更改为 GET :

    GET /website/blog/123?pretty

返回文档的一部分

默认情况下, GET 请求 会返回整个文档,这个文档正如存储在 _source 字段中的一样。但是也许你只对其中的 title 字段感兴趣。单个字段能用 _source 参数请求得到,多个字段也能使用逗号分隔的列表来指定

   GET /website/blog/123?_source=title,text

只返回_source字段

    GET /website/blog/123/_source

那么返回的的内容如下所示:


    {

      "title": "My first blog entry",

      "text":  "Just trying this out...",

      "date":  "2014/01/01"

    }


检查文档是否存在

如果只想检查一个文档是否存在 --根本不想关心内容--那么用 HEAD 方法来代替 GET 方法。 HEAD 请求没有返回体,只返回一个 HTTP 请求报头:

    curl -i -XHEAD http://localhost:9200/website/blog/123

如果文档存在, Elasticsearch 将返回一个 200 ok 的状态码:


    HTTP/1.1 200 OK

    Content-Type: text/plain; charset=UTF-8

    Content-Length: 0


若文档不存在, Elasticsearch 将返回一个 404 Not Found 的状态码:


    curl -i -XHEAD http://localhost:9200/website/blog/124

    HTTP/1.1 404 Not Found

    Content-Type: text/plain; charset=UTF-8

    Content-Length: 0


当然,一个文档仅仅是在检查的时候不存在,并不意味着一毫秒之后它也不存在:也许同时正好另一个进程就创建了该文档。

更新整个文档

在 Elasticsearch 中文档是 不可改变 的,不能修改它们。 相反,如果想要更新现有的文档,需要 重建索引或者进行替换, 我们可以使用相同的 index API 进行实现


PUT /website/blog/123

{

  "title": "My first blog entry",

  "text":  "I am starting to get the hang of this...",

  "date":  "2014/01/02"

}


删除文档

删除文档 的语法和我们所知道的规则相同,只是 使用 DELETE 方法:

    DELETE /website/blog/123

如果找到该文档,Elasticsearch 将要返回一个 200 ok 的 HTTP 响应码,和一个类似以下结构的响应体。注意,字段 _version 值已经增加:

{

  "found" :    true,

  "_index" :  "website",

  "_type" :    "blog",

  "_id" :      "123",

  "_version" : 3

}

如果文档没有 找到,我们将得到 404 Not Found 的响应码和类似这样的响应体:

{

  "found" :    false,

  "_index" :  "website",

  "_type" :    "blog",

  "_id" :      "123",

  "_version" : 4

}

上一篇 下一篇

猜你喜欢

热点阅读