Spring Data Elasticsearch是Spring Data項目下的一個子模塊。
查看 Spring Data的官網:http://projects.spring.io/spring-data/
pring Data 的使命是給各種數據訪問提供統一的編程接口,不管是關系型數據庫(如MySQL),還是非關系數據庫(如Redis),或者類似Elasticsearch這樣的索引數據庫。從而簡化開發人員的代碼,提高開發效率。
1. 創建工程
我們使用spring腳手架新建一個demo,學習Elasticsearch
一路NEXT
pom.xml如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>elasticsearch</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>elasticsearch</name>
<description>Demo project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2. 配置application.yaml文件
spring:
data:
elasticsearch:
cluster-name: elasticsearch
cluster-nodes: 192.168.0.22:9300
3. 實體類及注解
首先我們准備好實體類:
public class Item {
Long id;
String title; //標題
String category;// 分類
String brand; // 品牌
Double price; // 價格
String images; // 圖片地址
}
映射
Spring Data通過注解來聲明字段的映射屬性,有下面的三個注解:
@Document
作用在類,標記實體類為文檔對象,一般有四個屬性- indexName:對應索引庫名稱
- type:對應在索引庫中的類型
- shards:分片數量,默認5
- replicas:副本數量,默認1
@Id
作用在成員變量,標記一個字段作為id主鍵@Field
作用在成員變量,標記為文檔的字段,並指定字段映射屬性:- type:字段類型,取值是枚舉:FieldType
- index:是否索引,布爾類型,默認是true
- store:是否存儲,布爾類型,默認是false
- analyzer:分詞器名稱:ik_max_word
示例:
package com.example.elasticsearch.pojo;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* @author john
* @date 2019/12/8 - 13:47
*/
@Document(indexName = "item",type = "docs", shards = 1, replicas = 0)
public class Item {
@Id
private Long id;
@Field(type = FieldType.Text, analyzer = "ik_max_word")
private String title; //標題
@Field(type = FieldType.Keyword)
private String category;// 分類
@Field(type = FieldType.Keyword)
private String brand; // 品牌
@Field(type = FieldType.Double)
private Double price; // 價格
@Field(index = false, type = FieldType.Keyword)
private String images; // 圖片地址
public Item() {
}
public Item(Long id, String title, String category, String brand, Double price, String images) {
this.id = id;
this.title = title;
this.category = category;
this.brand = brand;
this.price = price;
this.images = images;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getImages() {
return images;
}
public void setImages(String images) {
this.images = images;
}
@Override
public String toString() {
return "Item{" +
"id=" + id +
", title='" + title + '\'' +
", category='" + category + '\'' +
", brand='" + brand + '\'' +
", price=" + price +
", images='" + images + '\'' +
'}';
}
}
4. 測試創建索引
package com.example.elasticsearch;
import com.example.elasticsearch.pojo.Item;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author john
* @date 2019/12/8 - 14:09
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class ElasticSearctTest {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Test
public void testCreate() {
// 創建索引,會根據Item類的@Document注解信息來創建
elasticsearchTemplate.createIndex(Item.class);
// 配置映射,會根據Item類中的id、Field等字段來自動完成映射
elasticsearchTemplate.putMapping(Item.class);
}
}
使用kubia查詢
5. 增刪改操作
Spring Data 的強大之處,就在於你不用寫任何DAO處理,自動根據方法名或類的信息進行CRUD操作。只要你定義一個接口,然后繼承Repository提供的一些子接口,就能具備各種基本的CRUD功能。
編寫 ItemRepository
package com.example.elasticsearch.repository;
import com.example.elasticsearch.pojo.Item;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* @author john
* @date 2019/12/8 - 14:39
*/
public interface ItemRepository extends ElasticsearchRepository<Item,Long> {
}
5.1增加
@Autowired
private ItemRepository itemRepository;
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Test
public void testAdd() {
Item item = new Item(1L, "小米手機7", " 手機",
"小米", 3499.00, "http://image.leyou.com/13123.jpg");
itemRepository.save(item);
}
5.2 修改(id存在就是修改,否則就是插入)
@Autowired
private ItemRepository itemRepository;
@Test
public void testUpdate() {
Item item = new Item(1L, "小米手機7777", " 手機",
"小米", 9499.00, "http://image.leyou.com/13123.jpg");
itemRepository.save(item);
}
5.3 批量新增
@Autowired
private ItemRepository itemRepository;
@Test
public void indexList() {
List<Item> list = new ArrayList<>();
list.add(new Item(2L, "堅果手機R1", " 手機", "錘子", 3699.00, "http://image.leyou.com/123.jpg"));
list.add(new Item(3L, "華為META10", " 手機", "華為", 4499.00, "http://image.leyou.com/3.jpg"));
// 接收對象集合,實現批量新增
itemRepository.saveAll(list);
}
5.4 刪除操作
@Autowired
private ItemRepository itemRepository;
@Test
public void testDelete() {
itemRepository.deleteById(1L);
}
5.5 根據id查詢
@Test
public void testQuery(){
Optional<Item> optional = itemRepository.findById(2L);
System.out.println(optional.get());
}
5.6 查詢全部,並按照價格降序排序
@Test
public void testFind(){
// 查詢全部,並按照價格降序排序
Iterable<Item> items = this.itemRepository.findAll(Sort.by(Sort.Direction.DESC, "price"));
items.forEach(item-> System.out.println(item));
}
6. 自定義方法
Spring Data 的另一個強大功能,是根據方法名稱自動實現功能。
比如:你的方法名叫做:findByTitle,那么它就知道你是根據title查詢,然后自動幫你完成,無需寫實現類。
當然,方法名稱要符合一定的約定:
Keyword | Sample | Elasticsearch Query String |
---|---|---|
And |
findByNameAndPrice |
{"bool" : {"must" : [ {"field" : {"name" : "?"}}, {"field" : {"price" : "?"}} ]}} |
Or |
findByNameOrPrice |
{"bool" : {"should" : [ {"field" : {"name" : "?"}}, {"field" : {"price" : "?"}} ]}} |
Is |
findByName |
{"bool" : {"must" : {"field" : {"name" : "?"}}}} |
Not |
findByNameNot |
{"bool" : {"must_not" : {"field" : {"name" : "?"}}}} |
Between |
findByPriceBetween |
{"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : ?,"include_lower" : true,"include_upper" : true}}}}} |
LessThanEqual |
findByPriceLessThan |
{"bool" : {"must" : {"range" : {"price" : {"from" : null,"to" : ?,"include_lower" : true,"include_upper" : true}}}}} |
GreaterThanEqual |
findByPriceGreaterThan |
{"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : null,"include_lower" : true,"include_upper" : true}}}}} |
Before |
findByPriceBefore |
{"bool" : {"must" : {"range" : {"price" : {"from" : null,"to" : ?,"include_lower" : true,"include_upper" : true}}}}} |
After |
findByPriceAfter |
{"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : null,"include_lower" : true,"include_upper" : true}}}}} |
Like |
findByNameLike |
{"bool" : {"must" : {"field" : {"name" : {"query" : "?*","analyze_wildcard" : true}}}}} |
StartingWith |
findByNameStartingWith |
{"bool" : {"must" : {"field" : {"name" : {"query" : "?*","analyze_wildcard" : true}}}}} |
EndingWith |
findByNameEndingWith |
{"bool" : {"must" : {"field" : {"name" : {"query" : "*?","analyze_wildcard" : true}}}}} |
Contains/Containing |
findByNameContaining |
{"bool" : {"must" : {"field" : {"name" : {"query" : "**?**","analyze_wildcard" : true}}}}} |
In |
findByNameIn(Collection<String>names) |
{"bool" : {"must" : {"bool" : {"should" : [ {"field" : {"name" : "?"}}, {"field" : {"name" : "?"}} ]}}}} |
NotIn |
findByNameNotIn(Collection<String>names) |
{"bool" : {"must_not" : {"bool" : {"should" : {"field" : {"name" : "?"}}}}}} |
Near |
findByStoreNear |
Not Supported Yet ! |
True |
findByAvailableTrue |
{"bool" : {"must" : {"field" : {"available" : true}}}} |
False |
findByAvailableFalse |
{"bool" : {"must" : {"field" : {"available" : false}}}} |
OrderBy |
findByAvailableTrueOrderByNameDesc |
{"sort" : [{ "name" : {"order" : "desc"} }],"bool" : {"must" : {"field" : {"available" : true}}}} |
例如,我們來按照價格區間查詢,定義這樣的一個方法:
public interface ItemRepository extends ElasticsearchRepository<Item,Long> {
/**
* 根據價格區間查詢
* @param price1
* @param price2
* @return
*/
List<Item> findByPriceBetween(double price1, double price2);
}
然后添加一些測試數據:
@Test
public void indexList() {
List<Item> list = new ArrayList<>();
list.add(new Item(1L, "小米手機7", "手機", "小米", 3299.00, "http://image.leyou.com/13123.jpg"));
list.add(new Item(2L, "堅果手機R1", "手機", "錘子", 3699.00, "http://image.leyou.com/13123.jpg"));
list.add(new Item(3L, "華為META10", "手機", "華為", 4499.00, "http://image.leyou.com/13123.jpg"));
list.add(new Item(4L, "小米Mix2S", "手機", "小米", 4299.00, "http://image.leyou.com/13123.jpg"));
list.add(new Item(5L, "榮耀V10", "手機", "華為", 2799.00, "http://image.leyou.com/13123.jpg"));
// 接收對象集合,實現批量新增
itemRepository.saveAll(list);
}
不需要寫實現類,然后我們直接去運行:
@Test
public void queryByPriceBetween(){
List<Item> list = this.itemRepository.findByPriceBetween(2000.00, 3500.00);
for (Item item : list) {
System.out.println("item = " + item);
}
}
雖然基本查詢和自定義方法已經很強大了,但是如果是復雜查詢(模糊、通配符、詞條查詢等)就顯得力不從心了。此時,我們只能使用原生查詢。
7. 高級查詢
7.1.基本查詢
先看看基本玩法
@Test
public void testBaseQuery(){
// 詞條查詢
MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("title", "小米");
// 執行查詢
Iterable<Item> items = this.itemRepository.search(queryBuilder);
items.forEach(System.out::println);
}
QueryBuilders提供了大量的靜態方法,用於生成各種不同類型的查詢對象,例如:詞條、模糊、通配符等QueryBuilder對象。
結果:
elasticsearch提供很多可用的查詢方式,但是不夠靈活。如果想玩過濾或者聚合查詢等就很難了。
7.2 自定義查詢
先來看最基本的match query:
@Test
public void testNativeQuery(){
// 構建查詢條件
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
// 添加基本的分詞查詢
queryBuilder.withQuery(QueryBuilders.matchQuery("title", "小米"));
// 執行搜索,獲取結果
Page<Item> items = this.itemRepository.search(queryBuilder.build());
// 打印總條數
System.out.println(items.getTotalElements());
// 打印總頁數
System.out.println(items.getTotalPages());
items.forEach(System.out::println);
}
NativeSearchQueryBuilder:Spring提供的一個查詢條件構建器,幫助構建json格式的請求體
Page<item>
:默認是分頁查詢,因此返回的是一個分頁的結果對象,包含屬性:
- totalElements:總條數
- totalPages:總頁數
- Iterator:迭代器,本身實現了Iterator接口,因此可直接迭代得到當前頁的數據
- 其它屬性:
7.3 分頁查詢
利用NativeSearchQueryBuilder
可以方便的實現分頁:
@Test
public void testNativeQuery2(){
// 構建查詢條件
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
// 添加基本的分詞查詢
queryBuilder.withQuery(QueryBuilders.termQuery("category", "手機"));
// 初始化分頁參數
int page = 0;
int size = 3;
// 設置分頁參數
queryBuilder.withPageable(PageRequest.of(page, size));
// 執行搜索,獲取結果
Page<Item> items = this.itemRepository.search(queryBuilder.build());
// 打印總條數
System.out.println(items.getTotalElements());
// 打印總頁數
System.out.println(items.getTotalPages());
// 每頁大小
System.out.println(items.getSize());
// 當前頁
System.out.println(items.getNumber());
items.forEach(System.out::println);
}
結果:
可以發現,Elasticsearch中的分頁是從第0頁開始。
7.4 排序
排序也通用通過NativeSearchQueryBuilder
完成:
@Test
public void testSort(){
// 構建查詢條件
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
// 添加基本的分詞查詢
queryBuilder.withQuery(QueryBuilders.termQuery("category", "手機"));
// 排序
queryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.DESC));
// 執行搜索,獲取結果
Page<Item> items = this.itemRepository.search(queryBuilder.build());
// 打印總條數
System.out.println(items.getTotalElements());
items.forEach(System.out::println);
}
結果:
8. 聚合
8.1 聚合為桶
桶就是分組,比如這里我們按照品牌brand進行分組:
@Test
public void testAgg(){
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
// 不查詢任何結果
queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{""}, null));
// 1、添加一個新的聚合,聚合類型為terms,聚合名稱為brands,聚合字段為brand
queryBuilder.addAggregation(
AggregationBuilders.terms("brands").field("brand"));
// 2、查詢,需要把結果強轉為AggregatedPage類型
AggregatedPage<Item> aggPage = (AggregatedPage<Item>) this.itemRepository.search(queryBuilder.build());
// 3、解析
// 3.1、從結果中取出名為brands的那個聚合,
// 因為是利用String類型字段來進行的term聚合,所以結果要強轉為StringTerm類型
StringTerms agg = (StringTerms) aggPage.getAggregation("brands");
// 3.2、獲取桶
List<StringTerms.Bucket> buckets = agg.getBuckets();
// 3.3、遍歷
for (StringTerms.Bucket bucket : buckets) {
// 3.4、獲取桶中的key,即品牌名稱
System.out.println(bucket.getKeyAsString());
// 3.5、獲取桶中的文檔數量
System.out.println(bucket.getDocCount());
}
}
顯示的結果:
8.2 嵌套聚合,求平均值
代碼:
@Test
public void testSubAgg(){
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
// 不查詢任何結果
queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{""}, null));
// 1、添加一個新的聚合,聚合類型為terms,聚合名稱為brands,聚合字段為brand
queryBuilder.addAggregation(
AggregationBuilders.terms("brands").field("brand")
.subAggregation(AggregationBuilders.avg("priceAvg").field("price")) // 在品牌聚合桶內進行嵌套聚合,求平均值
);
// 2、查詢,需要把結果強轉為AggregatedPage類型
AggregatedPage<Item> aggPage = (AggregatedPage<Item>) this.itemRepository.search(queryBuilder.build());
// 3、解析
// 3.1、從結果中取出名為brands的那個聚合,
// 因為是利用String類型字段來進行的term聚合,所以結果要強轉為StringTerm類型
StringTerms agg = (StringTerms) aggPage.getAggregation("brands");
// 3.2、獲取桶
List<StringTerms.Bucket> buckets = agg.getBuckets();
// 3.3、遍歷
for (StringTerms.Bucket bucket : buckets) {
// 3.4、獲取桶中的key,即品牌名稱 3.5、獲取桶中的文檔數量
System.out.println(bucket.getKeyAsString() + ",共" + bucket.getDocCount() + "台");
// 3.6.獲取子聚合結果:
InternalAvg avg = (InternalAvg) bucket.getAggregations().asMap().get("priceAvg");
System.out.println("平均售價:" + avg.getValue());
}
}
結果: