新建项目
新建一个springboot项目springboot_es
用于本次与ElasticSearch的整合,如下图
引入依赖
修改我们的pom.xml
,加入spring-boot-starter-data-elasticsearch
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>
编写配置文件
由于ElasticSearch从7.x版本开始淡化TransportClient甚至于在8.x版本中遗弃,所以spring data elasticsearch推荐我们使用rest客户端RestHingLevelClient
(端口号使用9200)以及接口ElasticSearchRespositoy
。
- RestHighLevelClient 更强大,更灵活,但是不能友好的操作对象
- ElasticSearchRepository 对象操作友好
首先我们编写配置文件如下
/** * ElasticSearch Rest Client config * @author Christy * @date 2021/4/29 19:40 **/ @Configuration public class ElasticSearchRestClientConfig extends AbstractElasticsearchConfiguration{ @Override @Bean public RestHighLevelClient elasticsearchClient() { final ClientConfiguration clientConfiguration = ClientConfiguration.builder() .connectedTo("192.168.8.101:9200") .build(); return RestClients.create(clientConfiguration).rest(); } }
springboot操作ES
RestHighLevelClient方式
有了上面的rest client,我们就可以在其他的地方注入该客户端对ElasticSearch进行操作。我们新建一个测试文件,使用客户端对ElasticSearch进行基本的操作
1.注入R
本文来源gao!%daima.com搞$代*!码9网(
estClient
/** * ElasticSearch Rest client操作 * * RestHighLevelClient 更强大,更灵活,但是不能友好的操作对象 * ElasticSearchRepository 对象操作友好 * * 我们使用rest client 主要测试文档的操作 * @Author Christy * @Date 2021/4/29 19:51 **/ @SpringBootTest public class TestRestClient { // 复杂查询使用:比如高亮查询 @Autowired private RestHighLevelClient restHighLevelClient; }
2.插入一条文档
/** * 新增一条文档 * @author Christy * @date 2021/4/29 20:17 */ @Test public void testAdd() throws IOException { /** * 向ES中的索引christy下的type类型中添加一天文档 */ IndexRequest indexRequest = new IndexRequest("christy","user","11"); indexRequest.source("{\"name\":\"齐天大圣孙悟空\",\"age\":685,\"bir\":\"1685-01-01\",\"introduce\":\"花果山水帘洞美猴王齐天大圣孙悟空是也!\"," + "\"address\":\"花果山\"}", XContentType.JSON); IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT); System.out.println(indexResponse.status()); }
我们可以看到文档插入成功,我们去kibana中查询该条文档
完全没有问题的。
3.删除一条文档
/** * 删除一条文档 * @author Christy * @date 2021/4/29 20:18 */ @Test public void deleteDoc() throws IOException { // 我们把特朗普删除了 DeleteRequest deleteRequest = new DeleteRequest("christy","user","rYBNG3kBRz-Sn-2f3ViU"); DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT); System.out.println(deleteResponse.status()); } }