# 启动关闭/缩小/滚动->索引

## Open / Close Index API /启动关闭索引

启动关闭索引允许关闭一个索引并在之后重新开启，一个关闭的索引几乎不占用集群资源（除了维持本身的元信息），并且关闭的索引对读写操作锁定。一个关闭的索引可以重新开启，将通过常规的恢复进程开启。

REST 接口为 `/{index}/_close` 和 `/{index}/_open`. 例如:

```
curl -XPOST 'localhost:9200/my_index/_close?pretty'
curl -XPOST 'localhost:9200/my_index/_open?pretty'
```

同时开启/关闭多个索引也是允许的。如果请求不存在的索引会抛出错误，可以通过修改配置 `ignore_unavailable=true 阻止抛出错误。`

所有的索引都可以被开启/关闭只用使用 \_all 或者采用通配符（例如 \* ）作为索引名称。

通过 \_all 或者通配符识别索引的方式可以通过修改配置 `action.destructive_requires_name=true 来禁用，这项配置也可以通过集群API修改更新。`

关闭索引需要消费大量的磁盘空间，可能会对现有环境造成问题。关闭索引的API可以通过集群设置API禁用：`cluster.indices.close.enable`= `false（默认为true），关闭。`

## Shrink Index /缩小索引

缩小索引API可以允许你将存在的索引转变为一个只包含主要分片的新索引。目标索引中请求的主要分片数量必须要为原索引中的因子（即原分片数量是新分片倍数），例如8个分片可以缩小到4、2、1个分片。如果原分片数量为素数则只能缩小到一个分片。在缩小开始时，每个分片的复制都必须在同一节点（node）存在。

缩小工作如下：

* 首先，以相同配置创建目标索引，但是主分片数量减少。
* 然后硬链接（ hard-linking ） 各部分自原索引到目标索引。（如果系统不支持硬链接，那么索引的所有部分都将复制迁移到新索引，将会花费大量时间）
* 最终，将会恢复目标索引，因为目标索引刚被重新打开就会被关闭。

```
curl -XPUT 'localhost:9200/my_source_index/_settings?pretty' -d'
{
  "settings": {
    "index.routing.allocation.require._name": "shrink_node_name",   # 1
    "index.blocks.write": true    #２
  }
}'
```

