描述: 使用的是 7.17.3版本,进行配置ES集群,以及常用的crud方法进行整合为工具类,方便调用
①导入JAR②配置ymlco.elastic.clients elasticsearch-java 7.17.3 jakarta.json jakarta.json-api 2.0.1 org.apache.httpcomponents httpclient 4.5.13
#elasticsearch地址配置,多个地址用逗号隔开 elasticsearch: hosts: 10.1.5.132:9200,10.1.5.133:9200,10.1.5.100:9200③编写config
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
@ConfigurationProperties(prefix = "elasticsearch")//配置配置信息的前缀
@Configuration
public class ElasticSearchClientConfig {
private String hosts;
private String username;
private String password;
@Bean
public ElasticsearchClient restClient() {
HttpHost[] httpHosts = toHttpHost();
//不需要密码的方式
RestClient restClient = RestClient.builder(httpHosts).build();
//需要密码的方式
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
RestClient restClient = RestClient.builder(httpHosts).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
})
.build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
return new ElasticsearchClient(transport);
}
private HttpHost[] toHttpHost() {
if (!StringUtils.hasLength(hosts)) {
throw new RuntimeException("elasticsearch.hosts不能为空!");
}
String[] hostArray = hosts.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;
}
public String getHosts() {
return hosts;
}
public void setHosts(String hosts) {
this.hosts = hosts;
}
}
④写一个工具类
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.elasticsearch.indices.DeleteIndexResponse;
import co.elastic.clients.elasticsearch.indices.GetIndexResponse;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import com.micro.core.enums.CoreConstant;
import com.micro.core.exceptions.ValidateException;
import com.micro.serv.product.model.vo.req.SalKnowledgeAnswerReqVO;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Component
public class ElasticSearchUtil {
@Resource
ElasticsearchClient elasticsearchClient;
public void create(String indexName) throws Exception {
//写法比RestHighLevelClient更加简洁
CreateIndexResponse indexResponse = elasticsearchClient.indices().create(c -> c.index(indexName));
if (!indexResponse.acknowledged()) {
throw new ValidateException(CoreConstant.TRANS_STATUS__FAILED, "ES增加索引" + indexName + "失败");
}
}
public void query(String indexName) throws IOException {
GetIndexResponse getIndexResponse = elasticsearchClient.indices().get(i -> i.index(indexName));
System.out.println(getIndexResponse.toString());
}
public void exists(String indexName) throws Exception {
BooleanResponse booleanResponse = elasticsearchClient.indices().exists(e -> e.index(indexName));
if (!booleanResponse.value()) {
throw new ValidateException(CoreConstant.TRANS_STATUS__FAILED, indexName + "索引不存在");
}
}
public void delete(String indexName) throws Exception {
DeleteIndexResponse deleteIndexResponse = elasticsearchClient.indices().delete(d -> d.index(indexName));
if (!deleteIndexResponse.acknowledged()) {
throw new ValidateException(CoreConstant.TRANS_STATUS__FAILED, "删除索引" + indexName + "失败");
}
}
public void exitsOrSave(String indexName) throws Exception {
BooleanResponse booleanResponse = elasticsearchClient.indices().exists(e -> e.index(indexName));
if (!booleanResponse.value()) {
create(indexName);
}
}
public void exitsOrDelete(String indexName) throws Exception {
BooleanResponse booleanResponse = elasticsearchClient.indices().exists(e -> e.index(indexName));
if (booleanResponse.value()) {
delete(indexName);
}
}
public void addDocument(SalKnowledgeAnswerReqVO reqVo) throws Exception {
//判断索引是否存在
String indexName = reqVo.getIndexName();
exitsOrSave(indexName);
IndexResponse indexResponse = elasticsearchClient.index(i -> i
.index(indexName)
//设置id
.id(reqVo.getKnowledgeId().toString())
//传入user对象
.document(reqVo));
}
public void updateDocument(SalKnowledgeAnswerReqVO reqVo) throws Exception {
UpdateResponse updateResponse = elasticsearchClient.update(u -> u
.index(reqVo.getIndexName())
.id(reqVo.getKnowledgeId().toString())
.doc(reqVo)
, SalKnowledgeAnswerReqVO.class);
}
public SalKnowledgeAnswerReqVO getDocument(SalKnowledgeAnswerReqVO reqVo) throws IOException {
GetResponse getResponse = elasticsearchClient.get(g -> g
.index(reqVo.getIndexName())
.id(reqVo.getKnowledgeId().toString())
, SalKnowledgeAnswerReqVO.class
);
return getResponse.source();
}
public void deleteDocument(String indexName,String id) throws IOException {
DeleteResponse deleteResponse = elasticsearchClient.delete(d -> d
.index(indexName)
.id(id)
);
System.out.println(deleteResponse.id());
}
public SalKnowledgeAnswerReqVO search(SalKnowledgeAnswerReqVO reqVo) throws IOException {
SearchResponse search = elasticsearchClient.search(s -> s
.index(reqVo.getIndexName())
//查询name字段包含hello的document(不使用分词器精确查找)
.query(q -> q
.term(t -> t
.field("name")
.value(v -> v.stringValue("hello"))
))
//分页查询,从第0页开始查询3个document
.from(0)
.size(3)
//按age降序排序
.sort(f->f.field(o->o.field("age").order(SortOrder.Desc))),SalKnowledgeAnswerReqVO.class
);
for (Hit hit : search.hits().hits()) {
System.out.println(hit.source());
}
return null;
}
}



