(八)Index and Query a Document
Let’s now put something into our customer index. We’ll index a simple customer document into the customer index, with an ID of 1 as follows:
现在让我们在客户索引中加入一些内容。我们将一个简单的客户文档索引到客户索引中,ID为1,如下所示:
curl -X PUT "localhost:9200/customer/_doc/1?pretty" -H 'Content-Type: application/json' -d'
{
"name": "John Doe"
}
'
And the response:
{ "_index" : "customer", "_type" : "_doc", "_id" : "1", "_version" : 1, "result" : "created", "_shards" : { "total" : 2, "successful" : 1, "failed" : 0 }, "_seq_no" : 0, "_primary_term" : 1 }
From the above, we can see that a new customer document was successfully created inside the customer index. The document also has an internal id of 1 which we specified at index time.
从上面可以看出,在客户索引中成功创建了一个新的客户文档。该文档的内部标识为1,我们在索引时指定。
It is important to note that Elasticsearch does not require you to explicitly create an index first before you can index documents into it. In the previous example, Elasticsearch will automatically create the customer index if it didn’t already exist beforehand.
值得注意的是,Elasticsearch在您将文档编入索引之前不需要先显式创建索引。在前面的示例中,如果客户索引事先尚未存在,则Elasticsearch将自动创建客户索引。
Let’s now retrieve that document that we just indexed:
我们现在检索刚刚编入索引的文档:
curl -X GET "localhost:9200/customer/_doc/1?pretty"
And the response:
{ "_index" : "customer", "_type" : "_doc", "_id" : "1", "_version" : 1, "found" : true, "_source" : { "name": "John Doe" } }
Nothing out of the ordinary here other than a field, found
, stating that we found a document with the requested ID 1 and another field, _source
, which returns the full JSON document that we indexed from the previous step.
除了字段之外,没有任何异常,发现,说明我们找到了一个具有请求ID 1的文档和另一个字段_source,它返回我们从上一步索引的完整JSON文档。