Springboot整合ES

官方文档

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();
	}

}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,下面是SpringBoot整合Elasticsearch的步骤: 1. 添加Elasticsearch的依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> ``` 2. 配置Elasticsearch连接 在application.yml或application.properties中添加以下配置: ``` spring: data: elasticsearch: cluster-name: elasticsearch # Elasticsearch集群名称 cluster-nodes: 127.0.0.1:9300 # Elasticsearch连接地址 ``` 3. 创建Elasticsearch实体类 创建一个Java类,使用@Document注解标记为Elasticsearch文档类型,并使用其他注解指定属性的映射关系,如下所示: ``` @Document(indexName = "my_index", type = "my_type") public class MyDocument { @Id private String id; private String title; private String content; // ... 省略getter和setter方法 } ``` 4. 创建Elasticsearch操作接口 创建一个接口,继承ElasticsearchRepository接口,并指定泛型为步骤3中创建的实体类,如下所示: ``` public interface MyDocumentRepository extends ElasticsearchRepository<MyDocument, String> { } ``` 5. 使用Elasticsearch操作数据 在需要使用Elasticsearch的地方注入MyDocumentRepository,即可使用其提供的方法进行数据的CRUD操作,如下所示: ``` @Autowired private MyDocumentRepository repository; public void save(MyDocument document) { repository.save(document); } public MyDocument findById(String id) { return repository.findById(id).orElse(null); } public void deleteById(String id) { repository.deleteById(id); } ``` 以上就是SpringBoot整合Elasticsearch的基本步骤,希望对你有帮助。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值