java操作elasticsearch索引判断 添加 删除

@Autowired
 private RestHighLevelClient restHighLevelClient;
//判断索引是否存在
 public Boolean isExistIndex(String... indexName){
     GetIndexRequest getIndexRequest = new GetIndexRequest();
     getIndexRequest.indices(indexName);
     try {
         Boolean exists = restHighLevelClient.indices().exists(getIndexRequest,RequestOptions.DEFAULT);
         return exists;
     }catch (Exception e){
         log.error(e.getMessage());
     }
     return false;
 }
/**
 * 删除索引
 *
 * @param indexName
 * @return
 */
public boolean deleteIndex(String indexName) {
    boolean acknowledged = false;
    try {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexName);
        deleteIndexRequest.indicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN);
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        acknowledged = delete.isAcknowledged();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return acknowledged;
}
/**
 * 创建索引
 *
 * @param indices
 * @return
 */
public void createIndex(String... indices){
    if(indices != null && indices.length > 0){
        for(String index : indices){
            if(!isExistsIndex(index)){
                CreateIndexRequest
                        createIndexRequest =
                        new CreateIndexRequest();
                createIndexRequest.index(index);
                try{
                    CreateIndexResponse
                            createIndexResponse =
                            restHighLevelClient.indices()
                                    .create(createIndexRequest,
                                            RequestOptions.DEFAULT);
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
}

 

经验分享 程序员 微信小程序 职场和发展