| [![](https://www.elastic.co/guide/en/elasticsearch/reference/current/images/icons/callouts/1.png)](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-shrink-index.html#CO120-1) | 强制所有分片都复制迁移到名字为`shrink_node_name 的节点上，通过`[Shard Allocation Filtering](https://www.elastic.co/guide/en/elasticsearch/reference/current/shard-allocation-filtering.html) 获取更多设置信息。 |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [![](https://www.elastic.co/guide/en/elasticsearch/reference/current/images/icons/callouts/2.png)](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-shrink-index.html#CO120-2) | 避免索引的所有写操作，但是依然可以修改索引的基本信息，例如删除索引。                                                                                                                                               |

从原索引迁移将会花费一定时间。进度信息可以在所有分片都迁移完成前通过 [`_cat recovery`API](https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-recovery.html) 或者 [`cluster health` API](https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-health.html) 使用 `wait_for_no_relocating_shards` 参数获得。

### Shrinking an index 缩小一个索引

缩小索引 `my_source_index` 到 新的索引 my\_target\_index ，可以用下列请求：

```
curl -XPOST 'localhost:9200/my_source_index/_shrink/my_target_index?pretty'
```

上述请求将会在目标索引信息加入到集群时立即返回——他不会等到缩小操作开始。

**重要：**

* 目标索引存在
* 原索引主分片数量比目标索引多
* 原索引主分片数量是目标索引倍数
* 索引中的所有文档在目标索引将会被缩小到一个分片的数量不会超过 `2,147,483,519`，因为这是一个分片的承受的最大文档数量。
* 执行缩小进程的节点必须要有足够的空闲磁盘空间满足原索引的分片能够全部复制迁徙到该节点。

缩小索引API和创建索引 [`（create index）` API](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html) 相似，并且对于目标索引接受 `settings` 和 `aliases 参数`

```
curl -XPOST 'localhost:9200/my_source_index/_shrink/my_target_index?pretty' -d'
{
  "settings": {
    "index.number_of_replicas": 1,
    "index.number_of_shards": 1,      ＃ 1
    "index.codec": "best_compression"   #　２
  },
  "aliases": {
    "my_search_indices": {}
  }
}'
```

| `}'` |
| ---- |

| [![](https://www.elastic.co/guide/en/elasticsearch/reference/current/images/icons/callouts/1.png)](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-shrink-index.html#CO121-1) | 注意目标分片数量为原分片数量的因子                                        |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
| [![](https://www.elastic.co/guide/en/elasticsearch/reference/current/images/icons/callouts/2.png)](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-shrink-index.html#CO121-2) | best\_compression最佳压缩时只会影响新写到索引的数据,例如当 force-merging 分片。 |

映射（Mappings） 不应该在缩小API中制定，因为所有的 `index.analysis.*`和 `index.similarity.*` 设置都会被原索引配置覆盖。

### Monitoring the shrink process /监测缩小进程

The shrink process can be monitored with the [`_cat recovery` API](https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-recovery.html), or the [`cluster health` API](https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-health.html) can be used to wait until all primary shards have been allocated by setting the `wait_for_status`parameter to `yellow`.

缩小进度可以被 [`_cat recovery` API](https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-recovery.html) 或者 [`cluster health` API](https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-health.html) 所监控。通过设置 wait\_for\_status 为 yellow ，可以等到所有的主分片都已经分配。

缩小API会在目标索引被创建时马上返回，这发生在所有分片被分配之前。这点说明这时所有分片都处于 `unassigned 状态，如果出于任何原因目标索引分片无法分配到执行缩小的节点上，那么主分片状态会一直停留在 unassigned ，直到分片被分配。`

一旦主节点分配成功，会转化状态会 initializing ，缩小进程就开始执行。当缩小操作结束的时候，这些分片会被激活。在这之后,Elasticsearch将试图分配副本,甚至可能决定主分片迁至另一个节点。

### Wait For Active Shards /等待激活分片

因为缩小操作会创建新的索引，所以[wait for active shards](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html#create-index-wait-for-active-shards) 设置依然有效。

## Rollover Index/滚动索引

当现有索引被认为太大或太旧时，滚动索引API会将别名滚动到新的索引。

API接受单个别名和条件列表。 别名只能指向一个索引。 如果索引满足指定的条件，则创建一个新的索引，并将别名切换到指向新的索引。

```
curl -XPUT 'localhost:9200/logs-000001 ?pretty' -d'    ＃ 1
{
  "aliases": {
    "logs_write": {}
  }
}'
# Add > 1000 documents to logs-000001
curl -XPOST 'localhost:9200/logs_write/_rollover ?pretty' -d'   ＃　２
{
  "conditions": {
    "max_age":   "7d",
    "max_docs":  1000
  }
}'
```

| [![](https://www.elastic.co/guide/en/elasticsearch/reference/current/images/icons/callouts/1.png)](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-rollover-index.html#CO122-1) | 创建索引 `logs-0000001` 别名为 `logs_write`.                                                          |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| [![](https://www.elastic.co/guide/en/elasticsearch/reference/current/images/icons/callouts/2.png)](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-rollover-index.html#CO122-2) | 如果 ogs\_write 指向的索引是在7天以前创建的，或者包含1000个以上的文档，则会创建 logs-000002索引，并更新logs\_write别名以指向logs-000002. |

上述可能会返回如下的响应:

```
{
  "acknowledged": true,
  "shards_acknowledged": true,
  "old_index": "logs-000001",
  "new_index": "logs-000002",
  "rolled_over": true, #　１
  "dry_run": false,　　#　２
  "conditions": {　　　　#　３
    "[max_age: 7d]": false,
    "[max_docs: 1000]": true
  }
}
```

| [![](https://www.elastic.co/guide/en/elasticsearch/reference/current/images/icons/callouts/1.png)](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-rollover-index.html#CO123-1) | index 是否被滚动.                      |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
| [![](https://www.elastic.co/guide/en/elasticsearch/reference/current/images/icons/callouts/2.png)](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-rollover-index.html#CO123-2) | Whether the rollover was dry run. |
| [![](https://www.elastic.co/guide/en/elasticsearch/reference/current/images/icons/callouts/3.png)](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-rollover-index.html#CO123-3) | 条件的列表.                            |

### Naming the new index/新索引名称

如果现有索引的名称以 - 和数字结尾。 logs-000001 - 然后新索引的名称将遵循相同的模式，增加数字（logs-000002）。 无论旧索引名称如何，编号为零填充长度为6。

如果旧名称与此模式不匹配，则必须按照如下所示,指定新索引的名称：

```
curl -XPOST 'localhost:9200/my_alias/_rollover/my_new_index_name?pretty' -d'
{
  "conditions": {
    "max_age":   "7d",
    "max_docs":  1000
  }
}'
```

### Using date math with the rolllover API/使用滚动API的日期计算

使用[日期计算](https://www.elastic.co/guide/en/elasticsearch/reference/current/date-math-index-names.html): 根据索引滚动的日期来命名滚动索引是有用的技术，例如`logstash-2016.02.03`.。 滚动API支持日期，但要求索引名称以一个破折号后跟一个数字，例如 logstash-2016.02.03-1，每次索引滚动时都会增加。 例如

```
# PUT /<logs-{now/d}-1> with URI encoding:
curl -XPUT 'localhost:9200/%3Clogs-%7Bnow%2Fd%7D-1%3E ?pretty' -d' #　１
{
  "aliases": {
    "logs_write": {}
  }
}'
curl -XPUT 'localhost:9200/logs_write/log/1?pretty' -d'
{
  "message": "a dummy log"
}'
# Wait for a day to pass
curl -XPOST 'localhost:9200/logs_write/_rollover ?pretty' -d'　#　２
{
  "conditions": {
    "max_docs":   "1"
  }
}'
```

| [![](https://www.elastic.co/guide/en/elasticsearch/reference/current/images/icons/callouts/1.png)](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-rollover-index.html#CO124-1) | `创建当日的索引logs-2016.10.31-1`                                                 |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| [![](https://www.elastic.co/guide/en/elasticsearch/reference/current/images/icons/callouts/2.png)](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-rollover-index.html#CO124-2) | 当日索引滚动, 立即生成如. `logs-2016.10.31-000002` , 或者`logs-2016.11.01-000002` 24小时后 |

然后可以按照[日期数学文档](https://www.elastic.co/guide/en/elasticsearch/reference/current/date-math-index-names.html) 中的描述来引用这些索引。 例如，要搜索过去三天创建的索引，您可以执行以下操作：

```
# GET /<logs-{now/d}-*>,<logs-{now/d-1d}-*>,<logs-{now/d-2d}-*>/_search
curl -XGET 'localhost:9200/%3Clogs-%7Bnow%2Fd%7D-*%3E%2C%3Clogs-%7Bnow%2Fd-1d%7D-*%3E%2C%3Clogs-%7Bnow%2Fd-2d%7D-*%3E/_search?pretty'
```

### Defining the new index/定义新索引

新索引的设置，映射和别名取自任何匹配的[索引模板](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templates.html)。 此外，您可以在请求正文中指定设置，映射和别名，就像[create index](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html)API一样。 请求中指定的值覆盖匹配索引模板中设置的任何值。 例如，以下滚动请求将覆盖index.number\_of\_shardssetting：

```
curl -XPUT 'localhost:9200/logs-000001?pretty' -d'
{
  "aliases": {
    "logs_write": {}
  }
}'
curl -XPOST 'localhost:9200/logs_write/_rollover?pretty' -d'
{
  "conditions" : {
    "max_age": "7d",
    "max_docs": 1000
  },
  "settings": {
    "index.number_of_shards": 2
  }
}'
```

### Dry run/干运行

滚动API支持dry\_run模式，可以在不执行实际滚动的情况下检查请求条件：

```
curl -XPUT 'localhost:9200/logs-000001?pretty' -d'
{
  "aliases": {
    "logs_write": {}
  }
}'
curl -XPOST 'localhost:9200/logs_write/_rollover?dry_run&pretty' -d'
{
  "conditions" : {
    "max_age": "7d",
    "max_docs": 1000
  }
}'
```

### Wait For Active Shards/等待激活分片

因为滚动操作会创建一个新的索引，因此在创建索引时的wait\_for\_active\_shards 设置也适用于滚动操作。
