前一章讲过如何将SpringBoot -ElasticSearch的高级客户端RestHighLevelClient 整合
这一章是使用RestHighLevelClient 进行Index操作
ElasticSearch计划7.X移出type,不再有type的操作,所有本文中将type和Index名称设置为相同的名字.
官方API地址Java High Level REST Client
这篇就关于使用RestClient操作索引,内容就是解决问题的实例。同样,一切版本以6.4.2为准。其他升级版本新的api不属此列。
添加Index
由于使用RestHighLevelClient(后称为rhlClient)时,进行Index操作,所有IndexRequest都会校验Index,type,source,contentType不为空。
所有构建创建Index创建请求时需要将Index,type,source,contentType配置完整
因为整合了ik中文分词器,所以“analyzer”: “ik_max_word”此处参考安装配置ik分词器
public boolean indexCreate() {
try {
CreateIndexRequest index = new CreateIndexRequest("index_name");
Map<String,Object> properties = Maps.newHashMap();
Map<String,Object> propertie = Maps.newHashMap();
propertie.put("type","text");
propertie.put("index",true);
propertie.put("analyzer","ik_max_word");
properties.put("field_name",propertie);
XContentBuilder builder = JsonXContent.contentBuilder();
builder.startObject()
.startObject("mappings")
.startObject("index_name")
.field("properties",properties)
.endObject()
.endObject()
.startObject("settings")
.field("number_of_shards",3)
.field("number_of_replicas",1)
.endObject()
.endObject();
index.source(builder);
rhlClient.indices().create(index,RequestOptions.DEFAULT);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
判断Index是否存在
public boolean indexExists(String indexName) {
GetIndexRequest request = new GetIndexRequest();
request.indices(indexName);
try {
return rhlClient.indices().exists(request, RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
删除Index
public boolean deleteIndex(String indexName) {
DeleteIndexRequest index = new DeleteIndexRequest(indexName);
try {
rhlClient.indices().delete(index);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}