概要
索引是我们使用Elasticsearch里最频繁的部分日常的操作都与索引有关,本篇从运维人员的视角,来玩一玩Elasticsearch的索引操作。
基本操作
在运维童鞋的视角里,索引的日常操作除了CRUD,还是打开关闭、压缩、alias重置,我们来了解一下。
创建索引
[esuser@elasticsearch02 ~]$curl -XPUT 'http://elasticsearch02:9200/music?pretty' -H 'Content-Type: application/json' -d '
{
"settings" : {
"index" : {
"number_of_shards" : 3,
"number_of_replicas" : 2
}
},
"mappings" : {
"type1" : {
"properties" : {
"name" : {
"type" : "text" }
}
}
}
}'
{
"acknowledged": true,
"shards_acknowledged": true
}
默认情况下,索引创建命令会在每个primary shard的replica shard 开始进行复制后,或者是请求超时之后,返回响应消息,如上。
acknowledged表示这个索引是否创建成功,shards_acknowledged
表明了每个primary shard有没有足够数量的replica开始进行复制。
可能这两个参数会为false,但是索引依然可以创建成功。因为这些参数仅仅是表明在请求超时之前,这两个操作有没有成功,也有可能请求超时了,在超时前都没成功,但是实际上Elasticsearch Server端接收到了消息,并且都执行了,只是响应前还没来得及执行,所以响应的是false。
删除索引
curl -XDELETE 'http://elasticsearch02:9200/music?pretty'
查询索引设置信息
curl -XGET 'http://elasticsearch02:9200/music?pretty'
打开/关闭索引
curl -XPOST 'http://elasticsearch02:9200/music/_close?pretty'
curl -XPOST 'http://elasticsearch02:9200/music/_open?pretty'
如果一个索引关闭了,那么这个索引就没有任何的性能开销了,只要保留这个索引的元数据即可,然后对这个索引的读写操作都不会成功。一个关闭的索引可以接着再打开,打开以后会进行shard recovery过程。
如果集群数据定时有备份,在执行恢复的操作之前,必须将待恢复的索引关闭,否则恢复会报失败。
压缩索引
我们知道索引的primary shard数量在创建时一旦指定,后期就不能修改了,但是有一个这样的情况:预估的shard数量在实际生产之后,发现估算得有点高,比如原来设置number_of_shards为8,结果生产上线后发现数据量没那么大,我想把这个索引的primary shard压缩一下,该如何操作呢?
shrink命令的作用就是对索引进行压缩的,不过有个限制:压缩后的shard数量必须可以被原来的shard数量整除。如我们的8个primary shard的index可以只能被压缩成4个,2个,或者1个primary shard的index。
shrink命令的工作流程:
- 创建一个跟source index的定义一样的target index,但是唯一的变化就是primary shard变成了指定的数量。
- 将source index的segment file直接用hard-link的方式连接到target index的segment file,如果操作系统不支持hard-link,那么就会将source index的segment file都拷贝到target index的data dir中,会很耗时。如果用hard-link会很快。
- target index进行shard recovery恢复。
案例演示
- 我们创建一个number_of_shards为8的索引,名称为music8
curl -XPUT 'http://elasticsearch02:9200/music8?pretty' -H 'Content-Type: application/json' -d '
{
"settings" : {
"index" : {
"number_of_shards" : 8,
"number_of_replicas" : 2
}
},
"mappings" : {
"children" : {
"properties" : {
"name" : {
"type" : "text" }
}
}
}
}'
- 在索引内灌点数据进去
- 将索引的shard都移到一个node上去,如node1
curl -XPUT 'http://elasticsearch02:9200/music8/_settings?pretty' -H 'Content-Type: application/json' -d '
{
"settings": {
"index.routing.allocation.require._name": "node-1",
"index.blocks.write": true
}
}'
这个过程叫shard copy relocate,使用
`curl -XGET ‘http://elasticsearch02:9200/_cat/recovery?v’