官方文档

springboot整合es的几种方式

  1. RestHighLevelClient 高级客户端
  2. ES JPA 不考虑

创建module
3. 创建ES搜索引擎模块

修改pom

  1. 添加spring-boot-data-es依赖
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

修改配置文件

  1. 手动注入es高级客户端bean,并配置es连接相关信息
@Bean
public RestHighLevelClient getRestHighLevelClient(){
	 HttpHost httpHost = new HttpHost("47.96.11.185", 9200, "http");
	 RestClientBuilder restClientBuilder = RestClient.builder(httpHost);
	 RestHighLevelClient restHighLevelClient = new
	RestHighLevelClient(restClientBuilder);
	 return restHighLevelClient;
}

主启动

业务类

  1. 完成ES的CURD操作,并保存模板到IDEA
@Slf4j
public class EsReviewTest {

	private RestHighLevelClient restHighLevelClient;

	private String indexName = "review_test";


	@Before
	public void before() {
		restHighLevelClient = new RestHighLevelClient(
				RestClient.builder(
						new HttpHost(
								"test.com",
								9200,
								"http"
						)
				)
		);
	}


	@Test
	public void 创建索引() {
		// PUT /${index_name}?master_timeout=30s&timeout=30s
		try {
			CreateIndexResponse createIndexResponse = restHighLevelClient
					.indices()
					.create(
							new CreateIndexRequest(
									indexName
							),
							RequestOptions.DEFAULT
					);
			if (!createIndexResponse.isAcknowledged()) {
				log.error("fail to create index , indexName = {}", indexName);
			} else {
				log.debug("success to create index , indexName = {}", indexName);
			}

		} catch (IOException e) {
			log.error("fail to create index , indexName = {}", indexName);
		}
	}

	@Test
	public void 删除索引() throws Exception {
		// DELETE /${index_name}
		AcknowledgedResponse acknowledgedResponse = restHighLevelClient
				.indices()
				.delete(
						new DeleteIndexRequest(
								indexName
						),
						RequestOptions.DEFAULT
				);
		if (!acknowledgedResponse.isAcknowledged()) {
			log.error("fail to del index , indexName = {}", indexName);
		} else {
			log.debug("success to del index , indexName = {}", indexName);
		}
	}

	@Test
	public void 添加文档() throws Exception {
		// POST /${index_name}/_doc/${id} {"key","value"}

		String id = "2";
		IndexRequest indexRequest = new IndexRequest();
		indexRequest
				.index(indexName)
				.id(id)
				.source(
						JSON.toJSONString(
								MapUtil.builder()
										.put("name", "maofeiyu")
										.put("age", 12)
										.build()
						)
						,
						XContentType.JSON
				)
		;
		IndexResponse indexResponse = restHighLevelClient
				.index(
						indexRequest,
						RequestOptions.DEFAULT
				);
		if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
			log.debug("success to add doc,doc_id is {}", id);
		}
		if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
			log.debug("success to update doc,doc_id is {}", id);
		}
		ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
		// 判断分片操作是否都成功
		if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
			log.warn("exist the error shard");
		}
		// 有存在失败的分片
		if (shardInfo.getFailed() > 0) {
			for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
				log.error("failure.reason() is {}", failure.reason());
			}
		}

	}

	@Test
	public void 批量添加文档() throws Exception {

	}

	@Test
	public void 修改文档() throws Exception {
		// 同上
		添加文档();
	}

	@Test
	public void 删除文档() throws Exception {
		String id = "1";
		DeleteResponse deleteResponse = restHighLevelClient
				.delete(
						new DeleteRequest(indexName)
								.id(id),
						RequestOptions.DEFAULT
				);
		if (deleteResponse.getResult() == DocWriteResponse.Result.DELETED) {
			log.debug("success to del the doc , doc_id is {}", id);
		} else {
			log.error("fail to del the doc , doc_id is {}", id);
		}

	}

	@Test
	public void 查询文档() throws Exception {
		/**
		 *  GET /${index_name}/_doc/_search
		 *
		 */
		String indexName = "";

		// 封装req请求体查询参数
		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
				.query(
						// 封装简易查询
						// QueryBuilders.termQuery(
						// 		"productName",
						// 		"java"
						// )
						QueryBuilders.matchQuery(
								"",
								""
						)
				)
				// 封装分页
				.from(0)
				.size(10)

				.highlighter(
						// 封装高亮查询
						new HighlightBuilder()
								// TODO: 这个啥意思
								.highlighterType("unified")

								// 设置需要高亮显示的字段
								.field(
										new HighlightBuilder.Field(
												""
										))
								// 高亮标签添加
								.preTags(
										"<label style='color:red'>"
								)
								.postTags(
										"</label>"
								)
				);


		// build get req body
		SearchRequest searchRequest = new SearchRequest(indexName)
				.source(
						searchSourceBuilder
				);

		// send search get req
		SearchResponse searchResponse = restHighLevelClient
				.search(
						searchRequest,
						RequestOptions.DEFAULT
				);




		// 带有复杂条件的结果集封装
		// java.util.List<com.bluedream.es.pojo.Product> products = java.util.Arrays.stream(searchResponse.getHits().getHits())
		// 		.map(hit -> {
		// 			com.bluedream.es.pojo.Product product = com.alibaba.fastjson.JSON.parseObject(hit.getSourceAsString(), com.bluedream.es.pojo.Product.class);
		// 			if (hit.getHighlightFields() != null) {
		// 				product
		// 						.setProductName(
		// 								java.util.Arrays.toString(
		// 										hit.getHighlightFields().get("productName").fragments()
		// 								)
		// 						);
		// 			}
		// 			return product;
		// 		}).collect(java.util.stream.Collectors.toList());
	}


	@After
	public void after() throws IOException {
		restHighLevelClient.close();
	}

}


Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