Elasticsearch核心知识篇(15)
document id的手动指定与自动生成两种方式解析
1.手动指定document id
(1)根据应用情况来说,是否满足手动指定document id的前提:
一般来说,是从某些其他的系统中,导入一些数据到es时,会采取这种方式,就是使用系统中已有数据的唯一标识,作为es中document的id。举个例子,比如说,我们现在在开发一个电商网站,做搜索功能,或者是OA系统,做员工检索功能。这个时候,数据首先会在网站系统或者IT系统内部的数据库中,会先有一份,此时就肯定会有一个数据库的primary key
(自增长,UUID,或者是业务编号)。如果将数据导入到es中,此时就比较适合采用数据在数据库中已有的primary key。
如果说,我们是在做一个系统,这个系统主要的数据存储就是es一种,也就是说,数据产生出来以后,可能就没有id,直接就放es一个存储,那么这个时候,可能就不太适合说手动指定document id的形式了,因为你也不知道id应该是什么,此时可以采取下面要讲解的让es自动生成id的方式。
手动指定的方式:put /index/type/id
PUT /test_index/test_type/2
{
"test_content": "my test"
}
2.自动生成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,分布式系统并行生成时不可能会发生冲突
Elasticsearch核心知识篇(16)
document的_source元数据以及定制返回结果解析
_source元数据
- 新增数据
put /test_index/test_type/1
{
"test_field1": "test field1",
"test_field2": "test field2"
}
- 查询数据
get /test_index/test_type/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_field2
# 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"
}
}
Elasticsearch核心知识篇(17)
document的全量替换、强制创建以及图解lazy delete机制
document的全量替换
-
语法与创建文档是一样的
- 如果document id不存在,那么就是创建
- 如果document id已经存在,那么就是全量替换操作,替换document的json串内容
-
document是不可变的,如果要修改document的内容,第一种方式就是
全量替换
,直接对document重新建立索引,替换里面所有的内容 -
es会将老的document标记为deleted,然后新增我们给定的一个document,当我们创建越来越多的document的时候,es会在适当的时机在后台自动删除标记为deleted的document(
删除机制
)
- 数据不存在,直接进行创建
- 数据存在,进行全量替换
全量替换以及之后的获取和删除的原理图解部分
document的强制创建
- 创建文档与全量替换的语法是一样的,有时我们只是想新建文档,不想替换文档,如果强制进行创建呢?
- 命令
PUT /index/type/id?op_type=create
PUT /index/type/id/_create
PUT /waws_test/waws_type/4?op_type=create
{
"test_field1":"waws521"
}
# 出现下面error正常
{
"error": {
"root_cause": [
{
"type": "version_conflict_engine_exception",
# 版本冲突,document已经存在了,当前版本是version 2
"reason": "[waws_type][4]: version conflict, document already exists (current version [2])",
"index_uuid": "x8b-zhPHS4GZcRNsFHlkbw",
"shard": "2",
"index": "waws_test"
}
],
"type": "version_conflict_engine_exception",
"reason": "[waws_type][4]: version conflict, document already exists (current version [2])",
"index_uuid": "x8b-zhPHS4GZcRNsFHlkbw",
"shard": "2",
"index": "waws_test"
},
"status": 409
}
document的删除
- 不会理解物理删除,只会将其标记为deleted,当数据越来越多的时候,在后台自动删除
- 命令
DELETE /index/type/id