文档经过index
API被索引——使数据能够被存储和搜索。可是首先咱们须要决定文档所在。正如咱们讨论的,文档经过其_index
、_type
、_id
惟一肯定。们能够本身提供一个_id
,或者也使用index
API 为咱们生成一个。web
若是你的文档有天然的标识符(例如user_account
字段或者其余值表示文档),你就能够提供本身的_id
,使用这种形式的index
API:ide
PUT /{index}/{type}/{id} { "field": "value", ... }
例如咱们的索引叫作“website”
,类型叫作“blog”
,咱们选择的ID是“123”
,那么这个索引请求就像这样:ui
PUT /website/blog/123 { "title": "My first blog entry", "text": "Just trying this out...", "date": "2014/01/01" }
Elasticsearch的响应:this
{ "_index": "website", "_type": "blog", "_id": "123", "_version": 1, "created": true }
响应指出请求的索引已经被成功建立,这个索引中包含_index
、_type
和_id
元数据,以及一个新元素:_version
。spa
Elasticsearch中每一个文档都有版本号,每当文档变化(包括删除)都会使_version
增长。在《版本控制》章节中咱们将探讨如何使用_version
号确保你程序的一部分不会覆盖掉另外一部分所作的更改。版本控制
若是咱们的数据没有天然ID,咱们可让Elasticsearch自动为咱们生成。请求结构发生了变化:PUT
方法——“在这个URL中存储文档”
变成了POST
方法——"在这个类型下存储文档"
。(译者注:原来是把文档存储到某个ID对应的空间,如今是把这个文档添加到某个_type
下)。code
URL如今只包含_index
和_type
两个字段:blog
POST /website/blog/ { "title": "My second blog entry", "text": "Still trying this out...", "date": "2014/01/01" }
响应内容与刚才相似,只有_id
字段变成了自动生成的值:索引
{ "_index": "website", "_type": "blog", "_id": "wM0OSFhDQXGZAWDf0-drSA", "_version": 1, "created": true }
自动生成的ID有22个字符长,URL-safe, Base64-encoded string universally unique identifiers, 或者叫 UUIDs。ip