Spring Boot整合Elasticsearch,實(shí)現(xiàn)function score query權(quán)重分查詢
本文提綱
一、ES 的使用場景
二、運(yùn)行 springboot-elasticsearch 工程
三、springboot-elasticsearch 工程代碼詳解
運(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
- cd elasticsearch-2.3.2/
- ./bin/elasticsearch -d
下面開始運(yùn)行工程步驟(Quick Start):
2. 項(xiàng)目結(jié)構(gòu)介紹
- org.spring.springboot.controller - Controller 層
- org.spring.springboot.repository - ES 數(shù)據(jù)操作層
- org.spring.springboot.domain - 實(shí)體類
- org.spring.springboot.service - ES 業(yè)務(wù)邏輯層
- Application - 應(yīng)用啟動(dòng)類
- 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 指令:
- 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è)城市
新增城市信息
- POST http://127.0.0.1:8080/api/city
- {
- "id":"1",
- "provinceid":"1",
- "cityname":"溫嶺",
- "description":"溫嶺是個(gè)好城市"
- }
- POST http://127.0.0.1:8080/api/city
- {
- "id":"2",
- "provinceid":"2",
- "cityname":"溫州",
- "description":"溫州是個(gè)熱城市"
- }
可以打開 ES 可視化工具 head 插件:http://localhost:9200/_plugin/head/:
(如果不知道怎么安裝,請查閱
《Elasticsearch 和插件 elasticsearch-head 安裝詳解》。)
在「數(shù)據(jù)瀏覽」tab,可以查閱到 ES 中數(shù)據(jù)是否被插入,插入后的數(shù)據(jù)格式如下:
- {
- "_index": "cityindex",
- "_type": "city",
- "_id": "1",
- "_version": 1,
- "_score": 1,
- "_source": {
- "id": 1,
- "provinceid": 1,
- "cityname": "溫嶺",
- "description": "溫嶺是個(gè)好城市"
- }
- }
下面驗(yàn)證下權(quán)重分查詢搜索接口的實(shí)現(xiàn):
- GET http://localhost:8080/api/city/search?pageNumber=0&pageSize=10&searchContent=溫嶺
數(shù)據(jù)是會(huì)出現(xiàn):
- [
- {
- "id": 1,
- "provinceid": 1,
- "cityname": "溫嶺",
- "description": "溫嶺是個(gè)好城市"
- },
- {
- "id": 2,
- "provinceid": 2,
- "cityname": "溫州",
- "description": "溫州是個(gè)熱城市"
- }
- ]
從啟動(dòng)后臺(tái) Console 可以看出,打印出來對(duì)應(yīng)的 DSL 語句:
- {
- "function_score" : {
- "functions" : [ {
- "filter" : {
- "bool" : {
- "should" : {
- "match" : {
- "cityname" : {
- "query" : "溫嶺",
- "type" : "boolean"
- }
- }
- }
- }
- },
- "weight" : 1000.0
- }, {
- "filter" : {
- "bool" : {
- "should" : {
- "match" : {
- "description" : {
- "query" : "溫嶺",
- "type" : "boolean"
- }
- }
- }
- }
- },
- "weight" : 100.0
- } ]
- }
- }
為什么會(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 依賴
- <dependencies>
- <!-- Spring Boot Elasticsearch 依賴 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
- </dependency>
- <!-- Spring Boot Web 依賴 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <!-- Junit -->
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.12</version>
- </dependency>
- </dependencies>
2. application.properties 配置 ES 地址
- # ES
- spring.data.elasticsearch.repositories.enabled = true
- spring.data.elasticsearch.cluster-nodes = 127.0.0.1:9300
默認(rèn) 9300 是 Java 客戶端的端口。9200 是支持 Restful HTTP 的接口。
3. ES 數(shù)據(jù)操作層
- @Repository
- public interface CityRepository extends ElasticsearchRepository<City,Long> {
- }
接口只要繼承 ElasticsearchRepository 類即可。默認(rèn)會(huì)提供很多實(shí)現(xiàn),比如 CRUD 和搜索相關(guān)的實(shí)現(xiàn)。
4. 實(shí)體類
- @Document(indexName = "cityindex", type = "city")
- public class City implements Serializable{
- private static final long serialVersionUID = -1L;
- /**
- * 城市編號(hào)
- */
- private Long id;
- /**
- * 省份編號(hào)
- */
- private Long provinceid;
- /**
- * 城市名稱
- */
- private String cityname;
- /**
- * 描述
- */
- private String description;
- }
注意
index 配置必須是全部小寫,不然會(huì)引出異常:
- org.elasticsearch.indices.InvalidIndexNameException: Invalid index name [cityIndex], must be lowercase
5. ES 業(yè)務(wù)邏輯層
Service 實(shí)現(xiàn)類:
- /**
- * 城市 ES 業(yè)務(wù)邏輯實(shí)現(xiàn)類
- *
- * Created by bysocket on 07/02/2017.
- */
- @Service
- public class CityESServiceImpl implements CityService {
- private static final Logger LOGGER = LoggerFactory.getLogger(CityESServiceImpl.class);
- @Autowired
- CityRepository cityRepository;
- @Override
- public Long saveCity(City city) {
- City cityResult = cityRepository.save(city);
- return cityResult.getId();
- }
- @Override
- public List<City> searchCity(Integer pageNumber,
- Integer pageSize,
- String searchContent) {
- // 分頁參數(shù)
- Pageable pageable = new PageRequest(pageNumber, pageSize);
- // Function Score Query
- FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery()
- .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("cityname", searchContent)),
- ScoreFunctionBuilders.weightFactorFunction(1000))
- .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("description", searchContent)),
- ScoreFunctionBuilders.weightFactorFunction(100));
- // 創(chuàng)建搜索 DSL 查詢
- SearchQuery searchQuery = new NativeSearchQueryBuilder()
- .withPageable(pageable)
- .withQuery(functionScoreQueryBuilder).build();
- LOGGER.info("\n searchCity(): searchContent [" + searchContent + "] \n DSL = \n " + searchQuery.getQuery().toString());
- Page<City> searchPageResults = cityRepository.search(searchQuery);
- return searchPageResults.getContent();
- }
- }
保存邏輯很簡單,這里不解釋了。
分頁 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)】