当前位置:   article > 正文

springboot整合RestHighLevelClient_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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

配置

  • yml
spring:
  es:
    urls:
      - "192.168.2.18:9200"
  • 1
  • 2
  • 3
  • 4
  • 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;
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91

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());
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298

参考文章

https://www.cnblogs.com/tanghaorong/p/16344391.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/199749
推荐阅读
相关标签
  

闽ICP备14008679号