5 索引操作

5.1 创建索引

创建索引时学习elasticsearch中最为重要的一部分,可以通过工具(head/kibana)或Rest API创建,当然kibana也是API.

注意:

  1. 索引名称不能有大写字母
  2. 索引名是唯一的,不能重复,重复创建会出错

5.1.1 通过head插件新建索引

在 head 插件中,选择 索引选项卡,然后点击新建索引。新建索引时,需要填入索引名称、分片数以及副本数。

5.1.2 通过API(kibana)

创建索引的请求:

PUT test2

创建成功后,接口返回:

{
  "acknowledged" : true,
  "shards_acknowledged" : true,
  "index" : "test2"
}

查看索引信息:

GET test2

接口返回

{
  "test2" : {
    "aliases" : { },
    "mappings" : { },
    "settings" : {
      "index" : {
        "creation_date" : "1636524358633",
        "number_of_shards" : "1",
        "number_of_replicas" : "1",
        "uuid" : "gChiYR4iTt-YQ4OMYVmcwQ",
        "version" : {
          "created" : "7040099"
        },
        "provided_name" : "test2"
      }
    }
  }
}

5.2 更新索引

索引创建好之后,可以修改其属性。
例如修改索引的副本数:

PUT test2/_settings
{
  "number_of_replicas": 2
}

5.3 修改索引的读写权限

索引创建成功后,默认是open状态,索引是具备读写权限的,可以向索引中写入文档:

请求:
PUT test2/_doc/111
{
  "title":"在test2中我是第一个文档"
}
返回:
{
  "_index" : "test2",
  "_type" : "_doc",
  "_id" : "111",
  "_version" : 1,
  "result" : "created",
  "_shards" : {
    "total" : 3,
    "successful" : 3,
    "failed" : 0
  },
  "_seq_no" : 0,
  "_primary_term" : 1
}

关闭索引的写权限

请求:
PUT test2/_settings
{
  "blocks.write": true
}

结果:
{
  "acknowledged" : true
}

开启写锁后,无法向索引中写入文档:

{
  "error": {
    "root_cause": [
      {
        "type": "cluster_block_exception",
        "reason": "index [test2] blocked by: [FORBIDDEN/8/index write (api)];"
      }
    ],
    "type": "cluster_block_exception",
    "reason": "index [test2] blocked by: [FORBIDDEN/8/index write (api)];"
  },
  "status": 403
}

其他类似的权限有:

  • blocks.write
  • blocks.read
  • blocks.read_only

5.4 查看索引:

查看单个索引
GET book/_settings
查看多个索引
GET book,test/_settings
查看所有索引
GET _all/_settings

5.5 删除索引

  1. head 插件可以删除索引
  2. rest api

DELETE test

5.6 索引打开/关闭

关闭索引:POST book/_close
打开索引:POST book/_open

可以同时关闭/打开多个索引,多个索引用 , 隔开,或者直接使用 _all 代表所有索引

5.7 复制索引

索引复制,只会复制数据,不会复制索引配置。


POST _reindex
{  
         "source": {"index":"test_old"},  
         "dest": {"index":"test_new"}
}

复制的时候,可以添加查询条件

5.8 索引别名

可以为索引创建别名,如果这个别名是唯一的,该别名可以代替索引名称。

POST /_aliases
{
  "actions": [
    {
      "add": {
        "index": "test",
        "alias": "test_alias"
      }
    }
  ]
}

将 add 改为 remove 就表示移除别名:

POST /_aliases
{
  "actions": [
    {
      "remove": {
        "index": "test",
        "alias": "test_alias"
      }
    }
  ]
}

查看某一个索引的别名:

GET /book/_alias

查看某一个别名对应的索引(test_alias 表示一个别名):

GET /test_alias/_alias

可以查看集群上所有可用别名

GET /_alias

posted on 2021-11-12 14:39  --工具人  阅读(113)  评论(0编辑  收藏  举报