引入依賴
<!-- es 高亮 -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.9.1</version>
</dependency>
<!-- es client -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.9.1</version>
</dependency>
<!-- es -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.9.1</version>
</dependency>
配置
- yml
spring:
es:
urls:
- "192.168.2.18:9200"
- config
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.util.Arrays;
/**
* 功能描述: EsConfig
*
* @author : yzd e-mail: 121665820@qq.com
* @return :
* @create : 2023/1/17 16:27
*/
@Slf4j
@Data
@Component
@Configuration
@ConfigurationProperties(prefix = "spring.es")
public class EsConfig {
public static final RequestOptions COMMON_OPTIONS;
public static final String DOCTOR_INDEX = "doctor_index";
public static final String HOSPITAL_INDEX = "hospital_index";
public static final String DISEASE_INDEX = "disease_index";
private String[] urls;
// 通用設(shè)置項(xiàng)
static {
RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
COMMON_OPTIONS = builder.build();
}
/**
* 初始化es 索引
* 創(chuàng)建索引庫(kù)和映射表結(jié)構(gòu)
* 注意:索引一般不會(huì)怎么創(chuàng)建
*/
@Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient restHighLevelClient = null;
try {
restHighLevelClient = new RestHighLevelClient(
RestClient.builder(Arrays.stream(urls).map(HttpHost::create).toArray(HttpHost[]::new)));
} catch (Exception e) {
log.error("初始化es連接失?。簕}", e.getMessage());
}
try {
if (restHighLevelClient != null) {
IndicesClient indicesClient = restHighLevelClient.indices();
// 創(chuàng)建get請(qǐng)求
GetIndexRequest doctorIndexGet = new GetIndexRequest(DOCTOR_INDEX);
// 判斷索引庫(kù)是否存在,不存在則創(chuàng)建
if (!indicesClient.exists(doctorIndexGet, RequestOptions.DEFAULT)) {
CreateIndexRequest doctorIndex = new CreateIndexRequest(DOCTOR_INDEX);
indicesClient.create(doctorIndex, RequestOptions.DEFAULT);
}
// 創(chuàng)建get請(qǐng)求
GetIndexRequest hospitalIndexGet = new GetIndexRequest(HOSPITAL_INDEX);
// 判斷索引庫(kù)是否存在,不存在則創(chuàng)建
if (!indicesClient.exists(hospitalIndexGet, RequestOptions.DEFAULT)) {
CreateIndexRequest hospitalIndex = new CreateIndexRequest(HOSPITAL_INDEX);
indicesClient.create(hospitalIndex, RequestOptions.DEFAULT);
}
// 創(chuàng)建get請(qǐng)求
GetIndexRequest diseaseIndexGet = new GetIndexRequest(HOSPITAL_INDEX);
// 判斷索引庫(kù)是否存在,不存在則創(chuàng)建
if (!indicesClient.exists(diseaseIndexGet, RequestOptions.DEFAULT)) {
CreateIndexRequest diseaseIndex = new CreateIndexRequest(DISEASE_INDEX);
indicesClient.create(diseaseIndex, RequestOptions.DEFAULT);
}
}
} catch (Exception e) {
log.warn("初始化es索引失敗:{}", e.getMessage());
}
return restHighLevelClient;
}
}
es util 封裝
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.springblade.core.mp.base.BaseEntity;
import org.springblade.core.tool.utils.Func;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
/**
* @Title: EsUtil
* @author: yzd e-mail: 121665820@qq.com
* @date: 2023/2/1 9:39
* @ClassName: EsUtil
* @Description: es 文檔操作
*/
@Service
@Slf4j
public class EsUtil {
@Autowired
private ThreadPoolTaskExecutor asyncServiceExecutor;
@Autowired
private RestHighLevelClient restHighLevelClient;
/**
* 功能描述: 創(chuàng)建文檔
*
* @param baseEntity 實(shí)體
* @param indexName 索引
* @return : void
* @author : yzd e-mail: 121665820@qq.com
* @create : 2023/2/1 10:16
*/
public void addDocument(BaseEntity baseEntity, String indexName) {
asyncServiceExecutor.execute(() -> {
String id = baseEntity.getId() + "";
if (this.exists(indexName, id)) {
this.updateDocument(baseEntity, indexName);
} else {
// 將對(duì)象轉(zhuǎn)為json
String data = JSON.toJSONString(baseEntity);
// 創(chuàng)建索引請(qǐng)求對(duì)象
IndexRequest indexRequest = new IndexRequest(indexName).id(id).source(data, XContentType.JSON);
// 執(zhí)行增加文檔
IndexResponse response = null;
try {
response = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
} catch (Exception e) {
log.error("執(zhí)行增加文檔error:", e);
}
log.info("創(chuàng)建文檔狀態(tài):{}", Objects.requireNonNull(response).status());
}
});
}
/**
* 功能描述: 獲取文檔信息
*
* @param id id
* @param indexName 索引
* @return : void
* @author : yzd e-mail: 121665820@qq.com
* @create : 2023/2/1 10:16
*/
public void getDocument(String id, String indexName) {
// 創(chuàng)建獲取請(qǐng)求對(duì)象
GetRequest getRequest = new GetRequest(indexName, id);
GetResponse response = null;
try {
response = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
} catch (Exception e) {
log.error("獲取文檔信息error:", e);
}
log.info("獲取文檔狀態(tài):{}", Objects.requireNonNull(response).getSourceAsString());
}
/**
* 功能描述: 更新文檔信息
*
* @param baseEntity 實(shí)體
* @param indexName 索引
* @return : void
* @author : yzd e-mail: 121665820@qq.com
* @create : 2023/2/1 10:16
*/
public void updateDocument(BaseEntity baseEntity, String indexName) {
asyncServiceExecutor.execute(() -> {
String id = baseEntity.getId() + "";
if (this.exists(indexName, id)) {
// 將對(duì)象轉(zhuǎn)為json
String data = JSON.toJSONString(baseEntity);
// 創(chuàng)建索引請(qǐng)求對(duì)象
UpdateRequest updateRequest = new UpdateRequest(indexName, id);
// 設(shè)置更新文檔內(nèi)容
updateRequest.doc(data, XContentType.JSON);
// 執(zhí)行更新文檔
UpdateResponse response = null;
try {
response = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
log.error("更新文檔信息error:", e);
}
log.info("更新文檔信息狀態(tài):{}", Objects.requireNonNull(response).status());
} else {
this.addDocument(baseEntity, indexName);
}
});
}
/**
* 功能描述: 刪除文檔信息
*
* @param idList idList
* @param indexName 索引
* @return : void
* @author : yzd e-mail: 121665820@qq.com
* @create : 2023/2/1 10:16
*/
public void deleteDocument(List<Long> idList, String indexName) {
asyncServiceExecutor.execute(() -> {
if (Func.isEmpty(idList)) {
return;
}
for (Long id : idList) {
// 創(chuàng)建刪除請(qǐng)求對(duì)象
DeleteRequest deleteRequest = new DeleteRequest(indexName, id.toString());
// 執(zhí)行刪除文檔
DeleteResponse response = null;
try {
response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
} catch (Exception e) {
log.error("刪除文檔信息error:", e);
}
log.info("刪除狀態(tài):{}", Objects.requireNonNull(response).status());
}
});
}
/**
* 判斷文檔是否存在
*
* @param indexName 索引名稱
* @param id 文檔id
* @return bool
*/
public boolean exists(String indexName, String id) {
GetRequest request = new GetRequest(indexName, id);
request.fetchSourceContext(new FetchSourceContext(false));
request.storedFields("_none_");
boolean exists = false;
try {
exists = restHighLevelClient.exists(request, RequestOptions.DEFAULT);
} catch (Exception e) {
log.error("判斷文檔是否存在error:", e);
}
return exists;
}
/**
* 醫(yī)生名稱
*/
private static final String DOCTOR_NAME = "name";
/**
* 醫(yī)院名稱
*/
private static final String HOSPITAL_NAME = "hospitalName";
/**
* 功能描述: 關(guān)鍵字搜索
*
* @param keywords 搜索關(guān)鍵字
* @param size 搜索結(jié)果數(shù)量
* @return : void
* @author : yzd e-mail: 121665820@qq.com
* @create : 2023/2/3 14:55
*/
public List<Object> search(String keywords, Integer size) {
try {
// 構(gòu)建查詢條件
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 模糊查詢
searchSourceBuilder.query(QueryBuilders.fuzzyQuery(DOCTOR_NAME, keywords).fuzziness(Fuzziness.AUTO));
searchSourceBuilder.query(QueryBuilders.fuzzyQuery(HOSPITAL_NAME, keywords).fuzziness(Fuzziness.AUTO));
// 多個(gè)字段查詢
searchSourceBuilder.query(QueryBuilders.multiMatchQuery(keywords, DOCTOR_NAME, HOSPITAL_NAME));
// 最大10條
searchSourceBuilder.size(size);
// 高亮 查詢 設(shè)置高亮三要素 field: 你的高亮字段 // preTags :前綴 // postTags:后綴
HighlightBuilder highlightBuilder = new HighlightBuilder().field(DOCTOR_NAME).field(HOSPITAL_NAME).preTags("<font color='red'>").postTags("</font>");
searchSourceBuilder.highlighter(highlightBuilder);
// 創(chuàng)建查詢請(qǐng)求對(duì)象,將查詢對(duì)象配置到其中
SearchRequest searchRequest = new SearchRequest(EsConfig.DOCTOR_INDEX, EsConfig.HOSPITAL_INDEX);
searchRequest.source(searchSourceBuilder);
// 執(zhí)行查詢,然后處理響應(yīng)結(jié)果
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
// 根據(jù)狀態(tài)和數(shù)據(jù)條數(shù)驗(yàn)證是否返回了數(shù)據(jù)
if (RestStatus.OK.equals(searchResponse.status()) && searchResponse.getHits().getTotalHits().value > 0) {
SearchHits hits = searchResponse.getHits();
ArrayList<Object> list = new ArrayList<>(hits.getHits().length);
for (SearchHit hit : hits) {
// 查詢實(shí)體轉(zhuǎn)為map
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
// 獲取高亮的數(shù)據(jù)
replaceHighlightField(sourceAsMap, hit.getHighlightFields(), DOCTOR_NAME);
replaceHighlightField(sourceAsMap, hit.getHighlightFields(), HOSPITAL_NAME);
// 設(shè)置實(shí)體索引類型
String indexName = hit.getIndex();
sourceAsMap.put("index", indexName);
list.add(sourceAsMap);
}
return list;
}
} catch (Exception e) {
log.error("關(guān)鍵字搜索失?。?, e);
}
return Collections.emptyList();
}
/**
* 功能描述: 獲取高亮的數(shù)據(jù) 并 插入 map
*
* @param sourceAsMap sourceAsMap 查詢結(jié)果
* @param highlightFields highlightFields 高亮 鍵值對(duì)
* @param highlightFieldStr highlightFieldStr 需高亮詞匯
* @return : void
* @author : yzd e-mail: 121665820@qq.com
* @create : 2023/2/3 16:50
*/
private void replaceHighlightField(Map<String, Object> sourceAsMap, Map<String, HighlightField> highlightFields, String highlightFieldStr) {
// 獲取高亮的數(shù)據(jù)
if (Func.isNotEmpty(highlightFields)) {
if (highlightFields.containsKey(highlightFieldStr)) {
HighlightField highlightField = highlightFields.get(highlightFieldStr);
Text[] fragments = highlightField.getFragments();
if (Func.isNotEmpty(fragments)) {
StringBuilder title = new StringBuilder();
for (Text fragment : fragments) {
title.append(fragment);
}
sourceAsMap.put("highlight", title);
}
}
}
}
/**
* 批量 導(dǎo)入 數(shù)據(jù)
*/
public void batchAddDocument(List<BaseEntity> baseEntityList, String indexName) {
//1. 所有數(shù)據(jù) baseEntityList
//2.bulk導(dǎo)入
BulkRequest bulkRequest = new BulkRequest();
//2.1 循環(huán) List,創(chuàng)建IndexRequest添加數(shù)據(jù)
for (BaseEntity baseEntity : baseEntityList) {
// 將對(duì)象轉(zhuǎn)為json
String data = JSON.toJSONString(baseEntity);
String id = baseEntity.getId() + "";
IndexRequest indexRequest = new IndexRequest(indexName);
indexRequest.id(id).source(data, XContentType.JSON);
bulkRequest.add(indexRequest);
}
// 執(zhí)行增加文檔
BulkResponse response = null;
try {
response = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
} catch (Exception e) {
log.error("批量執(zhí)行增加文檔error:", e);
}
log.info("批量執(zhí)行增加文檔:{}", Objects.requireNonNull(response).status());
}
}
參考文章
https://www.cnblogs.com/tanghaorong/p/16344391.html文章來源地址http://www.zghlxwxcb.cn/news/detail-743375.html
文章來源:http://www.zghlxwxcb.cn/news/detail-743375.html
到了這里,關(guān)于springboot整合RestHighLevelClient的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!