自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Spring Boot整合Elasticsearch,實(shí)現(xiàn)function score query權(quán)重分查詢

企業(yè)動(dòng)態(tài)
實(shí)際場景還會(huì)很復(fù)雜。這里只是點(diǎn)睛之筆,優(yōu)化或者更改下DSL語句就可以完成自己想要的搜索規(guī)則。

本文提綱

一、ES 的使用場景

二、運(yùn)行 springboot-elasticsearch 工程

三、springboot-elasticsearch 工程代碼詳解

[[191772]]

運(yùn)行環(huán)境:JDK 7 或 8,Maven 3.0+

技術(shù)棧:SpringBoot 1.5+,ElasticSearch 2.3.2

一、ES 的使用場景

簡單說,ElasticSearch(簡稱 ES)是搜索引擎,是結(jié)構(gòu)化數(shù)據(jù)的分布式搜索引擎。在

《Elasticsearch 和插件 elasticsearch-head 安裝詳解》

《Elasticsearch 默認(rèn)配置 IK 及 Java AnalyzeRequestBuilder 使用》

我詳細(xì)的介紹了如何安裝,初步使用了 IK 分詞器。這里,我主要講下 SpringBoot 工程中如何使用 ElasticSearch。

ES 的使用場景大致分為兩塊:

1. 全文檢索。加上分詞(IK 是其中一個(gè))、拼音插件等可以成為強(qiáng)大的全文搜索引擎。

2. 日志統(tǒng)計(jì)分析。可以實(shí)時(shí)動(dòng)態(tài)分析海量日志數(shù)據(jù)。

二、運(yùn)行 springboot-elasticsearch 工程

注意的是這里使用的是 ElasticSearch 2.3.2。是因?yàn)榘姹緦?duì)應(yīng)關(guān)系 :

  • 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**
  • * - 只需要你修改下對(duì)應(yīng)的 pom 文件版本號(hào)
  • ** - 下一個(gè) ES 的版本會(huì)有重大的更新

git clone 下載工程 springboot-elasticsearch ,項(xiàng)目地址見 GitHub - https://github.com/JeffLi1993/springboot-learning-example。

1. 后臺(tái)起守護(hù)線程啟動(dòng) Elasticsearch

  1. cd elasticsearch-2.3.2/  
  2. ./bin/elasticsearch -d 

下面開始運(yùn)行工程步驟(Quick Start):

2. 項(xiàng)目結(jié)構(gòu)介紹

  1. org.spring.springboot.controller - Controller 層  
  2. org.spring.springboot.repository - ES 數(shù)據(jù)操作層  
  3. org.spring.springboot.domain - 實(shí)體類  
  4. org.spring.springboot.service - ES 業(yè)務(wù)邏輯層  
  5. Application - 應(yīng)用啟動(dòng)類  
  6. application.properties - 應(yīng)用配置文件,應(yīng)用啟動(dòng)會(huì)自動(dòng)讀取配置 

本地啟動(dòng)的 ES ,就不需要改配置文件了。如果連測試 ES 服務(wù)地址,需要修改相應(yīng)配置

3.編譯工程

在項(xiàng)目根目錄 springboot-elasticsearch,運(yùn)行 maven 指令:

  1. mvn clean install 

4.運(yùn)行工程

右鍵運(yùn)行 Application 應(yīng)用啟動(dòng)類(位置:/springboot-learning-example/springboot-elasticsearch/src/main/java/org/spring/springboot/Application.java)的 main 函數(shù),這樣就成功啟動(dòng)了 springboot-elasticsearch 案例。

用 Postman 工具新增兩個(gè)城市

新增城市信息

  1. POST http://127.0.0.1:8080/api/city 
  2.     "id":"1"
  3.     "provinceid":"1"
  4.     "cityname":"溫嶺"
  5.     "description":"溫嶺是個(gè)好城市" 
  1. POST http://127.0.0.1:8080/api/city 
  2.     "id":"2"
  3.     "provinceid":"2"
  4.     "cityname":"溫州"
  5.     "description":"溫州是個(gè)熱城市" 

可以打開 ES 可視化工具 head 插件:http://localhost:9200/_plugin/head/

(如果不知道怎么安裝,請查閱

《Elasticsearch 和插件 elasticsearch-head 安裝詳解》。)

在「數(shù)據(jù)瀏覽」tab,可以查閱到 ES 中數(shù)據(jù)是否被插入,插入后的數(shù)據(jù)格式如下:

  1.      "_index""cityindex"
  2.      "_type""city"
  3.      "_id""1"
  4.      "_version": 1, 
  5.      "_score": 1, 
  6.      "_source": { 
  7.           "id": 1, 
  8.           "provinceid": 1, 
  9.           "cityname""溫嶺"
  10.           "description""溫嶺是個(gè)好城市" 
  11.      } 

下面驗(yàn)證下權(quán)重分查詢搜索接口的實(shí)現(xiàn):

  1. GET http://localhost:8080/api/city/search?pageNumber=0&pageSize=10&searchContent=溫嶺 

數(shù)據(jù)是會(huì)出現(xiàn):

  1.   { 
  2.     "id": 1, 
  3.     "provinceid": 1, 
  4.     "cityname""溫嶺"
  5.     "description""溫嶺是個(gè)好城市" 
  6.   }, 
  7.   { 
  8.     "id": 2, 
  9.     "provinceid": 2, 
  10.     "cityname""溫州"
  11.     "description""溫州是個(gè)熱城市" 
  12.   } 

從啟動(dòng)后臺(tái) Console 可以看出,打印出來對(duì)應(yīng)的 DSL 語句:

  1.  { 
  2.   "function_score" : { 
  3.     "functions" : [ { 
  4.       "filter" : { 
  5.         "bool" : { 
  6.           "should" : { 
  7.             "match" : { 
  8.               "cityname" : { 
  9.                 "query" : "溫嶺"
  10.                 "type" : "boolean" 
  11.               } 
  12.             } 
  13.           } 
  14.         } 
  15.       }, 
  16.       "weight" : 1000.0 
  17.     }, { 
  18.       "filter" : { 
  19.         "bool" : { 
  20.           "should" : { 
  21.             "match" : { 
  22.               "description" : { 
  23.                 "query" : "溫嶺"
  24.                 "type" : "boolean" 
  25.               } 
  26.             } 
  27.           } 
  28.         } 
  29.       }, 
  30.       "weight" : 100.0 
  31.     } ] 
  32.   } 

為什么會(huì)出現(xiàn) 溫州 城市呢?因?yàn)?function score query 權(quán)重分查詢,無相關(guān)的數(shù)據(jù)默認(rèn)分值為 1。如果想除去,設(shè)置一個(gè) setMinScore 分值即可。

三、springboot-elasticsearch 工程代碼詳解

具體代碼見 GitHub - https://github.com/JeffLi1993/springboot-learning-example

1.pom.xml 依賴

  1. <dependencies> 
  2.  
  3.     <!-- Spring Boot Elasticsearch 依賴 --> 
  4.     <dependency> 
  5.         <groupId>org.springframework.boot</groupId> 
  6.         <artifactId>spring-boot-starter-data-elasticsearch</artifactId> 
  7.     </dependency> 
  8.  
  9.     <!-- Spring Boot Web 依賴 --> 
  10.     <dependency> 
  11.         <groupId>org.springframework.boot</groupId> 
  12.         <artifactId>spring-boot-starter-web</artifactId> 
  13.     </dependency> 
  14.  
  15.     <!-- Junit --> 
  16.     <dependency> 
  17.         <groupId>junit</groupId> 
  18.         <artifactId>junit</artifactId> 
  19.         <version>4.12</version> 
  20.     </dependency> 
  21. </dependencies> 

2. application.properties 配置 ES 地址

  1. # ES 
  2. spring.data.elasticsearch.repositories.enabled = true 
  3. spring.data.elasticsearch.cluster-nodes = 127.0.0.1:9300 

默認(rèn) 9300 是 Java 客戶端的端口。9200 是支持 Restful HTTP 的接口。

