412
技術社區[雲棲]
Spring Boot 整合 Elasticsearch,實現 function score query 權重分查詢
摘要: 原創出處 www.bysocket.com 「泥瓦匠BYSocket 」歡迎轉載,保留摘要,謝謝!
『 預見未來最好的方式就是親手創造未來 – 《史蒂夫·喬布斯傳》 』
運行環境:JDK 7 或 8,Maven 3.0+
技術棧:SpringBoot 1.5+,ElasticSearch 2.3.2
本文提綱
一、ES 的使用場景
二、運行 springboot-elasticsearch 工程
三、springboot-elasticsearch 工程代碼詳解
一、ES 的使用場景
簡單說,ElasticSearch(簡稱 ES)是搜索引擎,是結構化數據的分布式搜索引擎。在《Elasticsearch 和插件 elasticsearch-head 安裝詳解》 和 《Elasticsearch 默認配置 IK 及 Java AnalyzeRequestBuilder 使用》 我詳細的介紹了如何安裝,初步使用了 IK 分詞器。這裏,我主要講下 SpringBoot 工程中如何使用 ElasticSearch。
ES 的使用場景大致分為兩塊
1. 全文檢索。加上分詞(IK 是其中一個)、拚音插件等可以成為強大的全文搜索引擎。
2. 日誌統計分析。可以實時動態分析海量日誌數據。
二、運行 springboot-elasticsearch 工程
注意的是這裏使用的是 ElasticSearch 2.3.2。是因為版本對應關係 :
|
1
2
3
4
|
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 文件版本號** - 下一個 ES 的版本會有重大的更新 |
git clone 下載工程 springboot-elasticsearch ,項目地址見 GitHub – https://github.com/JeffLi1993/springboot-learning-example。
1. 後台起守護線程啟動 Elasticsearch
|
1
2
|
cd elasticsearch-2.3.2/
./bin/elasticsearch -d
|
下麵開始運行工程步驟(Quick Start):
2. 項目結構介紹
|
1
2
3
4
5
6
|
org.spring.springboot.controller - Controller 層org.spring.springboot.repository - ES 數據操作層org.spring.springboot.domain - 實體類org.spring.springboot.service - ES 業務邏輯層Application - 應用啟動類application.properties - 應用配置文件,應用啟動會自動讀取配置 |
本地啟動的 ES ,就不需要改配置文件了。如果連測試 ES 服務地址,需要修改相應配置
3.編譯工程
在項目根目錄 springboot-elasticsearch,運行 maven 指令:
|
1
|
mvn clean install
|
4.運行工程
右鍵運行 Application 應用啟動類(位置:/springboot-learning-example/springboot-elasticsearch/src/main/java/org/spring/springboot/Application.java)的 main 函數,這樣就成功啟動了 springboot-elasticsearch 案例。
用 Postman 工具新增兩個城市
新增城市信息
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
POST http://127.0.0.1:8080/api/city
{"id":"1",
"provinceid":"1",
"cityname":"溫嶺",
"description":"溫嶺是個好城市"
}POST http://127.0.0.1:8080/api/city
{"id":"2",
"provinceid":"2",
"cityname":"溫州",
"description":"溫州是個熱城市"
} |
可以打開 ES 可視化工具 head 插件:https://localhost:9200/_plugin/head/:
(如果不知道怎麼安裝,請查閱 《Elasticsearch 和插件 elasticsearch-head 安裝詳解》 。)
在「數據瀏覽」tab,可以查閱到 ES 中數據是否被插入,插入後的數據格式如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
{"_index": "cityindex",
"_type": "city",
"_id": "1",
"_version": 1,
"_score": 1,
"_source": {
"id": 1,
"provinceid": 1,
"cityname": "溫嶺",
"description": "溫嶺是個好城市"
}} |
下麵驗證下權重分查詢搜索接口的實現:
GET https://localhost:8080/api/city/search?pageNumber=0&pageSize=10&searchContent=溫嶺
數據是會出現
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
[{"id": 1,
"provinceid": 1,
"cityname": "溫嶺",
"description": "溫嶺是個好城市"
},{"id": 2,
"provinceid": 2,
"cityname": "溫州",
"description": "溫州是個熱城市"
}] |
從啟動後台 Console 可以看出,打印出來對應的 DSL 語句:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
{"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
} ]}} |
為什麼會出現 溫州 城市呢?因為 function score query 權重分查詢,無相關的數據默認分值為 1。如果想除去,設置一個 setMinScore 分值即可。
三、springboot-elasticsearch 工程代碼詳解
具體代碼見 GitHub – https://github.com/JeffLi1993/springboot-learning-example
1.pom.xml 依賴
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>springboot</groupId>
<artifactId>springboot-elasticsearch</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-elasticsearch :: 整合 Elasticsearch </name>
<!-- Spring Boot 啟動父依賴 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<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>
</project>
|
這裏依賴的 spring-boot-starter-data-elasticsearch 版本是 1.5.1.RELEASE,對應的 spring-data-elasticsearch 版本是 2.1.0.RELEASE。後麵數據操作層都是通過該 spring-data-elasticsearch 提供的接口實現。
操作對應官方文檔:https://docs.spring.io/spring-data/elasticsearch/docs/2.1.0.RELEASE/reference/html/。
2. application.properties 配置 ES 地址
|
1
2
3
|
# ESspring.data.elasticsearch.repositories.enabled = true
spring.data.elasticsearch.cluster-nodes = 127.0.0.1:9300 |
默認 9300 是 Java 客戶端的端口。9200 是支持 Restful HTTP 的接口。
更多配置:
|
1
2
3
4
|
spring.data.elasticsearch.cluster-name Elasticsearch 集群名。(默認值: elasticsearch)spring.data.elasticsearch.cluster-nodes 集群節點地址列表,用逗號分隔。如果沒有指定,就啟動一個客戶端節點。spring.data.elasticsearch.propertie 用來配置客戶端的額外屬性。spring.data.elasticsearch.repositories.enabled 開啟 Elasticsearch 倉庫。(默認值:true。)
|
3. ES 數據操作層
|
1
2
3
4
5
|
@Repositorypublic interface CityRepository extends ElasticsearchRepository<City,Long> {
} |
接口隻要繼承 ElasticsearchRepository 類即可。默認會提供很多實現,比如 CRUD 和搜索相關的實現。
4. 實體類
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
@Document(indexName = "cityindex", type = "city")
public class City implements Serializable{ private static final long serialVersionUID = -1L;
/**
* 城市編號
*/
private Long id;
/**
* 省份編號
*/
private Long provinceid;
/**
* 城市名稱
*/
private String cityname;
/**
* 描述
*/
private String description;
} |
注意
index 配置必須是全部小寫,不然會暴異常。
org.elasticsearch.indices.InvalidIndexNameException: Invalid index name [cityIndex], must be lowercase
5. ES 業務邏輯層
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
/** * 城市 ES 業務邏輯實現類
*
* Created by bysocket on 07/02/2017.
*/
@Servicepublic 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) {
// 分頁參數
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));
// 創建搜索 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 搜索邏輯如下:
先創建分頁參數,然後用 FunctionScoreQueryBuilder 定義 Function Score Query,並設置對應字段的權重分值。城市名稱 1000 分,description 100 分。
然後創建該搜索的 DSL 查詢,並打印出來。
四、小結
實際場景還會很複雜。這裏隻是點睛之筆,後續大家優化或者更改下 DSL 語句就可以完成自己想要的搜索規則。
推薦:《Spring Boot 整合 Dubbo/ZooKeeper 詳解 SOA 案例》
上一篇:《Spring Boot 整合 Mybatis Annotation 注解案例》
歡迎掃一掃我的公眾號關注 — 及時得到博客訂閱哦!
— https://www.bysocket.com/ —
— https://github.com/JeffLi1993 —
最後更新:2017-05-19 12:04:49
