springboot整合RestHighLevelClient

这篇具有很好参考价值的文章主要介绍了springboot整合RestHighLevelClient。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

引入依赖

        <!-- 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;

	// 通用设置项
	static {
		RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
		COMMON_OPTIONS = builder.build();
	}

	/**
	 * 初始化es 索引
	 * 创建索引库和映射表结构
	 * 注意:索引一般不会怎么创建
	 */
	@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();
				// 创建get请求
				GetIndexRequest doctorIndexGet = new GetIndexRequest(DOCTOR_INDEX);
				// 判断索引库是否存在,不存在则创建
				if (!indicesClient.exists(doctorIndexGet, RequestOptions.DEFAULT)) {
					CreateIndexRequest doctorIndex = new CreateIndexRequest(DOCTOR_INDEX);
					indicesClient.create(doctorIndex, RequestOptions.DEFAULT);
				}
				// 创建get请求
				GetIndexRequest hospitalIndexGet = new GetIndexRequest(HOSPITAL_INDEX);
				// 判断索引库是否存在,不存在则创建
				if (!indicesClient.exists(hospitalIndexGet, RequestOptions.DEFAULT)) {
					CreateIndexRequest hospitalIndex = new CreateIndexRequest(HOSPITAL_INDEX);
					indicesClient.create(hospitalIndex, RequestOptions.DEFAULT);
				}
				// 创建get请求
				GetIndexRequest diseaseIndexGet = new GetIndexRequest(HOSPITAL_INDEX);
				// 判断索引库是否存在,不存在则创建
				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;

	/**
	 * 功能描述: 创建文档
	 *
	 * @param baseEntity 实体
	 * @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 {
				// 将对象转为json
				String data = JSON.toJSONString(baseEntity);
				// 创建索引请求对象
				IndexRequest indexRequest = new IndexRequest(indexName).id(id).source(data, XContentType.JSON);
				// 执行增加文档
				IndexResponse response = null;
				try {
					response = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
				} catch (Exception e) {
					log.error("执行增加文档error:", e);
				}
				log.info("创建文档状态:{}", 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) {
		// 创建获取请求对象
		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("获取文档状态:{}", Objects.requireNonNull(response).getSourceAsString());
	}


	/**
	 * 功能描述: 更新文档信息
	 *
	 * @param baseEntity 实体
	 * @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)) {
				// 将对象转为json
				String data = JSON.toJSONString(baseEntity);
				// 创建索引请求对象
				UpdateRequest updateRequest = new UpdateRequest(indexName, id);
				// 设置更新文档内容
				updateRequest.doc(data, XContentType.JSON);
				// 执行更新文档
				UpdateResponse response = null;
				try {
					response = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
				} catch (IOException e) {
					log.error("更新文档信息error:", e);
				}
				log.info("更新文档信息状态:{}", 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) {
				// 创建删除请求对象
				DeleteRequest deleteRequest = new DeleteRequest(indexName, id.toString());
				// 执行删除文档
				DeleteResponse response = null;
				try {
					response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
				} catch (Exception e) {
					log.error("删除文档信息error:", e);
				}
				log.info("删除状态:{}", 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;
	}


	/**
	 * 医生名称
	 */
	private static final String DOCTOR_NAME = "name";
	/**
	 * 医院名称
	 */
	private static final String HOSPITAL_NAME = "hospitalName";

	 /**
	 * 功能描述:  关键字搜索
	 *
	 * @param keywords 搜索关键字
	 * @param size     搜索结果数量
	 * @return : void
	 * @author : yzd e-mail: 121665820@qq.com
	 * @create : 2023/2/3 14:55
	 */
	public List<Object> search(String keywords, Integer size) {
		try {
			// 构建查询条件
			SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
			// 模糊查询
			searchSourceBuilder.query(QueryBuilders.fuzzyQuery(DOCTOR_NAME, keywords).fuzziness(Fuzziness.AUTO));
			searchSourceBuilder.query(QueryBuilders.fuzzyQuery(HOSPITAL_NAME, keywords).fuzziness(Fuzziness.AUTO));
			// 多个字段查询
			searchSourceBuilder.query(QueryBuilders.multiMatchQuery(keywords, DOCTOR_NAME, HOSPITAL_NAME));
			// 最大10条
			searchSourceBuilder.size(size);
			//  高亮 查询 设置高亮三要素   field: 你的高亮字段    // preTags :前缀    // postTags:后缀
			HighlightBuilder highlightBuilder = new HighlightBuilder().field(DOCTOR_NAME).field(HOSPITAL_NAME).preTags("<font color='red'>").postTags("</font>");
			searchSourceBuilder.highlighter(highlightBuilder);
			// 创建查询请求对象,将查询对象配置到其中
			SearchRequest searchRequest = new SearchRequest(EsConfig.DOCTOR_INDEX, EsConfig.HOSPITAL_INDEX);
			searchRequest.source(searchSourceBuilder);
			// 执行查询,然后处理响应结果
			SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
			// 根据状态和数据条数验证是否返回了数据
			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) {
					// 查询实体转为map
					Map<String, Object> sourceAsMap = hit.getSourceAsMap();
					// 获取高亮的数据
					replaceHighlightField(sourceAsMap, hit.getHighlightFields(), DOCTOR_NAME);
					replaceHighlightField(sourceAsMap, hit.getHighlightFields(), HOSPITAL_NAME);
					// 设置实体索引类型
					String indexName = hit.getIndex();
					sourceAsMap.put("index", indexName);
					list.add(sourceAsMap);
				}
				return list;
			}
		} catch (Exception e) {
			log.error("关键字搜索失败:", e);
		}
		return Collections.emptyList();
	}

	/**
	 * 功能描述: 获取高亮的数据 并 插入 map
	 *
	 * @param sourceAsMap sourceAsMap 查询结果
	 * @param highlightFields highlightFields 高亮 键值对
	 * @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) {
		// 获取高亮的数据
		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);
				}
			}
		}

	}



	/**
	 * 批量 导入  数据
	 */
	public void batchAddDocument(List<BaseEntity> baseEntityList, String indexName) {
		//1. 所有数据  baseEntityList
		
		//2.bulk导入
		BulkRequest bulkRequest = new BulkRequest();

		//2.1 循环 List,创建IndexRequest添加数据
		for (BaseEntity baseEntity : baseEntityList) {
			// 将对象转为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);
		}
		// 执行增加文档
		BulkResponse response = null;
		try {
			response = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
		} catch (Exception e) {
			log.error("批量执行增加文档error:", e);
		}
		log.info("批量执行增加文档:{}", Objects.requireNonNull(response).status());
	}
}

参考文章

https://www.cnblogs.com/tanghaorong/p/16344391.html文章来源地址https://www.toymoban.com/news/detail-743375.html

到了这里,关于springboot整合RestHighLevelClient的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包