SpringBoot整合elasticsearch

在這一篇文章開始以前,你須要先安裝一個ElasticSearch,若是你是mac或者linux能夠參考www.jianshu.com/p/e47b45137…,若是是windows能夠自定百度一下。java

下面是官方套話介紹elasticsearch:node

ElasticSearch是一個基於Lucene的搜索服務器。它提供了一個分佈式多用戶能力的全文搜索引擎,基於RESTful web接口。Elasticsearch是用Java開發的,並做爲Apache許可條款下的開放源碼發佈,是當前流行的企業級搜索引擎。設計用於雲計算中,可以達到實時搜索,穩定,可靠,快速,安裝使用方便。 咱們創建一個網站或應用程序,並要添加搜索功能,可是想要完成搜索工做的建立是很是困難的。咱們但願搜索解決方案要運行速度快,咱們但願能有一個零配置和一個徹底免費的搜索模式,咱們但願可以簡單地使用JSON經過HTTP來索引數據,咱們但願咱們的搜索服務器始終可用,咱們但願可以從一臺開始並擴展到數百臺,咱們要實時搜索,咱們要簡單的多租戶,咱們但願創建一個雲的解決方案。所以咱們利用Elasticsearch來解決全部這些問題及可能出現的更多其它問題。linux

具體elasticsearch相關問題能夠去elastic中文社區查看。git

這一篇文章將介紹springboot如何簡單整合elasticsearch。web

1.啓動elasticsearch。
2.新建項目,pom文件中加入elasticsearch依賴,完整pom以下:spring

<?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:類型 能夠理解爲表名apache

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 yangyang@dalaoyang.cn
 * @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,代碼以下:windows

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 yangyang@dalaoyang.cn
 * @date 2018/5/4
 */
@Component
public interface GoodsRepository extends ElasticsearchRepository<GoodsInfo,Long> {
}
複製代碼

最後新建一個controller進行測試,其中包含簡單的增刪改查以及一個搜索,增刪改查這裏不作解釋了。須要注意es的第一頁頁碼是0springboot

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 yangyang@dalaoyang.cn
 * @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/,以下圖

訪問http://localhost:8888/getGoodsList?query=商品,如圖:

源碼下載 :大老楊碼雲

我的網站:www.dalaoyang.cn

相關文章
相關標籤/搜索