【Elasticsearch 技术分享】—— Elasticsearch 存储一条数据, put 过程是什么样子的?
前言
在前面已经介绍了 ES 中常用的一些名词,知道了数据是存储在 shard 中的,而 index 会映射一个或者多个 shard 。那这时候我要存储一条数据到某个索引下,这条数据是在哪个 index 下的呢?
公众号:liuzhihangs,记录工作学习中的技术、开发及源码笔记;时不时分享一些生活中的见闻感悟。欢迎大佬来指导!
ES 演示
一切按照官方教程使用 三条命令,在本机启动三个节点组装成伪集群。
~ % > ./elasticsearch
~ % > ./elasticsearch -Epath.data=data2 -Epath.logs=log2
~ % > ./elasticsearch -Epath.data=data3 -Epath.logs=log3
创建索引
curl -X PUT "localhost:9200/my-index-000001?pretty" -H 'Content-Type: application/json' -d'
{
"settings": {
"index": {
"number_of_shards": 3,
"number_of_replicas": 2
}
}
}
'
当前版本 7.9
文档地址:https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html
ES 默认 number
默认 number

下面命令可以查看索引信息
curl -X GET "localhost:9200/_cat/indices/my-index-000001?v&s=index&pretty"

存放数据
curl -X PUT "localhost:9200/my-index-000001/_doc/0825?pretty" -H 'Content-Type: application/json' -d'
{
"name": "liuzhihang"
}
'

查询数据
curl -X GET "localhost:9200/my-index-000001/_doc/0825?pretty"
文档地址:
https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html

一条数据该存放在哪个 shard
通过命令可以看出:在存放数据时并没有指定到哪个 shard,那数据是存在哪里的呢?
当一条数据进来,会默认会根据 id 做路由
shard = hash(routing) % number_of_primary_shards
从而确定存放在哪个 shard。 routing 默认是 _id, 也可以设置其他。
这个 id 可以自己指定也可以系统给生成, 如果不指定则会系统自动生成。
put 一条数据的过程是什么样的?

写入过程主要分为三个阶段
1. primary shard 会验证传入的数据结构
2. 本地执行相关操作
3. 将操作转发给 replica shard
4. 当数据写入 primary shard 和 replica shard 成功后,路由节点返回响应给 Client。
在写操作时,默认情况下,只需要 primary shard 处于活跃状态即可进行操作。
在索引设置时可以设置这个属性
index.write.wait
默认是 1,即 primary shard 写入成功即可返回。
如果设置为 all 则相当于 number
可以通过索引设置动态覆盖此默认设置。
总结
如何查看数据在哪个 shard 上呢?
curl -X GET "localhost:9200/my-index-000001/_search_shards?routing=0825&pretty"
通过上面命令可以查到数据 0825 的所在 shard。
