本文讲解Spring Boot基础下,如何使用 ElasticSearch,实现全文搜索。

版本须知

spring data elasticSearch 的版本与Spring boot、Elasticsearch版本需要匹配。

Spring Boot Version (x) Spring Data Elasticsearch Version (y) Elasticsearch Version (z)
x <= 1.3.5 y <= 1.3.4 z <= 1.7.2
x >= 1.4.x 2.0.0 <=y <5.0.0 2.0.0 <= z < 5.0.0

环境依赖

修改 POM 文件,添加 spring-boot-starter-data-elasticsearch 依赖。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
  4. </dependency>

数据源

方案一 使用 Spring Boot 默认配置

在 src/main/resources/application.properties 中配置数据源信息。

  1. spring.data.elasticsearch.properties.host = 127.0.0.1
  2. spring.data.elasticsearch.properties.port = 9300

通过 Java Config 创建ElasticSearchConfig。

  1. @Configuration
  2. @EnableElasticsearchRepositories("com.lianggzone.springboot.action.data.elasticsearch")
  3. public class ElasticSearchConfig {}

方案二 手动创建

通过 Java Config 创建ElasticSearchConfig。

  1. @Configuration
  2. @EnableElasticsearchRepositories("com.lianggzone.springboot.action.data.elasticsearch")
  3. public class ElasticsearchConfig2 {
  4. private String hostname = "127.0.0.1";
  5. private int port = 9300;
  6. @Bean
  7. public ElasticsearchOperations elasticsearchTemplate() {
  8. return new ElasticsearchTemplate(client());
  9. }
  10. @Bean
  11. public Client client() {
  12. TransportClient client = new TransportClient();
  13. TransportAddress address = new InetSocketTransportAddress(hostname, port);
  14. client.addTransportAddress(address);
  15. return client;
  16. }
  17. }

业务操作

实体对象

  1. @Document(indexName = "springbootdb", type = "news")
  2. public class News {
  3. @Id
  4. private String id;
  5. private String title;
  6. private String content;
  7. @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyyMMdd'T'HHmmss.SSS'Z'")
  8. @Field(type = FieldType.Date, format = DateFormat.basic_date_time, index = FieldIndex.not_analyzed)
  9. @CreatedDate
  10. private Date createdDateTime;
  11. // GET和SET方法
  12. }

DAO相关

  1. public interface NewsRepository extends ElasticsearchRepository<News, String> {
  2. public List<News> findByTitle(String title);
  3. }

Service相关

我们来定义实现类,Service层调用Dao层的方法,这个是典型的套路。

  1. @Service
  2. public class NewsService {
  3. @Autowired
  4. private NewsRepository newsRepository;
  5. public Iterable<News> findAll(){
  6. return newsRepository.findAll();
  7. }
  8. public Iterable<News> search(QueryBuilder query){
  9. return newsRepository.search(query);
  10. }
  11. public List <News> findByTitle(String title) {
  12. return this.newsRepository.findByTitle(title);
  13. }
  14. public void deleteAll(String id){
  15. this.newsRepository.delete(id);
  16. }
  17. public void init(){
  18. for (int i = 0; i < 100; i++) {
  19. News news = new News();
  20. news.setId(i+"");
  21. news.setTitle(i + ".梁桂钊单元测试用例");
  22. news.setContent("梁桂钊单元测试用例"+i+"xxxxx");
  23. news.setCreatedDateTime(new Date());
  24. this.newsRepository.save(news);
  25. }
  26. }
  27. }

Controller相关

为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。

  1. @RestController
  2. @RequestMapping(value="/data/elasticsearch/news")
  3. public class NewsController {
  4. @Autowired
  5. private NewsService newsService;
  6. /**
  7. * 初始化
  8. * @param request
  9. */
  10. @RequestMapping(value = "/init", method = RequestMethod.POST)
  11. public void init(HttpServletRequest request) {
  12. this.newsService.init();
  13. }
  14. /**
  15. * findAll
  16. * @param request
  17. * @return
  18. */
  19. @RequestMapping(value = "/", method = RequestMethod.GET)
  20. public Map<String, Object> findList(HttpServletRequest request) {
  21. Map<String, Object> params = new HashMap<String, Object>();
  22. params.put("items", this.newsService.findAll());
  23. return params;
  24. }
  25. /**
  26. * find
  27. * @param request
  28. * @return
  29. */
  30. @RequestMapping(value = "/{title}", method = RequestMethod.GET)
  31. public Map<String, Object> search(@PathVariable String title) {
  32. // 构建查询条件
  33. QueryBuilder queryBuilder = QueryBuilders.queryString(title);
  34. Map<String, Object> params = new HashMap<String, Object>();
  35. params.put("items", this.newsService.search(queryBuilder));
  36. return params;
  37. }
  38. }

总结

上面这个简单的案例,让我们看到了 Spring Boot 整合 ElasticSearch 流程如此简单。

源代码

相关示例完整代码: springboot-action

(完)

如果觉得我的文章对你有帮助,请随意打赏。

Spring Boot 揭秘与实战(二) 数据存储篇 - ElasticSearch的更多相关文章

  1. Spring Boot 揭秘与实战(二) 数据存储篇 - 声明式事务管理

    文章目录 1. 声明式事务 2. Spring Boot默认集成事务 3. 实战演练4. 源代码 3.1. 实体对象 3.2. DAO 相关 3.3. Service 相关 3.4. 测试,测试 本文 ...

  2. Spring Boot 揭秘与实战(二) 数据存储篇 - MongoDB

    文章目录 1. 环境依赖 2. 数据源 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 3. 使用mongoTemplate操作4. 总结 3.1. 实体对象 3 ...

  3. Spring Boot 揭秘与实战(二) 数据存储篇 - Redis

    文章目录 1. 环境依赖 2. 数据源 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 3. 使用 redisTemplate 操作4. 总结 3.1. 工具类 ...

  4. Spring Boot 揭秘与实战(二) 数据存储篇 - JPA整合

    文章目录 1. 环境依赖 2. 数据源 3. 脚本初始化 4. JPA 整合方案一 通过继承 JpaRepository 接口 4.1. 实体对象 4.2. DAO相关 4.3. Service相关 ...

  5. Spring Boot 揭秘与实战(二) 数据存储篇 - MyBatis整合

    文章目录 1. 环境依赖 2. 数据源3. 脚本初始化 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 4. MyBatis整合5. 总结 4.1. 方案一 通过 ...

  6. Spring Boot 揭秘与实战(二) 数据存储篇 - 数据访问与多数据源配置

    文章目录 1. 环境依赖 2. 数据源 3. 单元测试 4. 源代码 在某些场景下,我们可能会在一个应用中需要依赖和访问多个数据源,例如针对于 MySQL 的分库场景.因此,我们需要配置多个数据源. ...

  7. Spring Boot 揭秘与实战(二) 数据存储篇 - MySQL

    文章目录 1. 环境依赖 2. 数据源3. 脚本初始化 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 4. 使用JdbcTemplate操作5. 总结 4.1. ...

  8. Spring Boot 揭秘与实战(二) 数据缓存篇 - 快速入门

    文章目录 1. 声明式缓存 2. Spring Boot默认集成CacheManager 3. 默认的 ConcurrenMapCacheManager 4. 实战演练5. 扩展阅读 4.1. Mav ...

  9. Spring Boot 揭秘与实战(二) 数据缓存篇 - Redis Cache

    文章目录 1. Redis Cache 集成 2. 源代码 本文,讲解 Spring Boot 如何集成 Redis Cache,实现缓存. 在阅读「Spring Boot 揭秘与实战(二) 数据缓存 ...

随机推荐

  1. activiti实战系列之动态表单 formService 自定义变量类型

    目前Activiti默认支持的类型有String,long,enum,date,boolean,collection 要自定义字段类型,首先需要表单类型解析类 /** * @Author:LJ * @ ...

  2. Physical Limits of ASM

    Oracle version 7, only 1,022 datafiles per database could be used.  Oracle version 11g, support 65,5 ...

  3. Spring控制反转(依赖注入)的最简单说明

    1.常规方式实现实例化 1.1已有角色如下: 一个接口Interface,两个接口实现类InstatnceA.InstanceB,一个调用类User 1.2当前实例化InstanceA如下: Inte ...

  4. 关于RabbitMQ服务器整合(二)

    准备工作 15min IDEA maven 3.0 在开始构建项目之前,机器需要安装rabbitmq,你可以去官网下载,http://www.rabbitmq.com/download.html ,如 ...

  5. python 利用turtle库绘制五角星

    # -*- coding: utf-8 –*-import turtleimport math def draw_polygon(aTurtle, size=50, n=3): for i in ra ...

  6. linux文件管理 文件搜索

    文件搜索命令find 'find [搜索范围] [搜索条件]' 搜索文件 find / -name install.log #避免大范围搜索,会非常消耗系统资源 #find是在系统当中搜索符合条件的文 ...

  7. Hive/hbase/sqoop的基本使用教程~

    Hive/hbase/sqoop的基本使用教程~ ###Hbase基本命令start-hbase.sh     #启动hbasehbase shell      #进入hbase编辑命令 list  ...

  8. 无法获取 vmci 驱动程序版本: 句柄无效

    https://jingyan.baidu.com/article/a3a3f811ea5d2a8da2eb8aa1.html 将 vmci0.present = "TURE" 改 ...

  9. 解决无法创建 JPA 工程的问题

    原创播客,如需转载请注明出处.原文地址:http://www.cnblogs.com/crawl/p/7703803.html ------------------------------------ ...

  10. 利用SMB jcifs实现对windows中的共享文件夹的操作

    需求是在本地上传文件到服务器上,服务器是windows的,使用共享文件夹提供权限给你的. 利用第三方: CIFS (Common Internet File System) SMB(Server Me ...