本文讲解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.  
  5. private String hostname = "127.0.0.1";
  6. private int port = 9300;
  7.  
  8. @Bean
  9. public ElasticsearchOperations elasticsearchTemplate() {
  10. return new ElasticsearchTemplate(client());
  11. }
  12.  
  13. @Bean
  14. public Client client() {
  15. TransportClient client = new TransportClient();
  16. TransportAddress address = new InetSocketTransportAddress(hostname, port);
  17.  
  18. client.addTransportAddress(address);
  19. return client;
  20. }
  21. }

业务操作

实体对象

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

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

Controller相关

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

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

总结

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

源代码

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

(完)

 

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

相关文章: