一、有关ElasticSearch的部署,网上的资料非常多,可以自行搜索搭建
二、jar包的引入,如下:
二、jar包的引入,如下:
<!--elasticsearch-->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.2.4</version>
</dependency>
<!-- jest -->
<dependency>
<groupId>io.searchbox</groupId>
<artifactId>jest</artifactId>
<version>2.0.0</version>
</dependency>
三、采用Spring注入的方式,将JestClient注入
@Configuration
public class JestConfiguration {
@Value("${ES_CONNECT_IP_ONE}")
private String ES_CONNECT_IP_ONE;
@Value("${ES_NODE_CLIENT_PORT}")
private String ES_NODE_CLIENT_PORT;
@Value("${ES_CLUSTER_NAME}")
private String ES_CLUSTER_NAME;
public @Bean
HttpClientConfig httpClientConfig() {
HttpClientConfig httpClientConfig = new HttpClientConfig
.Builder("http://"+ES_CONNECT_IP_ONE+":"+ES_NODE_CLIENT_PORT+"/")
.gson(new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create())
.multiThreaded(true)
.readTimeout(10000)
.build();
return httpClientConfig;
}
public @Bean
JestClient jestClient() {
JestClientFactory factory = new JestClientFactory();
factory.setHttpClientConfig(httpClientConfig());
System.out.println("获得ES客户端连接:" + factory.getObject());
return factory.getObject();
}
}
四、创建索引
1、创建索引之前判断是否存在要创建的索引,如果已经存在索引需要删除之后重新创建
/**
* 创建索引之前,删除以前的
*
* @param jestClient
* @param indexName
*/
private Boolean beforRemoveIndex(JestClient jestClient, String indexName) {
Boolean isDeleteSuccess = true;
try {
JestUtil jestUtil = new JestUtil();
Boolean indicesExists = jestUtil.indicesExists(jestClient, indexName);
if (indicesExists) {
System.out.println(("导入数据的索引indexName:{}已经存在,删除之后再导入数据" + indexName));
isDeleteSuccess = jestUtil.deleteIndex(jestClient, indexName);
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return isDeleteSuccess;
}
2、创建索引
JestResult execute = jestClient.execute(new CreateIndex.Builder(indexName.toLowerCase()).build());
五、注意
1、mapping的创建,前提条件是索引必须存在
2、索引必须是全部小写的字母,索引的type大小写都可以