Spring Boot 揭秘與實戰(二) 數據存儲篇 - ElasticSearch


文章目錄

  1. 1. 版本須知
  2. 2. 環境依賴
  3. 3. 數據源
    1. 3.1. 方案一 使用 Spring Boot 默認配置
    2. 3.2. 方案二 手動創建
  4. 4. 業務操作5. 總結
    1. 4.1. 實體對象
    2. 4.2. DAO相關
    3. 4.3. Service相關
    4. 4.4. Controller相關
  5. 6. 源代碼

本文講解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

(完)

 

微信公眾號


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM