0


通过Spring Data Elasticsearch操作ES

Elasticsearch

  1. Elasticsearch (ES)是一个基于Lucene构建的开源、分布式、RESTful 接口全文搜索引擎。Elasticsearch 还是一个分布式文档数据库,其中每个字段均是被索引的数据且可被搜索,它能够扩展至数以百计的服务器存储以及处理PB级的数据。它可以在很短的时间内在存储、搜索和分析大量的数据。它通常作为具有复杂搜索场景情况下的核心发动机。**es是由java语言编写的**。
  2. Elasticsearch就是为高可用和可扩展而生的。可以通过购置性能更强的服务器来完成。

官网

Elasticsearch:官方分布式搜索和分析引擎 | Elastichttps://www.elastic.co/cn/elasticsearch/

Spring Data

  1. Spring DataSpring 的一个子项目。用于简化数据库访问,支持NoSQL和关系数据库存储。其主要目标是使数据库的访问变得方便快捷。

官网

Spring DataLevel up your Java code and explore what Spring can do for you.https://spring.io/projects/spring-data

Spring Data ElasticSearch

  1. Spring Data ElasticSearch 基于 spring data API 简化 elasticSearch操作,将原始操作elasticSearch的客户端API进行封装。Spring DataElasticsearch项目提供集成搜索引擎。Spring Data Elasticsearch POJO的关键功能区域为中心的模型与Elastichsearch交互文档和轻松地编写一个存储库数据访问层。

官网

Spring Data Elasticsearchhttps://spring.io/projects/spring-data-elasticsearch

代码

  1. 创建maven项目,并引入依赖
  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.3.6.RELEASE</version>
  5. <relativePath/>
  6. </parent>
  7. <dependencies>
  8. <dependency>
  9. <groupId>org.projectlombok</groupId>
  10. <artifactId>lombok</artifactId>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-devtools</artifactId>
  19. <scope>runtime</scope>
  20. <optional>true</optional>
  21. </dependency>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-test</artifactId>
  25. <scope>test</scope>
  26. </dependency>
  27. <dependency>
  28. <groupId>org.springframework.boot</groupId>
  29. <artifactId>spring-boot-test</artifactId>
  30. </dependency>
  31. <dependency>
  32. <groupId>junit</groupId>
  33. <artifactId>junit</artifactId>
  34. </dependency>
  35. <dependency>
  36. <groupId>org.springframework</groupId>
  37. <artifactId>spring-test</artifactId>
  38. </dependency>
  39. </dependencies>

在resources文件夹下创建application.properties文件

application.properties内容如下

  1. # es 服务地址
  2. elasticsearch.host=部署es服务器的ip
  3. # es 服务端口
  4. elasticsearch.port=9200
  5. # 配置日志级别,开启 debug 日志
  6. logging.level.com.es=debug

创建MainApplication

  1. package com.es;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class MainApplication {
  6. public static void main(String[] args) {
  7. SpringApplication.run(MainApplication.class, args);
  8. }
  9. }

创建ElasticSearch配置文件ElasticsearchConfig

  1. package com.es.config;
  2. import lombok.Data;
  3. import org.apache.http.HttpHost;
  4. import org.elasticsearch.client.RestClient;
  5. import org.elasticsearch.client.RestClientBuilder;
  6. import org.elasticsearch.client.RestHighLevelClient;
  7. import org.springframework.boot.context.properties.ConfigurationProperties;
  8. import org.springframework.context.annotation.Configuration;
  9. import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
  10. @ConfigurationProperties(prefix = "elasticsearch")
  11. @Configuration
  12. @Data
  13. public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {
  14. private String host ;
  15. private Integer port ;
  16. @Override
  17. public RestHighLevelClient elasticsearchClient() {
  18. RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));
  19. RestHighLevelClient restHighLevelClient = new
  20. RestHighLevelClient(builder);
  21. return restHighLevelClient;
  22. }
  23. }

创建实体类Person

  1. package com.es.DO;
  2. import lombok.Data;
  3. import org.springframework.data.annotation.Id;
  4. import org.springframework.data.elasticsearch.annotations.Document;
  5. import org.springframework.data.elasticsearch.annotations.Field;
  6. import org.springframework.data.elasticsearch.annotations.FieldType;
  7. @Data
  8. @Document(indexName = "contact", shards = 3, replicas = 1)
  9. public class Person {
  10. /**
  11. * 主键 id
  12. */
  13. @Id
  14. public Long id;
  15. /**
  16. * 姓名 name
  17. */
  18. @Field(type = FieldType.Text, analyzer = "ik_max_word")
  19. public String name;
  20. /**
  21. * 年龄 age
  22. */
  23. @Field(type = FieldType.Integer)
  24. public int age;
  25. /**
  26. * 地址 address
  27. */
  28. @Field(type = FieldType.Keyword, index = false)
  29. public String address;
  30. }

配置Person的Dao类,PersonDao

  1. package com.es.dao;
  2. import com.es.DO.Person;
  3. import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
  4. import org.springframework.stereotype.Repository;
  5. @Repository
  6. public interface PersonDao extends ElasticsearchRepository<Person, Long>{
  7. }

创建测试类SpringDataESIndexTest,测试类跟启动类在同一个包下,不然启动会报错。

  1. package com.es.test;
  2. import com.es.DO.Person;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.test.context.SpringBootTest;
  7. import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9. @RunWith(SpringRunner.class)
  10. @SpringBootTest
  11. public class SpringDataESIndexTest {
  12. //注入 ElasticsearchRestTemplate
  13. @Autowired
  14. private ElasticsearchRestTemplate elasticsearchRestTemplate;
  15. //创建索引并增加映射配置
  16. @Test
  17. public void createIndex(){
  18. //创建索引,系统初始化会自动创建索引
  19. System.out.println("创建索引");
  20. }
  21. @Test
  22. public void deleteIndex(){
  23. //创建索引,系统初始化会自动创建索引
  24. boolean flg = elasticsearchRestTemplate.deleteIndex(Person.class);
  25. System.out.println("删除索引 = " + flg);
  26. }
  27. }

测试

  1. 对索引创建及删除进行测试
  2. http://IP地址:9200/_cat/indices?v,用浏览器或Postman等工具访问该地址来看结果
  3. 运行createIndex测试方法

  1. 运行deleteIndex测试方法

文档操作

  1. 新加SpringDataESPersonDaoTest测试类

新增

  1. @Autowired
  2. private PersonDao personDao;
  3. /**
  4. * 新增
  5. */
  6. @Test
  7. public void save(){
  8. Person person = new Person();
  9. person.setId(1L);
  10. person.setName("张三");
  11. person.setAge(21);
  12. person.setAddress("北京市海淀区");
  13. personDao.save(person);
  14. }

测试地址:http://IP地址:9200/contact/_doc/1

修改

  1. @Autowired
  2. private PersonDao personDao;
  3. //修改
  4. @Test
  5. public void update(){
  6. Person person = new Person();
  7. person.setId(1L);
  8. person.setName("张三");
  9. person.setAge(21);
  10. person.setAddress("北京市朝阳区");
  11. personDao.save(person);
  12. }

测试地址:http://IP地址:9200/contact/_doc/1

根据 id 查询

  1. @Autowired
  2. private PersonDao personDao;
  3. //根据 id 查询
  4. @Test
  5. public void findById(){
  6. Person person = personDao.findById(1L).get();
  7. System.out.println(person);
  8. }

打印成功

打印所有

  1. @Autowired
  2. private PersonDao personDao;
  3. @Test
  4. public void findAll(){
  5. Iterable<Person> persons = personDao.findAll();
  6. for (Person person : persons) {
  7. System.out.println(person);
  8. }
  9. }

