贺兰县住房城乡建设局网站,南通优化网站价格,WordPress如何快速排名,企业服务账号怎么查询文章目录 1、整合2、简单示例3、一点补充4、增删改查索引与文档 1、整合
整合思路都一样#xff0c;先起步依赖或普通依赖#xff0c;再配置#xff0c;再封装的操作对象。先引入依赖#xff1a;
dependency groupIdorg.springframework.boot/grou… 文章目录 1、整合2、简单示例3、一点补充4、增删改查索引与文档 1、整合
整合思路都一样先起步依赖或普通依赖再配置再封装的操作对象。先引入依赖
dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-data-elasticsearch/artifactId
/dependencyapplication.yaml配置
spring: elasticsearch: rest: uris: http://localhost:9200在需要的地方注入客户端操作对象
Autowired
ElasticsearchRestTemplate template;注意与以往不同的是SpringBoot平台并没有跟随ES的更新速度进行同步更新ES提供了High Level Client操作ES导入坐标
dependency groupIdorg.elasticsearch.client/groupId artifactIdelasticsearch-rest-high-level-client/artifactId
/dependency不用加配置上面的starter搭配的那个配置也可以注释掉了使用es-high-level-clientES的信息写在代码中不写在配置文件中因为没和SpringBoot整合还。
2、简单示例
既然es-high-level-client还没和Spring做整合那自然不能使用Autowired自动注入一个客户端操作对象了。RestHighLevelClient对象需要我们自己来手动创建并初始化。且之前对象做为Bean交给Spring管理时我们只管用现在手搓的RestHighLevelClient用完需要关闭资源连接。在UT中看下效果以创建索引为例
Test
void test() throws IOException {HttpHost host HttpHost.create(http://localhost:9200); RestClientBuilder builder RestClient.builder(host); RestHighLevelClient client new RestHighLevelClient(builder); //客户端操作 CreateIndexRequest request new CreateIndexRequest(books); //获取操作索引的客户端对象调用创建索引操作 client.indices().create(request, RequestOptions.DEFAULT); //关闭客户端 client.close();
}
创建客户端连接对象和关闭连接是重复操作使用SetUp和TearDown方法来改进下 SetUp和TearDown分别代表每个测试用例Test执行前和执行后进行的操作。 SpringBootTest
class Springboot18EsApplicationTests {private RestHighLevelClient client; BeforeEach void setUp() { this.client new RestHighLevelClient(RestClient.builder(HttpHost.create(http://localhost:9200))); } AfterEach void tearDown() throws IOException { this.client.close(); }}
此时直接写CRUD代码就行。
Test
void test() throws IOException { //客户端操作 CreateIndexRequest request new CreateIndexRequest(books); //获取操作索引的客户端对象调用创建索引操作 client.indices().create(request, RequestOptions.DEFAULT);
}
3、一点补充
高版本的SpringBoot好像已经完成了整合可以直接注入RestHighLevelClient这个对象测试版本SpringBoot 2.6.13
Autowired
private RestHighLevelClient restHighLevelClient;在Ioc容器中获取一下是可以拿到这个Bean的且其加载了application.yaml中的es配置
spring: elasticsearch: rest: uris: http://localhost:9200 # 默认就是这个uri写不写都行不确定没查文档实际开发时自己看吧注入不成功就Bean自己创建一个。
4、增删改查索引与文档
之前专栏已经整理完了跳转【ES专栏】