简介
本文主要介绍如何通过spring-data-elasticsearch访问es,使用最新版本的3.2.0.RELEASE
&restClient
完整代码github地址
创建模块
在项目search-engine-demo
中创建新模块
选择spring Initializer
,然后点击Next
,如下图所示
修改Artifact为spring-es
,Desc为springboot 集成es
,Package为app
,然后点击Next
,如下图所示
按照下图所示勾选依赖
勾选玩上面的依赖后点击Next
,然后点击Finish
,如下图
依赖版本
groupId | artifactId | version |
---|---|---|
org.springframework.boot | spring-boot-starters | 2.2.0.RELEASE |
org.springframework.boot | spring-boot-starter-web | 2.2.0.RELEASE |
org.springframework.boot | spring-boot-starter-data-elasticsearch | 2.2.0.RELEASE |
org.springframework.data | spring-data-elasticsearch | 3.2.0.RELEASE |
org.elasticsearch.client | elasticsearch-rest-high-level-client | 6.8.3 |
配置
将application.properties
改名为application.yml
,使用yml格式进行配置,可以根据自己的爱好选择
spring:
elasticsearch:
rest:
# es连接地址
uris: http://192.168.1.14:9200
# 用户名
username: search
# 密码
password: 123456
测试
创建测试包app.rest
,创建测试类ElasticsearchRestTemplateTest
,内容如下
package app.rest;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
/**
* @author faith.huan 2019-10-20 11:13
*/
@SpringBootTest
@Slf4j
class ElasticsearchRestTemplateTest {
@Autowired
private ElasticsearchRestTemplate restTemplate;
@Test
void get() {
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withIndices("es_doc")
.withTypes("_doc")
.withQuery(new MatchAllQueryBuilder())
.build();
long count = restTemplate.count(searchQuery);
log.info("索引es_doc中有{}个文档", count);
}
}
测试用例执行截图
从日志中能看到查询出了索引es_doc
中有336个文档,至此spring与es集成完成