ElasticSearch为了便于处理索引管理(Indices administration)请求,提供了

org.elasticsearch.client.IndicesAdminClient接口。通过如下代码从 Client 对象中获得这个接口的实现:


1.  
1.   IndicesAdminClient indicesAdminClient = client.admin().indices();


IndicesAdminClient定义了好几种prepareXXX()方法作为创建请求的入口点。

1. 索引存在API

索引存在API用于检查集群中是否存在由prepareExists调用指定的索引。


1.  
1.      /**
2.       * 判断索引是否存在
3.    
4.    
5.    
6.    
7.      publicstaticbooleanisIndexExists(Client client,String index){
8.    
9.          if(Objects.equal(client,null)){
10.             logger.info("---------IndexAPI isIndexExists 请求客户端为null");
11.             returnfalse;
12.         }
13.   
14.         if(StringUtils.isBlank(index)){
15.             logger.info("---------IndexAPI isIndexExists 索引名称为空");
16.             returnfalse;
17.         }
18.   
19.         IndicesAdminClientindicesAdminClient = client.admin().indices();
20.         IndicesExistsResponse response =indicesAdminClient.prepareExists(index).get();
21.         return response.isExists();
22.   
23.         /* 另一种方式
24.   
25.   
26.     }


 

prepareExists()可以同时指定多个索引:

1.  
1.   IndicesExistsResponse response = indicesAdminClient.prepareExists(index1, index2 ....).get();

 

2. 类型存在API

类型存在API和索引存在API类似,只是不是用来检查索引是否存在,而是检查指定索引下的指定类型是否存在。为了确保成功返回结果,请确保索引已经存在,否则不会查找到指定的类型。下面代码演示查找索引下的指定类型:


1.  
1.      /**
2.       * 判断类型是否存在
3.    
4.    
5.    
6.    
7.    
8.      publicstaticboolean isTypeExists(Client client,String index,String type){
9.    
10.         if(!isIndexExists(client, index)){
11.             logger.info("--------- isTypeExists 索引 [{}]  不存在",index);
12.             returnfalse;
13.         }
14.   
15.         IndicesAdminClient indicesAdminClient = client.admin().indices();
16.         TypesExistsResponse response = indicesAdminClient.prepareTypesExists(index).setTypes(type).get();
17.         return response.isExists();
18.   
19.     }


 

3. 创建索引API

创建索引API可以用来建立一个新索引。我们可以创建空索引或者给它设置它的映射(mapping)和设置信息(settings)。

3.1 创建空索引

下面代码创建了一个空索引:

1.  
1.      /**
2.       * 创建空索引  默认setting 无mapping
3.    
4.    
5.    
6.    
7.      publicstaticboolean createSimpleIndex(Client client,String index){
8.    
9.          IndicesAdminClient indicesAdminClient = client.admin().indices();
10.         CreateIndexResponse response = indicesAdminClient.prepareCreate(index).get();
11.         return response.isAcknowledged();
12.   
13.     }

查看索引状态信息:


1.  
1.   {
2.      "state":"open",
3.      "settings":{
4.          "index":{
5.              "creation_date":"1476078197394",
6.              "number_of_shards":"5",
7.              "number_of_replicas":"1",
8.              "uuid":"rBATEkx_SBq_oUEIlW8ryQ",
9.              "version":{
10.                 "created":"2030399"
11.             }
12.         }
13.     },
14.     "mappings":{
15.   
16.     },
17.     "aliases":[
18.   
19.     ]
20.  }


 

3.2. 创建复杂索引

下面代码创建复杂索引,给它设置它的映射(mapping)和设置信息(settings),指定分片个数为3,副本个数为2,同时设置school字段不分词。

1.  
1.      /**
2.       * 创建索引指定setting
3.    
4.    
5.    
6.    
7.      publicstaticboolean createIndex(Client client,String index){
8.    
9.          //settings
10.         Settings settings =Settings.builder().put("index.number_of_shards",3).put("index.number_of_replicas",2).build();
11.   
12.         // mapping
13.         XContentBuilder mappingBuilder;
14.         try{
15.             mappingBuilder  =XContentFactory.jsonBuilder()
16.                     .startObject()
17.                         .startObject(index)
18.                            .startObject("properties")
19.                                .startObject("name").field("type","string").field("store","yes").endObject()
20.                                .startObject("sex").field("type","string").field("store","yes").endObject()
21.                                .startObject("college").field("type","string").field("store","yes").endObject()
22.                                .startObject("age").field("type","integer").field("store","yes").endObject()
23.                                .startObject("school").field("type","string").field("store","yes").field("index","not_analyzed").endObject()
24.                            .endObject()
25.                         .endObject()
26.                     .endObject();
27.         }catch(Exception e){
28.             logger.error("--------- createIndex 创建 mapping  失败:",e);
29.             returnfalse;
30.         }
31.   
32.         IndicesAdminClient indicesAdminClient = client.admin().indices();
33.         CreateIndexResponse response = indicesAdminClient.prepareCreate(index)
34.                 .setSettings(settings)
35.                 .addMapping(index, mappingBuilder)
36.                 .get();
37.   
38.         return response.isAcknowledged();
39.   
40.     }


查看索引状态信息:


1.  
1.   {
2.      "state":"open",
3.      "settings":{
4.          "index":{
5.              "creation_date":"1476078400025",
6.              "number_of_shards":"3",
7.              "number_of_replicas":"2",
8.              "uuid":"ToakRDisSYyX7vjH30HR-g",
9.              "version":{
10.                 "created":"2030399"
11.             }
12.         }
13.     },
14.     "mappings":{
15.         "simple-index":{
16.             "properties":{
17.                 "college":{
18.                     "store":true,
19.                     "type":"string"
20.                 },
21.                 "school":{
22.                     "index":"not_analyzed",
23.                     "store":true,
24.                     "type":"string"
25.                 },
26.                 "sex":{
27.                     "store":true,
28.                     "type":"string"
29.                 },
30.                 "name":{
31.                     "store":true,
32.                     "type":"string"
33.                 },
34.                 "age":{
35.                     "store":true,
36.                     "type":"integer"
37.                 }
38.             }
39.         }
40.     },
41.     "aliases":[
42.   
43.     ]
44.  }



4. 删除索引

删除索引API允许我们反向删除一个或者多个索引。


1.  
1.      /**
2.       * 删除索引
3.    
4.    
5.    
6.      publicstaticboolean deleteIndex(Client client,String index){
7.    
8.          IndicesAdminClient indicesAdminClient = client.admin().indices();
9.          DeleteIndexResponse response = indicesAdminClient.prepareDelete(index).execute().actionGet();
10.         return response.isAcknowledged();
11.   
12.     }



5. 关闭索引

关闭索引API允许我们关闭不使用的索引,进而释放节点和集群的资源,如cpu时钟周期和内存。

1.  
1.      /**
2.       * 关闭索引
3.    
4.    
5.    
6.    
7.      publicstaticboolean closeIndex(Client client,String index){
8.    
9.          IndicesAdminClient indicesAdminClient = client.admin().indices();
10.         CloseIndexResponse response = indicesAdminClient.prepareClose(index).get();
11.         return response.isAcknowledged();
12.     }


测试:


1.  
1.      @Test
2.      publicvoidcloseIndex()throwsException{
3.          String index ="suggestion-index";
4.          if(!IndexAPI.isIndexExists(client, index)){
5.              logger.info("--------- closeIndex 索引 [{}]  不存在", index);
6.              return;
7.          }
8.    
9.          boolean result =IndexAPI.closeIndex(client, index);
10.         logger.info("---------closeIndex {}",result);
11.     }


关闭之前:

关闭之后:

6. 打开索引

打开索引API允许我们打开我们之前使用关闭索引API

1.  
1.      /**
2.       * 关闭索引
3.    
4.    
5.    
6.    
7.      publicstaticboolean openIndex(Client client,String index){
8.    
9.          IndicesAdminClient indicesAdminClient = client.admin().indices();
10.         OpenIndexResponse response = indicesAdminClient.prepareOpen(index).get();
11.         return response.isAcknowledged();
12.     }


7. 设置映射API

设置映射API允许我们在指定索引上一次性创建或修改一到多个索引的映射。如果设置映射必须确保指定的索引必须存在,否则会报错。


1.  
1.      /**
2.       * 设置映射
3.    
4.    
5.    
6.    
7.    
8.      publicstaticboolean putIndexMapping(Client client,String index,String type){
9.    
10.         // mapping
11.         XContentBuilder mappingBuilder;
12.         try{
13.             mappingBuilder  =XContentFactory.jsonBuilder()
14.                     .startObject()
15.                         .startObject(type)
16.                            .startObject("properties")
17.                                .startObject("name").field("type","string").field("store","yes").endObject()
18.                                .startObject("sex").field("type","string").field("store","yes").endObject()
19.                                .startObject("college").field("type","string").field("store","yes").endObject()
20.                                .startObject("age").field("type","long").field("store","yes").endObject()
21.                                .startObject("school").field("type","string").field("store","yes").field("index","not_analyzed").endObject()
22.                            .endObject()
23.                         .endObject()
24.                     .endObject();
25.         }catch(Exception e){
26.             logger.error("--------- createIndex 创建 mapping  失败:", e);
27.             returnfalse;
28.         }
29.   
30.         IndicesAdminClient indicesAdminClient = client.admin().indices();
31.         PutMappingResponse response = indicesAdminClient.preparePutMapping(index).setType(type).setSource(mappingBuilder).get();
32.         return response.isAcknowledged();
33.   
34.     }


先创建一个空索引,这样该索引上不会有映射,再使用下面代码添加映射:


1.  
1.      @Test
2.      publicvoidputIndexMapping()throwsException{
3.          String index ="simple-index";
4.          String type ="simple-type";
5.    
6.          if(!IndexAPI.isIndexExists(client, index)){
7.              logger.info("--------- putIndexMapping 索引 [{}]  不存在", index);
8.              return;
9.          }
10.   
11.         boolean result =IndexAPI.putIndexMapping(client, index, type);
12.         logger.info("---------putIndexMapping {}",result);
13.     }


添加映射之后的索引信息:

1.  
1.   {
2.      "state":"open",
3.      "settings":{
4.          "index":{
5.              "creation_date":"1476108496237",
6.              "number_of_shards":"5",
7.              "number_of_replicas":"1",
8.              "uuid":"9SR5OQJ-QLSARFjmimvs1A",
9.              "version":{
10.                 "created":"2030399"
11.             }
12.         }
13.     },
14.     "mappings":{
15.         "simple-type":{
16.             "properties":{
17.                 "college":{
18.                     "store":true,
19.                     "type":"string"
20.                 },
21.                 "school":{
22.                     "index":"not_analyzed",
23.                     "store":true,
24.                     "type":"string"
25.                 },
26.                 "sex":{
27.                     "store":true,
28.                     "type":"string"
29.                 },
30.                 "name":{
31.                     "store":true,
32.                     "type":"string"
33.                 },
34.                 "age":{
35.                     "store":true,
36.                     "type":"long"
37.                 }
38.             }
39.         }
40.     },
41.     "aliases":[
42.   
43.     ]
44.  }


 

8. 别名API

别名API允许我们可以为已经存在的索引创建别名

1.  
1.      /**
2.       * 为索引创建别名
3.    
4.    
5.    
6.    
7.    
8.      publicstaticboolean addAliasIndex(Client client,String index ,String alias){
9.    
10.         IndicesAdminClient indicesAdminClient = client.admin().indices();
11.         IndicesAliasesResponse response = indicesAdminClient.prepareAliases().addAlias(index, alias).get();
12.         return response.isAcknowledged();
13.   
14.     }

测试:下面代码为simple-index索引创建一个别名为simple:

1.  
1.      @Test
2.      publicvoidaddAliasIndex()throwsException{
3.          String index ="simple-index";
4.          String aliasName ="simple";
5.          boolean result =IndexAPI.addAliasIndex(client, index, aliasName);
6.          logger.info("---------addAliasIndex {}", result);
7.      }


结果图:

 

9.  别名存在API

别名存在API允许我们检查是否存在至少一个我们列举出的的别名,注意是判断的索引别名,不是索引。我们可以在别名中使用星号通配符。


1.  
1.      /**
2.       * 判断别名是否存在
3.    
4.    
5.    
6.    
7.      publicstaticboolean isAliasExist(Client client,String... aliases){
8.    
9.          IndicesAdminClient indicesAdminClient = client.admin().indices();
10.         AliasesExistResponse response = indicesAdminClient.prepareAliasesExist(aliases).get();
11.         return response.isExists();
12.   
13.     }


测试,下面代码检查以sim开头的索引别名和test索引别名是否存在,我们列举的索引别名只要有一个存在就会返回true。

1.  
1.      @Test
2.      publicvoidisAliasExist()throwsException{
3.          String aliasName ="simp*";
4.          String aliasName2 ="test";
5.          boolean result =IndexAPI.isAliasExist(client, aliasName, aliasName2);
6.          logger.info("---------isAliasExist {}", result);// true
7.      }

 

10. 获取别名API

获取别名API可以列举出当前已经定义的的别名


1.  
1.      /**
2.       * 获取别名
3.    
4.    
5.    
6.      publicstaticvoid getAliasIndex(Client client,String... aliases){
7.    
8.          IndicesAdminClient indicesAdminClient = client.admin().indices();
9.          GetAliasesResponse response = indicesAdminClient.prepareGetAliases(aliases).get();
10.         ImmutableOpenMap<String,List<AliasMetaData>> aliasesMap = response.getAliases();
11.   
12.         UnmodifiableIterator<String> iterator = aliasesMap.keysIt();
13.   
14.         while(iterator.hasNext()){
15.             String key = iterator.next();
16.             List<AliasMetaData> aliasMetaDataList = aliasesMap.get(key);
17.             for(AliasMetaData aliasMetaData : aliasMetaDataList){
18.                 logger.info("--------- getAliasIndex {}", aliasMetaData.getAlias());
19.             }
20.         }
21.     }


测试,下面代码展示以sim开头的别名和test别名:

1.  
1.      @Test
2.      publicvoidgetAliasIndex()throwsException{
3.          String aliasName ="simp*";
4.          String aliasName2 ="test";
5.          IndexAPI.getAliasIndex(client, aliasName, aliasName2);// simpletest
6.      }

 

11. 删除别名API

删除别名API允许我们删除指定索引的别名,如果索引没有该别名,则会报错

1.  
1.      /**
2.       * 删除别名
3.    
4.    
5.    
6.    
7.    
8.      publicstaticboolean deleteAliasIndex(Client client,String index,String... aliases){
9.    
10.         IndicesAdminClient indicesAdminClient = client.admin().indices();
11.         IndicesAliasesResponse response = indicesAdminClient.prepareAliases().removeAlias(index, aliases).get();
12.         return response.isAcknowledged();
13.   
14.     }

测试,下面代码删除test-index索引的别名test:


1.  
1.      @Test
2.      publicvoid deleteAliasIndex()throwsException{
3.          String index ="test-index";
4.          String aliasName ="test";
5.    
6.          boolean result =IndexAPI.deleteAliasIndex(client, index, aliasName);
7.          logger.info("---------deleteAliasIndex {}", result);// true
8.      }


 

12. 更新设置API

更新设置API允许我们更新特定索引或全部索引的设置。

1.  
1.      /**
2.       * 更新设置
3.    
4.    
5.    
6.    
7.    
8.      publicstaticboolean updateSettingsIndex(Client client,String index,Settings settings){
9.    
10.         IndicesAdminClient indicesAdminClient = client.admin().indices();
11.         UpdateSettingsResponse response = indicesAdminClient.prepareUpdateSettings(index).setSettings(settings).get();
12.         return response.isAcknowledged();
13.   
14.     }

测试,下面代码更改副本数为2,修改分片个数会报错:

1.  
1.      @Test
2.      publicvoidupdateSettingsIndex()throwsException{
3.          String index ="test-index";
4.          Settings settings =Settings.builder().put("index.number_of_replicas",2).build();
5.    
6.          if(!IndexAPI.isIndexExists(client, index)){
7.              logger.info("--------- updateSettingsIndex 索引 [{}]  不存在", index);
8.              return;
9.          }
10.   
11.         boolean result =IndexAPI.updateSettingsIndex(client, index, settings);
12.         logger.info("---------updateSettingsIndex {}", result);// true
13.     }

 

13. 索引统计API

索引统计API可以提供关于索引,文档,存储以及操作的信息,如获取,查询,索引等。这些信息按类别进行了划分,如果需要输出特定信息需要在请求时指定。下面代码演示了获取指定索引的全部信息:

1.  
1.      /**
2.       * 索引统计
3.    
4.    
5.    
6.      publicstaticvoid indexStats(Client client,String index){
7.    
8.          IndicesAdminClient indicesAdminClient = client.admin().indices();
9.          IndicesStatsResponse response = indicesAdminClient.prepareStats(index).all().get();
10.   
11.         ShardStats[] shardStatsArray = response.getShards();
12.         for(ShardStats shardStats : shardStatsArray){
13.             logger.info("shardStats {}",shardStats.toString());
14.         }
15.   
16.         Map<String,IndexStats> indexStatsMap = response.getIndices();
17.         for(String key : indexStatsMap.keySet()){
18.             logger.info("indexStats {}", indexStatsMap.get(key));
19.         }
20.   
21.         CommonStats commonStats = response.getTotal();
22.         logger.info("totalcommonStats {}",commonStats.toString());
23.   
24.         commonStats  = response.getPrimaries();
25.         logger.info("primariescommonStats {}", commonStats.toString());
26.   
27.     }