深入淺出 spring-data-elasticsearch - 基本案例詳解(三
『 風雲說:能分享自己職位的知識的領導是個好領導。 』運行環境:JDK 7 或 8,Maven 3.0+
技術棧:SpringBoot 1.5+, Spring Data Elasticsearch 1.5+ ,ElasticSearch 2.3.2
本文提綱
一、spring-data-elasticsearch-crud 的工程介紹
二、運行 spring-data-elasticsearch-crud 工程
三、spring-data-elasticsearch-crud 工程代碼詳解
一、spring-data-elasticsearch-crud 的工程介紹
spring-data-elasticsearch-crud 的工程,介紹 Spring Data Elasticsearch 簡單的 ES 操作。Spring Data Elasticsearch 可以跟 JPA 進行類比。其使用方法也很簡單。
二、運行 spring-data-elasticsearch-crud 工程
注意的是這裏使用的是 ElasticSearch 2.3.2。是因為版本對應關係 https://github.com/spring-projects/spring-data-elasticsearch/wiki/Spring-Data-Elasticsearch---Spring-Boot---version-matrix;
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 的版本會有重大的更新
1. 後台起守護線程啟動 Elasticsearch
cd elasticsearch-2.3.2/
./bin/elasticsearch -d
git clone 下載工程 springboot-elasticsearch ,項目地址見 GitHub - https://github.com/JeffLi1993/ ... ample。
下麵開始運行工程步驟(Quick Start):
2. 項目結構介紹
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.編譯工程
在項目根目錄 spring-data-elasticsearch-crud,運行 maven 指令:
mvn clean install
4.運行工程
右鍵運行 Application 應用啟動類(位置:/springboot-learning-example/springboot-elasticsearch/src/main/java/org/spring/springboot/Application.java)的 main 函數,這樣就成功啟動了 springboot-elasticsearch 案例。
用 Postman 工具新增兩個城市
a. 新增城市信息
POST http://127.0.0.1:8080/api/city
{
"id”:"1",
"score":"5",
"name":"上海",
"description":"上海是個熱城市"
}
POST http://127.0.0.1:8080/api/city
{
"id":"2",
"score”:"4",
"name”:”溫嶺",
"description":”溫嶺是個沿海城市"
}
可以打開 ES 可視化工具 head 插件:https://localhost:9200/_plugin/head/:
(如果不知道怎麼安裝,請查閱 《Elasticsearch 和插件 elasticsearch-head 安裝詳解》 https://www.bysocket.com/?p=1744 。)
在「數據瀏覽」tab,可以查閱到 ES 中數據是否被插入,插入後的數據格式如下:
{
"_index": "cityindex",
"_type": "city",
"_id": "1",
"_version": 1,
"_score": 1,
"_source": {
"id":"2",
"score”:"4",
"name”:”溫嶺",
"description":”溫嶺是個沿海城市"
}
}
下麵是基本查詢語句的接口:
a. 普通查詢,查詢城市描述
GET https://localhost:8080/api/city ... on%3D溫嶺
返回 JSON 如下:[
{
"id": 2,
"name": "溫嶺",
"description": "溫嶺是個沿海城市",
"score": 4
}
]
b. AND 語句查詢
GET https://localhost:8080/api/city ... on%3D溫嶺&score=4
返回 JSON 如下:[
{
"id": 2,
"name": "溫嶺",
"description": "溫嶺是個沿海城市",
"score": 4
}
]
如果換成 score=5 ,就沒有結果了。c. OR 語句查詢
GET https://localhost:8080/api/city ... on%3D上海&score=4
返回 JSON 如下:[
{
"id": 2,
"name": "溫嶺",
"description": "溫嶺是個沿海城市",
"score": 4
},
{
"id": 1,
"name": "上海",
"description": "上海是個好城市",
"score": 3
}
]
d. NOT 語句查詢
GET https://localhost:8080/api/city ... on%3D溫州
返回 JSON 如下:[
{
"id": 2,
"name": "溫嶺",
"description": "溫嶺是個沿海城市",
"score": 4
},
{
"id": 1,
"name": "上海",
"description": "上海是個好城市",
"score": 3
}
]
e. LIKE 語句查詢
GET https://localhost:8080/api/city ... on%3D城市
返回 JSON 如下:[
{
"id": 2,
"name": "溫嶺",
"description": "溫嶺是個沿海城市",
"score": 4
},
{
"id": 1,
"name": "上海",
"description": "上海是個好城市",
"score": 3
}
]
三、spring-data-elasticsearch-crud 工程代碼詳解
具體代碼見 GitHub - https://github.com/JeffLi1993/springboot-learning-example
1.pom.xml 依賴
<?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/ma ... gt%3B
<modelVersion>4.0.0</modelVersion>
<groupId>springboot</groupId>
<artifactId>spring-data-elasticsearch-crud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-data-elasticsearch-crud :: spring-data-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。對應官方文檔:https://docs.spring.io/spring-d ... html/。後麵數據操作層都是通過該 spring-data-elasticsearch 提供的接口實現。
2. application.properties 配置 ES 地址
# ES
spring.data.elasticsearch.repositories.enabled = true
spring.data.elasticsearch.cluster-nodes = 127.0.0.1:9300
默認 9300 是 Java 客戶端的端口。9200 是支持 Restful HTTP 的接口。
更多配置:
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 數據操作層
/**
* ES 操作類
* <p>
* Created by bysocket on 17/05/2017.
*/
public interface CityRepository extends ElasticsearchRepository<City, Long> {
/**
* AND 語句查詢
*
* @param description
* @param score
* @return
*/
List<City> findByDescriptionAndScore(String description, Integer score);
/**
* OR 語句查詢
*
* @param description
* @param score
* @return
*/
List<City> findByDescriptionOrScore(String description, Integer score);
/**
* 查詢城市描述
*
* 等同於下麵代碼
* @Query("{\"bool\" : {\"must\" : {\"term\" : {\"description\" : \"?0\"}}}}")
* Page<City> findByDescription(String description, Pageable pageable);
*
* @param description
* @param page
* @return
*/
Page<City> findByDescription(String description, Pageable page);
/**
* NOT 語句查詢
*
* @param description
* @param page
* @return
*/
Page<City> findByDescriptionNot(String description, Pageable page);
/**
* LIKE 語句查詢
*
* @param description
* @param page
* @return
*/
Page<City> findByDescriptionLike(String description, Pageable page);
}
接口隻要繼承 ElasticsearchRepository 類即可。默認會提供很多實現,比如 CRUD 和搜索相關的實現。類似於 JPA 讀取數據,是使用 CrudRepository 進行操作 ES 數據。支持的默認方法有: count(), findAll(), findOne(ID), delete(ID), deleteAll(), exists(ID), save(DomainObject), save(Iterable<DomainObject>)。
另外可以看出,接口的命名是遵循規範的。常用命名規則如下:
關鍵字 方法命名
And findByNameAndPwd
Or findByNameOrSex
Is findById
Between findByIdBetween
Like findByNameLike
NotLike findByNameNotLike
OrderBy findByIdOrderByXDesc
Not findByNameNot
4. 實體類
/**
* 城市實體類
* <p>
* Created by bysocket on 03/05/2017.
*/
@Document(indexName = "province", type = "city")
public class City implements Serializable {
private static final long serialVersionUID = -1L;
/**
* 城市編號
*/
private Long id;
/**
* 城市名稱
*/
private String name;
/**
* 描述
*/
private String description;
/**
* 城市評分
*/
private Integer score;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
}
注意
a. City 屬性名不支持駝峰式。
b. indexName 配置必須是全部小寫,不然會出異常。
org.elasticsearch.indices.InvalidIndexNameException: Invalid index name [provinceIndex], must be lowercase
四、小結
預告下
下一篇《深入淺出 spring-data-elasticsearch - 實戰案例詳解》,會帶來實戰項目中涉及到的權重分 & 短語精準匹配的講解。
摘要: 原創出處 www.bysocket.com 「泥瓦匠BYSocket 」歡迎轉載,保留摘要,謝謝!
最後更新:2017-06-20 20:58:15