备注:elasticsearch6.x以后一个index只能存在一个type。以下代码仅供参考,涉及的参数需要根据使用场景进行修改。
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.3.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version6.3.2</version>
</dependency>
//初始化client
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1", 9200, "http")));
//删除索引
public boolean deleteIndex(String index){
DeleteIndexRequest request = new DeleteIndexRequest(index);
request.indicesOptions(IndicesOptions.lenientExpandOpen());
DeleteIndexResponse = client.indices().delete(request);
return deleteIndexResponse.isAcknowledged();
}
//创建索引
public boolean createIndex(String index,String alias,int
numberOfShards,int numberOfRelicas){
CreateIndexRequest request = new CreateIndexRequest(index);
request.settings(Settings.builder()
.put("index.number_of_shards", numberOfShards)
.put("index.number_of_replicas", numberOfRelicas)
);
//如果不需要指定字段属性可以忽略以下mapping设置,新增文档后会自动创建mapping
request.mapping("data",
" {\n" +
" \""+type+"\": {\n" +
" \"properties\": {\n" +
需要的设计的字段属性+
" }\n" +
" }\n" +
" }",
XContentType.JSON);
//设置别名
if(alias != null && !alias.equals("")){
request.alias(
new Alias(alias)
);
}
CreateIndexResponse createIndexResponse = client.indices().create(request);
return createIndexResponse.isAcknowledged();
}
//判断索引是否存在
public boolean isIndexExists(String index){
GetIndexRequest request = new GetIndexRequest();
request.indices(index);
request.local(false);
request.humanReadable(true);
boolean exists = client.indices().exists(request) ;
return exists;
}