【SpringBoot】SpringBoot 整合ElasticSearch(二十一)

  本章介紹SpringBoot與ElasticSearch整合,SpringBoot默認支持兩種技術來與ES交互html

    一、Jest(默認不生效,須要導入jest工具包)java

    二、SpringBoot ElasticSearch(ES版本可能不合適,須要相應版本)node

  ElasticSearch安裝參考:【ElasticSearch】 安裝git

ElasticSearch自動配置

  一、搭建SpringBoot項目,pom.xml文件以下:github

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0"
 3  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5     <modelVersion>4.0.0</modelVersion>
 6 
 7     <groupId>com.test</groupId>
 8     <artifactId>test-springboot-es</artifactId>
 9     <version>1.0-SNAPSHOT</version>
10 
11     <parent>
12         <groupId>org.springframework.boot</groupId>
13         <artifactId>spring-boot-starter-parent</artifactId>
14         <version>2.1.8.RELEASE</version>
15     </parent>
16 
17     <properties>
18 
19         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
20         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
21         <java.version>1.8</java.version>
22     </properties>
23 
24     <dependencies>
25 
26         <dependency>
27             <groupId>org.springframework.boot</groupId>
28             <artifactId>spring-boot-starter-web</artifactId>
29         </dependency>
30 
31         <!-- SpringBoot默認使用SpringData ElasticSearch模塊進行操做 -->
32         <dependency>
33             <groupId>org.springframework.boot</groupId>
34             <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
35         </dependency>
36 
37         <!-- https://mvnrepository.com/artifact/io.searchbox/jest -->
38         <!--<dependency>-->
39             <!--<groupId>io.searchbox</groupId>-->
40             <!--<artifactId>jest</artifactId>-->
41             <!--<version>6.3.1</version>-->
42         <!--</dependency>-->
43 
44         <dependency>
45             <groupId>org.springframework.boot</groupId>
46             <artifactId>spring-boot-starter-test</artifactId>
47             <scope>test</scope>
48         </dependency>
49 
50     </dependencies>
51 
52 
53     <!-- SpringBoot打包插件,能夠將代碼打包成一個可執行的jar包 -->
54     <build>
55         <plugins>
56             <plugin>
57                 <groupId>org.springframework.boot</groupId>
58                 <artifactId>spring-boot-maven-plugin</artifactId>
59             </plugin>
60         </plugins>
61     </build>
62 </project>
pom.xml

  二、查看spring-boot-autoconfigure中,在org.springframework.boot.autoconfigure.data.elasticsearch包下有不少Elasticsearch自動配置類,能夠分別查看,能夠看到注入了對象,其中有ElasticsearchRepositoriesAutoConfiguration、ElasticsearchDataAutoConfiguration等web

    

  三、啓動ElasticsearchDataAutoConfiguration類中,自動注入了ElasticsearchTemplate,用於操做Elasticsearchspring

 1 public class ElasticsearchDataAutoConfiguration {  2 
 3  @Bean  4  @ConditionalOnMissingBean  5     @ConditionalOnBean(Client.class)  6     public ElasticsearchTemplate elasticsearchTemplate(Client client, ElasticsearchConverter converter) {  7         try {  8             return new ElasticsearchTemplate(client, converter);  9  } 10         catch (Exception ex) { 11             throw new IllegalStateException(ex); 12  } 13  } 14 
15  ... 16 }

  四、查看spring-boot-autoconfigure中,在org.springframework.boot.autoconfigure.elasticsearch.jest包下,有JestAutoConfiguration自動配置類,它給SpringBoot自動注入了JestClient也是用來操做Elasticsearch的apache

 1 public class JestAutoConfiguration {  2 
 3  ...  4 
 5     @Bean(destroyMethod = "shutdownClient")  6  @ConditionalOnMissingBean  7     public JestClient jestClient() {  8         JestClientFactory factory = new JestClientFactory();  9  factory.setHttpClientConfig(createHttpClientConfig()); 10         return factory.getObject(); 11  } 12 
13  ... 14 }

SpringBoot整合Jest

  一、在SpringBoot項目中,引入Jest依賴json

1 <dependency>
2     <groupId>io.searchbox</groupId>
3     <artifactId>jest</artifactId>
4     <version>6.3.1</version>
5 </dependency>

  二、添加jest的es配置信息瀏覽器

spring:
  elasticsearch:
    jest:
      uris: http://192.168.0.1:9200

  三、編寫測試類,測試jest,內容以下:

 1 package com.test.springboot.es;  2 
 3 import com.test.springboot.es.bean.Article;  4 import io.searchbox.client.JestClient;  5 import io.searchbox.core.Index;  6 import io.searchbox.core.Search;  7 import io.searchbox.core.SearchResult;  8 import org.junit.Test;  9 import org.junit.runner.RunWith; 10 import org.springframework.beans.factory.annotation.Autowired; 11 import org.springframework.boot.test.context.SpringBootTest; 12 import org.springframework.test.context.junit4.SpringRunner; 13 
