maven dependency import:
1. maven dependency import
1. Root Pom properites set the version number of elasticSearch (same as its own elasticSearch version) <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <elasticsearch.version>7.6.1</elasticsearch.version> </properties>2. The requirements module pom introduces dependencies
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>3. Import formatted json
<!-- alibbaFastJson is used for JSON.toJSONString() formatting entity class -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
ClentCreate
Create the Config class
package com.hisicom.resourcedirectory.config;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @ClassName : ElasticSearchClientConfig //类名
* @Description : //描述
* @Date: 2022-07-04 09:52 //时间
*/
@Configuration
public class ElasticSearchClientConfig {
@Value("${elasticsearch.port}") //appliction文件自定义端口号
private String httpHost;
@Bean
public RestHighLevelClient restHighLevelClient() {
System.err.println("elasticSearch port:"+httpHost);
return new RestHighLevelClient(
RestClient.builder(
new HttpHost(httpHost, 9200, "http"),
new HttpHost(httpHost, 9201, "http")
));
// RestClient.builder(
// new HttpHost("127.0.0.1", 9200, "http"),
// new HttpHost("127.0.0.1", 9201, "http")
// ));
}
}
service processing
The comments are perfect, you can see the comments
private static RestHighLevelClient restHighLevelClient;//注入client
ElasticUtils(@Autowired RestHighLevelClient restHighLevelClient) {
ElasticUtils.restHighLevelClient = restHighLevelClient;
}
/**
* 根据索引名称 查询索引是否存在
*
* @param indexName 索引名称
* @return true 存在;false 不存在
*/
public static boolean existElasticSearchIndex(String indexName) {
if ("".equals(indexName) || indexName == null) {
return false;
}
GetIndexRequest getIndexRequest = new GetIndexRequest(indexName);
try {
return restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static CreateIndexResponse createdIndexRequest(String indexName) {
//先查询一下 es服务中是否已存在索引
boolean existElasticSearchIndex = existElasticSearchIndex(indexName);
CreateIndexResponse createIndexResponse = null;
if (existElasticSearchIndex) {//如果存在 返回null
return null;
}
CreateIndexRequest index = new CreateIndexRequest(indexName);//不存在则创建该索引
//打开form - size分页最大条数限制 (推荐使用searchAfter 该方法可能会导致OOM或ES索引性能丢失) 最大值2147483647
index.settings(Settings.builder().put("max_result_window",2147483647));
//超时时间为10分钟
index.setTimeout(TimeValue.timeValueMillis(10));
try {
createIndexResponse = restHighLevelClient.indices().create(index, RequestOptions.DEFAULT);
System.out.println(createIndexResponse);
return createIndexResponse;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* es根据参数模糊搜索
* @param searchParamEntity 参数实体类
* @return resultEntity
* */
public static EsSearchResultEntity searchIndexByParam(SearchParamEntity searchParamEntity) {
EsSearchResultEntity searchResultEntity = new EsSearchResultEntity(); //创建自定义返回类
ArrayList<Map<String, Object>> resultData = new ArrayList<>(); //数据封装
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); //创建BoolQuery对象
//这里注意 must和Should 同时使用会只执行must的条件 should筛选会失效
if (searchParamEntity.getAreaCode()!=null && searchParamEntity.getAreaCodeFiled()!=null && !"".equals(searchParamEntity.getAreaCode()) && !"".equals(searchParamEntity.getAreaCodeFiled())) {
//拼接参数 (searchParamEntity.getAreaCodeFiled: 参数key : 参数value searchParamEntity.getAreaCode() 参数值 ) *相当于 oracle的 % like '%areaCode%'
WildcardQueryBuilder queryBuilder = QueryBuilders.wildcardQuery(searchParamEntity.getAreaCodeFiled() + ".keyword", "*" + searchParamEntity.getAreaCode() + "*");
boolQueryBuilder.must(queryBuilder);//must = oracle(and条件)
}
if (!"".equals(searchParamEntity.getSearchKeyWord()) && searchParamEntity.getSearchFiledCodeList() != null) {
for (String filedCode : searchParamEntity.getSearchFiledCodeList()) {//根上面同理一样
WildcardQueryBuilder queryBuilder = QueryBuilders.wildcardQuery(filedCode + ".keyword", "*" + searchParamEntity.getSearchKeyWord() + "*");
//MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery(filedCode, searchParamEntity.getSearchKeyWord());
boolQueryBuilder.should(queryBuilder);//should = oracle(or条件)
}
}
//trackTotalHits 获取w条数据 超过1需要加上 "track_total_hits":true ,不然只能显示出9999条
//数据分页
Integer pageNum = searchParamEntity.getPageNum();
Integer pageSize = searchParamEntity.getPageSize();
int form = (pageNum - 1) * pageSize;
SearchRequest searchRequest = new SearchRequest(searchParamEntity.getSearchIndexName())
.source(new SearchSourceBuilder().query(boolQueryBuilder).trackTotalHits(true)
.from(form)
.size(pageSize)
.sort("_score", SortOrder.DESC)//取值与排序
);
try {
SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
for (SearchHit documentFields : search.getHits().getHits()) {//数据处理 放入resultData (ArrayList<HashMap> 对象)
resultData.add(documentFields.getSourceAsMap());
}
searchResultEntity.setDatas(resultData); //将数据封装到自定义Entity
searchResultEntity.setTotal(search.getHits().getTotalHits().value);//将查到的总条数封装到自定义Entity 获取w条数据 超过1需要加上 "track_total_hits":true ,不然只能显示出9999条
System.out.println("result=" + resultData);
} catch (IOException e) {
e.printStackTrace();
System.err.println("请求异常 请确认参数是否正确 或 elasticSearch服务是否正常开启");
}
return searchResultEntity; //返回数据
}
/**
* 批量向es插入数据
* @param data 数据对象
* @param indexName 要插入的索引名称
* @return
*/
public static boolean addDocElasticSearchByList(List<HashMap<Object, Object>> data, String indexName) {
BulkRequest bulkRequest = new BulkRequest().timeout(TimeValue.timeValueMinutes(2));//创建Bulk请求对象 设置2分钟超市时间
for (int i = 0; i < data.size(); i++) {//循环data 并添加到request当中
bulkRequest.add(
new IndexRequest(indexName).source(JSON.toJSONString(data.get(i)), XContentType.JSON)//默认随机UUid 也可自定义id(.id())
);
}
try {
BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);//请求并向索引添加数据
System.out.println("status=" + bulkResponse.status());
System.out.println("hasFailures=" + bulkResponse.hasFailures());
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public static boolean deleteElasticSearchIndexByIndexName(String indexName) {
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexName);
AcknowledgedResponse delete = null;//delete 删除索引
try {
delete = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
System.out.println("索引不存在");
return false;
}
System.out.println(delete.isAcknowledged());//是否删除成功 返回true
return delete.isAcknowledged();
}
//调用方法
public static void resourceDataInit(String indexName, List<HashMap<Object, Object>> datas) {
System.err.println("---------- 正在同步ElasticSearch数据 -----------------");
if (existElasticSearchIndex(indexName)) {
ElasticUtils.deleteElasticSearchIndexByIndexName(indexName);
}
if (datas != null && createdIndexRequest(indexName) != null) {
addDocElasticSearchByList(datas, indexName);
}
System.err.println("---------- 同步已结束 -----------------");
}