SpringBoot整合elasticsearch
在這一篇文章開始之前,你需要先安裝一個ElasticSearch,如果你是mac或者linux可以參考https://www.jianshu.com/p/e47b451375ea,如果是windows可以自定百度一下。
下面是官方套話介紹elasticsearch:
ElasticSearch是一個基於Lucene的搜尋伺服器。它提供了一個分散式多使用者能力的全文搜尋引擎,基於RESTful web介面。Elasticsearch是用Java開發的,並作為Apache許可條款下的開放原始碼釋出,是當前流行的企業級搜尋引擎。設計用於雲端計算中,能夠達到實時搜尋,穩定,可靠,快速,安裝使用方便。 我們建立一個網站或應用程式,並要新增搜尋功能,但是想要完成搜尋工作的建立是非常困難的。我們希望搜尋解決方案要執行速度快,我們希望能有一個零配置和一個完全免費的搜尋模式,我們希望能夠簡單地使用JSON通過HTTP來索引資料,我們希望我們的搜尋伺服器始終可用,我們希望能夠從一臺開始並擴充套件到數百臺,我們要實時搜尋,我們要簡單的多租戶,我們希望建立一個雲的解決方案。因此我們利用Elasticsearch來解決所有這些問題及可能出現的更多其它問題。
具體elasticsearch相關問題可以去elastic中文社群檢視。
這一篇文章將介紹springboot如何簡單整合elasticsearch。
1.啟動elasticsearch。 2.新建專案,pom檔案中加入elasticsearch依賴,完整pom如下:
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.dalaoyang</groupId> <artifactId>springboot_elasticsearch</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot_elasticsearch</name> <description>springboot_elasticsearch</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <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-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
配置檔案如下:
##埠號
server.port=8888
##es地址
spring.data.elasticsearch.cluster-nodes = 127.0.0.1:9300
新建一個商品實體類GoodsInfo,其中需要注意: indexName:索引名稱 可以理解為資料庫名 必須為小寫 不然會報org.elasticsearch.indices.InvalidIndexNameException異常 type:型別 可以理解為表名
package com.dalaoyang.entity;
import org.springframework.data.elasticsearch.annotations.Document;
import java.io.Serializable;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.entity
* @email [email protected]
* @date 2018/5/4
*/
@Document(indexName = "testgoods",type = "goods")
//indexName索引名稱 可以理解為資料庫名 必須為小寫 不然會報org.elasticsearch.indices.InvalidIndexNameException異常
//type型別 可以理解為表名
public class GoodsInfo implements Serializable {
private Long id;
private String name;
private String description;
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 GoodsInfo(Long id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
}
public GoodsInfo() {
}
}
建立GoodsRepository,繼承ElasticsearchRepository,程式碼如下:
package com.dalaoyang.repository;
import com.dalaoyang.entity.GoodsInfo;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.repository
* @email [email protected]
* @date 2018/5/4
*/
@Component
public interface GoodsRepository extends ElasticsearchRepository<GoodsInfo,Long> {
}
最後新建一個controller進行測試,其中包含簡單的增刪改查以及一個搜尋,增刪改查這裡不做解釋了。需要注意es的第一頁頁碼是0
package com.dalaoyang.controller;
import com.dalaoyang.entity.GoodsInfo;
import com.dalaoyang.repository.GoodsRepository;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.controller
* @email [email protected]
* @date 2018/5/4
*/
@RestController
public class GoodsController {
@Autowired
private GoodsRepository goodsRepository;
//http://localhost:8888/save
@GetMapping("save")
public String save(){
GoodsInfo goodsInfo = new GoodsInfo(System.currentTimeMillis(),
"商品"+System.currentTimeMillis(),"這是一個測試商品");
goodsRepository.save(goodsInfo);
return "success";
}
//http://localhost:8888/delete?id=1525415333329
@GetMapping("delete")
public String delete(long id){
goodsRepository.delete(id);
return "success";
}
//http://localhost:8888/update?id=1525417362754&name=修改&description=修改
@GetMapping("update")
public String update(long id,String name,String description){
GoodsInfo goodsInfo = new GoodsInfo(id,
name,description);
goodsRepository.save(goodsInfo);
return "success";
}
//http://localhost:8888/getOne?id=1525417362754
@GetMapping("getOne")
public GoodsInfo getOne(long id){
GoodsInfo goodsInfo = goodsRepository.findOne(id);
return goodsInfo;
}
//每頁數量
private Integer PAGESIZE=10;
//http://localhost:8888/getGoodsList?query=商品
//http://localhost:8888/getGoodsList?query=商品&pageNumber=1
//根據關鍵字"商品"去查詢列表,name或者description包含的都查詢
@GetMapping("getGoodsList")
public List<GoodsInfo> getList(Integer pageNumber,String query){
if(pageNumber==null) pageNumber = 0;
//es搜尋預設第一頁頁碼是0
SearchQuery searchQuery=getEntitySearchQuery(pageNumber,PAGESIZE,query);
Page<GoodsInfo> goodsPage = goodsRepository.search(searchQuery);
return goodsPage.getContent();
}
private SearchQuery getEntitySearchQuery(int pageNumber, int pageSize, String searchContent) {
FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery()
.add(QueryBuilders.matchPhraseQuery("name", searchContent),
ScoreFunctionBuilders.weightFactorFunction(100))
.add(QueryBuilders.matchPhraseQuery("description", searchContent),
ScoreFunctionBuilders.weightFactorFunction(100))
//設定權重分 求和模式
.scoreMode("sum")
//設定權重分最低分
.setMinScore(10);
// 設定分頁
Pageable pageable = new PageRequest(pageNumber, pageSize);
return new NativeSearchQueryBuilder()
.withPageable(pageable)
.withQuery(functionScoreQueryBuilder).build();
}
}
啟動專案,先呼叫http://localhost:8888/save方法,插入幾條資料,然後去es管理頁面http://localhost:9200/_plugin/head/,如下圖