14 import java.io.IOException; 15 
16 @RunWith(SpringRunner.class) 17 @SpringBootTest 18 public class TestApplication { 19 
20  @Autowired 21  JestClient jestClient; 22 
23     // 給ES索引(保存)一個文檔
24  @Test 25     public void contextLoad() throws IOException { 26         Article article = new Article(); 27         article.setId(1); 28         article.setTitle("好消息"); 29         article.setAuthor("張三"); 30         article.setContent("Hello Word"); 31 
32         // 構建一個索引功能
33         Index index = new Index.Builder(article).index("test").type("news").build(); 34         // 執行
35  jestClient.execute(index); 36  } 37 
38     // 測試Jest搜索
39  @Test 40     public void jestSearch() throws IOException { 41 
42         String json = "{\n" +
43                 "    \"query\" : {\n" +
44                 "        \"match\" : {\n" +
45                 "            \"content\" : \"Hello\"\n" +
46                 "        }\n" +
47                 "    }\n" +
48                 "}"; 49 
50         // 構建一個搜索功能
51         Search search = new Search.Builder(json).addIndex("test").addType("news").build(); 52         // 執行
53         SearchResult result = jestClient.execute(search); 54         // 打印結果
55  System.out.println(result.getJsonString()); 56  } 57 }

  四、測試方法

    運行方法contextLoad(),保存數據,使用地址(http://192.168.0.1:9200/test/news/_search)訪問ElasticSearch,得到數據以下:

    

    運行jestSearch() 方法,測試Jest搜索,效果以下:

    

  五、更多jestClient,能夠參考官方文檔:https://github.com/searchbox-io/Jest/tree/master/jest

SpringBoot整合ElasticSearch

  一、在SpringBoot項目中,引入依賴spring-boot-starter-data-elasticsearch,版本問題參考官網:https://docs.spring.io/spring-data/elasticsearch/docs/4.0.0.M4/reference/html/#preface.versions

1 <!-- SpringBoot默認使用SpringData ElasticSearch模塊進行操做 -->
2 <dependency>
3     <groupId>org.springframework.boot</groupId>
4     <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
5 </dependency>

 

  二、添加elasticsearch的配置信息

spring:
  data:
    elasticsearch:
      #集羣名稱
      cluster-name: elasticsearch
      #節點
      cluster-nodes: 192.168.0.1:9300

    注:其中節點的端口使用的是9300端口,也就是ES節點之間通信使用的端口。

 

  三、編輯方法save(),保存數據到elasticsearch中,內容以下:

 1 @RunWith(SpringRunner.class)  2 @SpringBootTest  3 public class TestApplication2 {  4 
 5  @Autowired  6  ElasticsearchTemplate elasticsearchTemplate;  7 
 8     // 給ES索引(保存)一個文檔
 9  @Test 10     public void save() { 11         Article article = new Article(); 12         article.setId(1); 13         article.setTitle("好消息"); 14         article.setAuthor("張三"); 15         article.setContent("Hello Word"); 16 
17         IndexQuery indexQuery = new IndexQueryBuilder() 18  .withId(article.getId().toString()) 19  .withObject(article) 20  .build(); 21 
22         // 存入索引,返回文檔ID
23         String documentId = elasticsearchTemplate.index(indexQuery); 24  System.out.println(documentId); 25 
26  } 27 }

 

 

     注意Article類須要進行文檔註釋,內容以下,不然報錯

1 @Document(indexName="test", type = "news") 2 public class Article { 3 
4     private Integer id; 5     private String author; 6     private String title; 7     private String content; 8 }

 

  四、測試方法save(),運行save()方法後,使用瀏覽器訪問es,地址:http://192.168.0.1:9200/test/news/1

      

  五、編輯方法search(),查詢數據

 1 // 測試elasticsearchTemplate搜索
 2 @Test  3 public void search() throws IOException {  4 
 5     String json = "{\n" +
 6             "        \"match\" : {\n" +
 7             "            \"content\" : \"Hello\"\n" +
 8             "        }\n" +
 9             "    }"; 10 
11     StringQuery query = new StringQuery(json); 12     query.addIndices("test"); 13     query.addTypes("news"); 14 
15     List<Article> articles = elasticsearchTemplate.queryForList(query, Article.class); 16     if(articles.size() > 0) { 17         for (Article a : articles){ 18  System.out.println(a.toString()); 19  } 20  } 21 }

 

  六、執行方法search(),結果以下:

    

  Spring Data Repositories功能

    參考文檔:https://docs.spring.io/spring-data/elasticsearch/docs/4.0.0.M4/reference/html/#repositories

    編寫一個ElasticsearchRepository的子接口來操ES

  七、編寫ElasticsearchRepository的子接口,無需使用@Repository註解,SpringBoot會自動注入容器

1 package com.test.springboot.es.bean.repository; 2 
3 import com.test.springboot.es.bean.Article; 4 import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; 5 
6 public interface ArticleRepository extends ElasticsearchRepository<Article, Integer> { 7 }

 

  八、編寫測試方法,測試ArticleRepository類的保存

 1 @Autowired  2 ArticleRepository articleRepository;  3 
 4 @Test  5 public void test01(){  6     Article article = new Article();  7     article.setId(2);  8     article.setTitle("慢消息");  9     article.setAuthor("李四"); 10     article.setContent("Hello XXXX"); 11 
12  articleRepository.save(article); 13 
14 }

  九、運行方法test01(),以後查詢索引test,地址:http://192.168.0.1:9200/test/news/_search

    

  十、自定義查詢方法,在ArticleRepository類中,增長findByAuthor方法

1 public interface ArticleRepository extends ElasticsearchRepository<Article, Integer> { 2 
3     List<Article> findByAuthor(String author); 4 
5 }

 

  十一、編輯測試方法forindByAuthor()

1 @Test 2 public void forindByAuthor(){ 3     List<Article> articles = articleRepository.findByAuthor("李四"); 4     if(articles.size() > 0) { 5         for (Article a : articles){ 6  System.out.println(a.toString()); 7  } 8  } 9 }

 

  十二、測試自定義查詢方法

    

    更多規則參考官網文檔:https://docs.spring.io/spring-data/elasticsearch/docs/4.0.0.M4/reference/html/#repositories.query-methods

相關文章
相關標籤/搜索