Elasticsearch中document的基础知识

写在前面的话:读书破万卷,编码如有神
--------------------------------------------------------------------

参考内容:

  《Elasticsearch顶尖高手系列-快速入门篇》,中华石杉

--------------------------------------------------------------------

主要内容包括:

  • document的核心元数据
  • document id的手动指定和自动生成
  • document的_source元数据以及定制返回结果

--------------------------------------------------------------------

1、document的核心元数据

document的核心元数据有三个:_index、_type、_id

(1.1) _index元数据

  • 代表一个document存放在哪个index中
  • 类似的数据放在一个索引中,非类似的数据放在不同的索引中:product index(包含了所有的商品)、sales index(包含了所有的商品销售数据)、inventory index(包含了所有库存的相关数据)
  • index中包含了很多类似的document: 类似是什么意思呢,其实指的就是说,这些document的fields很大一部分是相同的,你说你放了3个document,每个document的fields都完全不一样,这就不是类似了,就不太适合放到一个index里面去了
  • 索引名称必须是小写,不能用下划线开头,不包含逗号

(1.2) _type元数据

  • 代表document属于index的哪个类别
  • 一个索引通常会划分为多个type,逻辑上对index有些许不同的几类数据进行分类
  • type名称可以是大写或者小写,但是同时不能用下划线开头,不能包含逗号

(1.3) _id元数据

  • 代表document的唯一标识,与_index和_type一起可以起唯一标识和定位一个document
  • 我们可以手动指定document的id,也可以不指定,由es自动为我们创建一个id

--------------------------------------------------------------------

2、document id的手动指定和自动生成

(2.1)、手动指定document id

根据应用情况来说,是否满足手动指定document id的前提:一般来说,是从某些其他系统中导入一些数据到es时会采取这种方式,就是系统中已有数据的唯一标识,作为es中的document的id

语法格式为:

put /index/type/id

{

    "json"  

}

(2.2)、自动生成document id

语法格式:

post /index/type

{

  "json"

}

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

--------------------------------------------------------------------

3、document的_source元数据以及定制返回结果

(3.1)、_source元数据

首先我们往es中添加一条数据:

1 PUT /test_index/test_type/1
2 {
3   "test_field1":"test field1",
4   "test_field2":"test field2"
5 }

查询这条数据:

 1 GET /test_index/test_type/1
 2 返回结果:
 3 {
 4   "_index": "test_index",
 5   "_type": "test_type",
 6   "_id": "1",
 7   "_version": 1,
 8   "found": true,
 9   "_source": {
10     "test_field1": "test field1",
11     "test_field2": "test field2"
12   }
13 }

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

(3.2)、定制返回结果,指定_source中返回哪些field

 1 GET /test_index/test_type/1?_source=test_field2
 2 返回结果:
 3 {
 4   "_index": "test_index",
 5   "_type": "test_type",
 6   "_id": "1",
 7   "_version": 1,
 8   "found": true,
 9   "_source": {
10     "test_field2": "test field2"
11   }
12 }
posted @ 2018-02-16 14:33  火爆泡菜  阅读(7303)  评论(0编辑  收藏  举报