上QQ阅读APP看书,第一时间看更新
How to do it...
The HTTP method that's used is POST. The URL format for optimizing one or more indices is as follows:
http://<server>/<source_index_name>/_shrink/<target_index_name>
To shrink an index, we will perform the following steps:
- We need all the primary shards of the index to be shrinking in the same node. We need the name of the node that will contain the shrink index. We can retrieve it using the _nodes API:
GET /_nodes?pretty
Within the result, there will be a similar section:
....
"cluster_name" : "elastic-cookbook",
"nodes" : {
"9TiCStQuTDaTyMb4LgWDsg" : {
"name" : "1e9840cf42df",
"transport_address" : "172.18.0.2:9300",
"host" : "172.18.0.2",
"ip" : "172.18.0.2",
"version" : "7.0.0",
"build_flavor" : "default",
"build_type" : "docker",
"build_hash" : "f076a79",
"total_indexing_buffer" : 103795916,
....
The name of my node is 1e9840cf42df.
- Now, we can change the index settings, forcing allocation to a single node for our index, and disabling the writing for the index. This can be done using the following code:
PUT /myindex/_settings
{
"settings": {
"index.routing.allocation.require._name": "1e9840cf42df",
"index.blocks.write": true
}
}
- We need to check if all the shards are relocated. We can check for their green status:
GET /_cluster/health?pretty
The result will be as follows:
{
"cluster_name" : "elastic-cookbook",
"status" : "yellow",
"timed_out" : false,
"number_of_nodes" : 1,
"number_of_data_nodes" : 1,
"active_primary_shards" : 2,
"active_shards" : 2,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 1,
"delayed_unassigned_shards" : 0,
"number_of_pending_tasks" : 0,
"number_of_in_flight_fetch" : 0,
"task_max_waiting_in_queue_millis" : 0,
"active_shards_percent_as_number" : 66.66666666666666
}
- The index should be in a read-only state to shrink. We need to disable the writing for the index using this code snippet:
PUT /myindex/_settings?
{"index.blocks.write":true}
- If we consider the index we created in the Creating an index recipe, the shrink call for creating the reduced_index will be as follows:
POST /myindex/_shrink/reduced_index
{
"settings": {
"index.number_of_replicas": 1,
"index.number_of_shards": 1,
"index.codec": "best_compression"
},
"aliases": {
"my_search_indices": {}
}
}
- The result returned by Elasticsearch should be as follows:
{"acknowledged":true}
- We can also wait for a yellow status, if the index is ready to work:
GET /_cluster/health?wait_for_status=yellow
- Now, we can remove the read-only setting by changing the index settings:
PUT /myindex/_settings
{"index.blocks.write":false}