3. ES 數(shù)據(jù)操作層

  1. @Repository 
  2. public interface CityRepository extends ElasticsearchRepository<City,Long> { 
  3.  

接口只要繼承 ElasticsearchRepository 類即可。默認(rèn)會(huì)提供很多實(shí)現(xiàn),比如 CRUD 和搜索相關(guān)的實(shí)現(xiàn)。

4. 實(shí)體類

  1. @Document(indexName = "cityindex", type = "city"
  2. public class City implements Serializable
  3.  
  4.     private static final long serialVersionUID = -1L; 
  5.  
  6.     /** 
  7.      * 城市編號(hào) 
  8.      */ 
  9.     private Long id; 
  10.  
  11.     /** 
  12.      * 省份編號(hào) 
  13.      */ 
  14.     private Long provinceid; 
  15.  
  16.     /** 
  17.      * 城市名稱 
  18.      */ 
  19.     private String cityname; 
  20.  
  21.     /** 
  22.      * 描述 
  23.      */ 
  24.     private String description; 

注意

index 配置必須是全部小寫,不然會(huì)引出異常:

  1. org.elasticsearch.indices.InvalidIndexNameException: Invalid index name [cityIndex], must be lowercase 

5. ES 業(yè)務(wù)邏輯層

Service 實(shí)現(xiàn)類:

  1. /** 
  2.  * 城市 ES 業(yè)務(wù)邏輯實(shí)現(xiàn)類 
  3.  * 
  4.  * Created by bysocket on 07/02/2017. 
  5.  */ 
  6. @Service 
  7. public class CityESServiceImpl implements CityService { 
  8.  
  9.     private static final Logger LOGGER = LoggerFactory.getLogger(CityESServiceImpl.class); 
  10.  
  11.     @Autowired 
  12.     CityRepository cityRepository; 
  13.  
  14.     @Override 
  15.     public Long saveCity(City city) { 
  16.  
  17.         City cityResult = cityRepository.save(city); 
  18.         return cityResult.getId(); 
  19.     } 
  20.  
  21.     @Override 
  22.     public List<City> searchCity(Integer pageNumber, 
  23.                                  Integer pageSize, 
  24.                                  String searchContent) { 
  25.         // 分頁參數(shù) 
  26.         Pageable pageable = new PageRequest(pageNumber, pageSize); 
  27.  
  28.         // Function Score Query 
  29.         FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery() 
  30.                 .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("cityname", searchContent)), 
  31.                     ScoreFunctionBuilders.weightFactorFunction(1000)) 
  32.                 .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("description", searchContent)), 
  33.                         ScoreFunctionBuilders.weightFactorFunction(100)); 
  34.  
  35.         // 創(chuàng)建搜索 DSL 查詢 
  36.         SearchQuery searchQuery = new NativeSearchQueryBuilder() 
  37.                 .withPageable(pageable) 
  38.                 .withQuery(functionScoreQueryBuilder).build(); 
  39.  
  40.         LOGGER.info("\n searchCity(): searchContent [" + searchContent + "] \n DSL  = \n " + searchQuery.getQuery().toString()); 
  41.  
  42.         Page<City> searchPageResults = cityRepository.search(searchQuery); 
  43.         return searchPageResults.getContent(); 
  44.     } 
  45.  

保存邏輯很簡單,這里不解釋了。

分頁 function score query 搜索邏輯:

先創(chuàng)建分頁參數(shù),然后用 FunctionScoreQueryBuilder 定義 Function Score Query,并設(shè)置對(duì)應(yīng)字段的權(quán)重分值。城市名稱 1000 分,description 100 分。

然后創(chuàng)建該搜索的 DSL 查詢,并打印出來。

四、小結(jié)

實(shí)際場景還會(huì)很復(fù)雜。這里只是點(diǎn)睛之筆,后續(xù)大家優(yōu)化或者更改下 DSL 語句就可以完成自己想要的搜索規(guī)則。

【本文為51CTO專欄作者“李強(qiáng)強(qiáng)”的原創(chuàng)稿件,轉(zhuǎn)載請通過51CTO聯(lián)系作者獲取授權(quán)】

戳這里,看該作者更多好文

責(zé)任編輯:武曉燕 來源: 51CTO專欄
相關(guān)推薦

2024-11-11 10:02:37

Spring搜索數(shù)據(jù)

2022-01-04 19:15:33

ElasticsearSpring BootLogstash

2017-04-17 10:35:40

Spring BooRedis 操作

2022-12-23 08:28:42

策略模式算法

2023-08-02 07:21:30

工具搜索排序

2017-10-17 15:14:33

Spring BooThymeleafWeb

2022-07-21 11:04:53

Swagger3Spring

2022-08-24 08:42:59

Minio存儲(chǔ)Golang

2023-10-12 10:32:51

2022-05-30 07:31:38

SpringBoot搜索技巧

2024-03-26 08:08:08

SpringBPMN模型

2022-05-06 10:42:09

JavaFlowable引擎

2021-12-27 09:59:57

SpringCanal 中間件

2021-09-16 10:29:05

開發(fā)技能代碼

2009-06-18 09:47:50

2023-10-09 16:35:19

方案Spring支付

2025-03-26 03:25:00

SpringGuavaCaffeine

2022-05-18 12:04:19

Mybatis數(shù)據(jù)源Spring

2017-05-12 15:47:15

Spring BootMybatis Ann Web

2023-11-13 12:48:32

語言DSL
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)