删除

  1. @Autowired
  2. private PersonDao personDao;
  3. @Test
  4. public void delete(){
  5. Person person = new Person();
  6. person.setId(1L);
  7. personDao.delete(person);
  8. }

测试地址:http://IP地址:9200/contact/_doc/1

已删除

批量新增

  1. @Autowired
  2. private PersonDao personDao;
  3. //批量新增
  4. @Test
  5. public void saveAll(){
  6. List<Person> personList = new ArrayList<>();
  7. for (int i = 0; i < 10; i++) {
  8. Person person = new Person();
  9. person.setId(Long.valueOf(i));
  10. person.setName("["+i+"]张三");
  11. person.setAge(21+i);
  12. person.setAddress("北京市海淀区");
  13. personList.add(person);
  14. }
  15. personDao.saveAll(personList);
  16. }

测试地址:http://ip地址:9200/contact/_search

分页查询

  1. @Autowired
  2. private PersonDao personDao;
  3. @Test
  4. public void findByPageable(){
  5. //设置排序(排序方式,正序还是倒序,排序的 id)
  6. Sort sort = Sort.by(Sort.Direction.DESC,"id");
  7. int currentPage=0;//当前页,第一页从 0 开始, 1 表示第二页
  8. int pageSize = 5;//每页显示多少条
  9. //设置查询分页
  10. PageRequest pageRequest = PageRequest.of(currentPage, pageSize,sort);
  11. //分页查询
  12. Page<Person> personPage = personDao.findAll(pageRequest);
  13. for (Person person : personPage.getContent()) {
  14. System.out.println(person);
  15. }
  16. }

查询成功,查出第一页

完整代码如下

  1. package com.es.test;
  2. import com.es.DO.Person;
  3. import com.es.dao.PersonDao;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.data.domain.Page;
  9. import org.springframework.data.domain.PageRequest;
  10. import org.springframework.data.domain.Sort;
  11. import org.springframework.test.context.junit4.SpringRunner;
  12. import java.util.ArrayList;
  13. import java.util.List;
  14. @RunWith(SpringRunner.class)
  15. @SpringBootTest
  16. public class SpringDataESPersonDaoTest {
  17. @Autowired
  18. private PersonDao personDao;
  19. /**
  20. * 新增
  21. */
  22. @Test
  23. public void save(){
  24. Person person = new Person();
  25. person.setId(1L);
  26. person.setName("张三");
  27. person.setAge(21);
  28. person.setAddress("北京市海淀区");
  29. personDao.save(person);
  30. }
  31. //POSTMAN, GET http://IP地址:9200/contact/_doc/1
  32. //修改
  33. @Test
  34. public void update(){
  35. Person person = new Person();
  36. person.setId(1L);
  37. person.setName("张三");
  38. person.setAge(21);
  39. person.setAddress("北京市朝阳区");
  40. personDao.save(person);
  41. }
  42. //POSTMAN, GET http://IP地址:9200/contact/_doc/1
  43. //根据 id 查询
  44. @Test
  45. public void findById(){
  46. Person person = personDao.findById(1L).get();
  47. System.out.println(person);
  48. }
  49. @Test
  50. public void findAll(){
  51. Iterable<Person> persons = personDao.findAll();
  52. for (Person person : persons) {
  53. System.out.println(person);
  54. }
  55. }
  56. //删除
  57. @Test
  58. public void delete(){
  59. Person person = new Person();
  60. person.setId(1L);
  61. personDao.delete(person);
  62. }
  63. //POSTMAN, GET http://IP地址:9200/contact/_doc/1
  64. //批量新增
  65. @Test
  66. public void saveAll(){
  67. List<Person> personList = new ArrayList<>();
  68. for (int i = 0; i < 10; i++) {
  69. Person person = new Person();
  70. person.setId(Long.valueOf(i));
  71. person.setName("["+i+"]张三");
  72. person.setAge(21+i);
  73. person.setAddress("北京市海淀区");
  74. personList.add(person);
  75. }
  76. personDao.saveAll(personList);
  77. }
  78. //分页查询
  79. @Test
  80. public void findByPageable(){
  81. //设置排序(排序方式,正序还是倒序,排序的 id)
  82. Sort sort = Sort.by(Sort.Direction.DESC,"id");
  83. int currentPage=0;//当前页,第一页从 0 开始, 1 表示第二页
  84. int pageSize = 5;//每页显示多少条
  85. //设置查询分页
  86. PageRequest pageRequest = PageRequest.of(currentPage, pageSize,sort);
  87. //分页查询
  88. Page<Person> personPage = personDao.findAll(pageRequest);
  89. for (Person person : personPage.getContent()) {
  90. System.out.println(person);
  91. }
  92. }
  93. }

