Elasticsearch:如何把一个索引变为只读

948 阅读1分钟

将索引设置为只读可能听起来很奇怪,但在 Elasticsearch 中执行此类操作是可能的。想象一下这样一种情况,你特别需要限制对索引的写入操作,无论是维护、业务规则还是任何其他原因。让我们学习如何将索引配置为已读以及如何撤消操作。

我们先使用如下的命令来创建一个叫做 test 的索引:



1.  PUT test/_doc/1
2.  {
3.    "content": "I am xiaoguo from Elastic"
4.  }


设置为只读

要进行此更改,我们需要更新索引设置。 下面的命令将使索引成为只读的。



1.  PUT /test/_settings
2.  {
3.    "index": {
4.      "blocks": {
5.        "write": true
6.      }
7.    }
8.  }


执行完上面的命令后,我们可以再接着创建一个如下的一个文档:



1.  PUT test/_doc/2
2.  {
3.    "content": "I am an evangelist as well"
4.  }


我们可以看到如下的一个响应:



1.  {
2.    "error": {
3.      "root_cause": [
4.        {
5.          "type": "cluster_block_exception",
6.          "reason": "index [test] blocked by: [FORBIDDEN/8/index write (api)];"
7.        }
8.      ],
9.      "type": "cluster_block_exception",
10.      "reason": "index [test] blocked by: [FORBIDDEN/8/index write (api)];"
11.    },
12.    "status": 403
13.  }


要恢复只需将状态从 true 更改为 false。我们试着运行如下的命令:



1.  PUT /test/_settings
2.  {
3.    "index": {
4.      "blocks": {
5.        "write": false
6.      }
7.    }
8.  }


我们再次写入我们想要的文档。我们可以看到这次的写入是成功的:



1.  PUT test/_doc/2
2.  {
3.    "content": "I am an evangelist as well"
4.  }


上面的响应为:



1.  {
2.    "_index": "test",
3.    "_id": "2",
4.    "_version": 1,
5.    "result": "created",
6.    "_shards": {
7.      "total": 2,
8.      "successful": 1,
9.      "failed": 0
10.    },
11.    "_seq_no": 1,
12.    "_primary_term": 1
13.  }


希望这个能帮助到你。