前言
提示:以下是本篇文章正文内容,下面案例可供参考
一、新增索引
代码如下(示例):
/**
* 功能描述: 新增索引
* @param indexName 索引名字
* @param mapping 映射
* @param replicas 副本
* @param shards 分片
* @return : void
*/
public CreateIndexResponse indexCreation(String indexName, String mapping, Integer replicas, Integer shards) throws IOException, IndexException {
//1.使用client获取操作索引对象
GetIndexRequest getIndexRequest = new GetIndexRequest(indexName);
IndicesClient indices = restHighLevelClient.indices();
boolean exists = indices.exists(getIndexRequest, RequestOptions.DEFAULT);
if (exists) {
log.error(String.valueOf(ResponseEnum.INDEX_EXISTENCE));
throw new IndexException(ResponseEnum.INDEX_EXISTENCE);
}
//2.1 设置索引名称 你要添加的数据库名称
CreateIndexRequest request = new CreateIndexRequest(indexName);//这里数据库名不能小写大写一块用
Map map = new HashMap();
map.put("number_of_replicas", replicas);
map.put("number_of_shards", shards);
request.settings(map);
request.mapping(mapping, XContentType.JSON);
CreateIndexResponse createIndexResponse = null;
try {
createIndexResponse = indices.create(request, RequestOptions.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
log.error("创建索引失败--{}", e);
}
return createIndexResponse;
}
controller
public BaseResponse indexCreation(@RequestParam("indexName") String indexName, @RequestBody String mapping, @RequestParam("replicas") Integer replicas, @RequestParam("shards") Integer shards) throws IOException, IndexException {
CreateIndexResponse createIndexResponse = searchService.indexCreation(indexName, mapping, replicas, shards);
if (createIndexResponse == null) {
BaseResponse baseResponse = new BaseResponse(ResponseEnum.INDEX_FAIL.getCode(), false