Elasticsearch 使用集群 - 创建和查询文档

章节


现在把一些内容放入customer索引中。我们将一个简单的客户文档放到customer索引中,ID为1,如下所示:

API:

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

curl命令访问API:

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

响应:

{
  "_index" : "customer",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 1,
  "result" : "created",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 0,
  "_primary_term" : 1
}

可以看到,customer索引中成功创建了一个新文档。文档的内部id也是1,在创建文档时指定。

注意,Elasticsearch并不要求,先要有索引,才能将文档编入索引。创建文档时,如果指定索引不存在,将自动创建。

现在检索刚才编入索引的文档:

GET /customer/_doc/1?pretty

curl命令访问API:

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

响应:

{
  "_index" : "customer",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 1,
  "_seq_no" : 0,
  "_primary_term" : 1,
  "found" : true,
  "_source" : {
    "name" : "John Doe"
  }
}

这里有一个字段found为真,表示找到了一个ID为1的文档,另一个字段_source,该字段返回完整JSON文档。

posted @ 2019-09-05 16:03  吴吃辣  阅读(253)  评论(0编辑  收藏  举报