Elasticsearch元数据

_index元数据

代表一个 document 存放在哪个 index 中。

类似的数据放在一个索引,非类似的数据放不同索引:product index(包含了所有的商品),sales index(包含了所有的商品销售数据),inventory index(包含了所有库存相关的数据)。如果你把比如 product,sales,human resource(employee),全都放在一个大的 index 里面,比如说 company index,不合适的。

index 中包含了很多类似的 document:类似是什么意思,其实指的就是说,这些 document 的 fields 很大一部分是相同的,你说你放了 3 个 document,每个 document 的 fields 都完全不一样,这就不是类似了,就不太适合放到一个 index 里面去了。

索引名称必须是小写的,不能用下划线开头,不能包含逗号:product,website,blog

_id元数据

代表 document 的唯一标识,与 index 一起,可以唯一标识和定位一个 document。

我们可以手动指定 document 的 id(put /index/id),也可以不指定,由 es 自动为我们创建一个 id。

document id

手动指定 document id,根据应用情况来说,是否满足手动指定 document id 的前提:

一般来说,是从某些其他的系统中,导入一些数据到 es 时,会采取这种方式,就是使用系统中已有数据的唯一标识,作为 es 中 document 的 id。举个例子,比如说,我们现在在开发一个电商网站,做搜索功能,或者是 OA 系统,做员工检索功能。这个时候,数据首先会在网站系统或者 IT 系统内部的数据库中,会先有一份,此时就肯定会有一个数据库的 primary key(自增长,UUID,或者是业务编号)。如果将数据导入到 es 中,此时就比较适合采用数据在数据库中已有的 primary key。

如果说,我们是在做一个系统,这个系统主要的数据存储就是 es 一种,也就是说,数据产生出来以后,可能就没有 id,直接就放 es 一个存储,那么这个时候,可能就不太适合说手动指定 document id 的形式了,因为你也不知道 id 应该是什么,此时可以采取下面要讲解的让 es 自动生成id的方式。

put /index/id PUT /test_index/2 { "test_content": "my test" }

自动生成 document id

post /index/type POST /test_index/test_type { "test_content": "my test" } { "_index": "test_index", "_type": "test_type", "_id": "AVp4RN0bhjxldOOnBxaE", "_version": 1, "result": "created", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "created": true }

自动生成的 id,长度为 20 个字符,URL 安全,base64 编码,GUID,分布式系统并行生成时不可能会发生冲突。

_source元数据

put /test_index/1 { "test_field1": "test field1", "test_field2": "test field2" } get /test_index/1 { "_index": "test_index", "_type": "test_type", "_id": "1", "_version": 2, "found": true, "_source": { "test_field1": "test field1", "test_field2": "test field2" } }

_source 元数据:就是说,我们在创建一个 document 的时候,使用的那个放在 request body 中的 json 串,默认情况下,在 get 的时候,会原封不动的给我们返回回来。

定制返回结果

定制返回的结果,指定 _source 中,返回哪些 field:

GET /test_index/test_type/1?_source=test_field1,test_field2 { "_index": "test_index", "_type": "test_type", "_id": "1", "_version": 2, "found": true, "_source": { "test_field2": "test field2" } }