在Spring boot中主要有Java REST Client、spring-data-elasticsearch两种方式,这里建议使用Elasticsearch官方提供的Java High Level REST Client来集成。
一:导入依赖:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.10.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.10.2</version>
</dependency>
创建es映射
PUT user_index
{
"settings":{
"number_of_shards": "3",
"number_of_replicas": "0"
},
"mappings": {
"properties":{
"age" : {
"type" : "short"
},
"createTime" : {
"type" : "long"
},
"id" : {
"type" : "integer"
},
"updateTime" : {
"type" : "long"
},
"userName" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword"
}
}
}
}
}
}
二:初始化客户端
1,添加配置文件添加连接信息
elasticsearch:
host: 127.0.0.1:9200
port: 9200
connTimeout: 3000
socketTimeout: 5000
connectionRequestTimeout: 1000
username: elastic
password: 123456
2,添加ES配置类
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
/**
* @date 2022/7/15
**/
@Configuration
public class ElasticsearchConfiguration {
@Value("${elasticsearch.host}")
private String host;
@Value("${elasticsearch.port}")
private Integer port;
@Value("${elasticsearch.connTimeout}")
private Integer connTimeout;
@Value("${elasticsearch.socketTimeout}")
private Integer socketTimeout;
@Value("${elasticsearch.connectionRequestTimeout}")
private Integer connectionRequestTimeout;
@Value("${elasticsearch.username}")
private String username;
@Value("${elasticsearch.password}")
private String password;
@Bean(destroyMethod = "close", name = "client")
public RestHighLevelClient initRestClient() {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
RestClientBuilder builder = RestClient.builder(toHttpHost())
.setRequestConfigCallback(requestConfigBuilder ->
requestConfigBuilder.setConnectTimeout(connTimeout)
.setSocketTimeout(socketTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout))
.setHttpClientConfigCallback(h -> h.setDefaultCredentialsProvider(credentialsProvider));
return new RestHighLevelClient(builder);
}
/**
* 解析配置的字符串,转为HttpHost对象数组
*/
private HttpHost[] toHttpHost() {
if (!StringUtils.hasLength(host)) {
throw new RuntimeException("invalid elasticsearch configuration");
}
String[] hostArray = host.split(",");
HttpHost[] httpHosts = new HttpHost[hostArray.length];
HttpHost httpHost;
for (int i = 0; i < hostArray.length; i++) {
String[] strings = hostArray[i].split(":");
httpHost = new HttpHost(strings[0], Integer.parseInt(strings[1]), "http");
httpHosts[i] = httpHost;
}
return httpHosts;
}
}
三,springboot api封装
@Component
public class EsUtil {
@Resource
private RestHighLevelClient restHighLevelClient;
/**
* 创建索引
*/
@SneakyThrows
public Boolean createIndex(String indexName) {
CreateIndexRequest request = new CreateIndexRequest(indexName);
// request.settings() 可以设置分片规则
// request.mapping() 可以设置映射字段
CreateIndexResponse indexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
return indexResponse.isAcknowledged();
}
/**
* 查询索引 * 查询全部
*/
@SneakyThrows
public List<String> searchIndex(String indexName) {
GetIndexRequest request = new GetIndexRequest(indexName);
boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
if (!exists) {
return Lists.newArrayList();
}
GetIndexResponse getIndexResponse = restHighLevelClient.indices().get(request, RequestOptions.DEFAULT);
return Lists.newArrayList(getIndexResponse.getIndices());
}
/**
* 删除索引
*/
@SneakyThrows
public Boolean deleteIndex(String indexName) {
GetIndexRequest getIndexRequest = new GetIndexRequest(indexName);
boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
if (!exists) {
return false;
}
DeleteIndexRequest request = new DeleteIndexRequest(indexName);
AcknowledgedResponse response = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
return response.isAcknowledged();
}
/**
* 文档数据插入(插入前会