文档搜索

  1. 新建测试类SpringDataESSearchTest

termQuery

  1. @Autowired
  2. private PersonDao personDao;
  3. /**
  4. * term 查询
  5. * search(termQueryBuilder) 调用搜索方法,参数查询构建器对象
  6. */
  7. @Test
  8. public void termQuery(){
  9. TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "[8]张三");
  10. Iterable<Person> persons = personDao.search(termQueryBuilder);
  11. for (Person person : persons) {
  12. System.out.println(person);
  13. }
  14. }

termQuery加分页

  1. @Autowired
  2. private PersonDao personDao;
  3. /**
  4. * term 查询加分页
  5. */
  6. @Test
  7. public void termQueryByPage(){
  8. int currentPage= 0 ;
  9. int pageSize = 5;
  10. //设置查询分页
  11. PageRequest pageRequest = PageRequest.of(currentPage, pageSize);
  12. TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "[8]张三");
  13. Iterable<Person> persons =
  14. personDao.search(termQueryBuilder,pageRequest);
  15. for (Person person : persons) {
  16. System.out.println(person);
  17. }
  18. }

只有一条name为[8]张三的记录

完整代码如下

  1. package com.es.test;
  2. import com.es.DO.Person;
  3. import com.es.dao.PersonDao;
  4. import org.elasticsearch.index.query.QueryBuilders;
  5. import org.elasticsearch.index.query.TermQueryBuilder;
  6. import org.junit.Test;
  7. import org.junit.runner.RunWith;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.boot.test.context.SpringBootTest;
  10. import org.springframework.data.domain.PageRequest;
  11. import org.springframework.test.context.junit4.SpringRunner;
  12. @RunWith(SpringRunner.class)
  13. @SpringBootTest
  14. public class SpringDataESSearchTest {
  15. @Autowired
  16. private PersonDao personDao;
  17. /**
  18. * term 查询
  19. * search(termQueryBuilder) 调用搜索方法,参数查询构建器对象
  20. */
  21. @Test
  22. public void termQuery(){
  23. TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "[8]张三");
  24. Iterable<Person> persons = personDao.search(termQueryBuilder);
  25. for (Person person : persons) {
  26. System.out.println(person);
  27. }
  28. }
  29. /**
  30. * term 查询加分页
  31. */
  32. @Test
  33. public void termQueryByPage(){
  34. int currentPage= 0 ;
  35. int pageSize = 5;
  36. //设置查询分页
  37. PageRequest pageRequest = PageRequest.of(currentPage, pageSize);
  38. TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "[8]张三");
  39. Iterable<Person> persons =
  40. personDao.search(termQueryBuilder,pageRequest);
  41. for (Person person : persons) {
  42. System.out.println(person);
  43. }
  44. }
  45. }

本文转载自: https://blog.csdn.net/zhiwenganyong/article/details/122764105
版权归原作者 像向日葵一样~ 所有, 如有侵权,请联系我们删除。

“通过Spring Data Elasticsearch操作ES”的评论:

还没有评论