Spring Boot+Elasticsearch實現(xiàn)簡單全文搜索

elasticsearch

ElasticSearch是一個基于Lucene的搜索服務器颁独。它提供了一個分布式多用戶能力的全文搜索引擎彩届,基于RESTful web接口。Elasticsearch是用Java開發(fā)的誓酒,并作為Apache許可條款下的開放源碼發(fā)布樟蠕,是當前流行的企業(yè)級搜索引擎。設計用于[云計算]中靠柑,能夠達到實時搜索寨辩,穩(wěn)定,可靠歼冰,快速靡狞,安裝使用方便。
spring boot操作elasticsearch需要通過spring data elasticsearch來實現(xiàn)
添加依賴:
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
實現(xiàn)效果:
微信截圖_20180521120057.png

實體類:

package com.example.demo.entity;

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;



/**
 * Created by linziyu on 2018/5/19.
 * 實體類
 *
 *
 */
//定義索引名字及類型
@Document(indexName = "poem",type = "poem",shards = 1, replicas = 0)
public class Poem {

    @Id
    private long id;
    private String title;
    private String content;

    public Poem(long id, String title, String content) {
        this.id = id;
        this.title = title;
        this.content = content;
    }

    public Poem(String title, String content) {
        this.title = title;
        this.content = content;
    }

    public Poem() {
    }

    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 getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

dao層
package com.example.demo.repository;

import com.example.demo.entity.Poem;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

/**
 * Created by linziyu on 2018/5/19.
 * dao層
 *
 */
public interface PoemRepository extends ElasticsearchRepository<Poem,Long>{
    Page<Poem> findByTitleLikeOrContentLike(String title, String content, Pageable pageable);
    Page<Poem> findByContentLike(String content,Pageable pageable);

}

只需要繼承ElasticsearchRepository即可隔嫡,與JpaRepository相似甸怕,里面封裝好了基本的CRUD操作方法。

ElasticsearchRepository源碼:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.data.elasticsearch.repository;

import java.io.Serializable;
import org.elasticsearch.index.query.QueryBuilder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository;
import org.springframework.data.repository.NoRepositoryBean;

@NoRepositoryBean
public interface ElasticsearchRepository<T, ID extends Serializable> extends ElasticsearchCrudRepository<T, ID> {
    <S extends T> S index(S var1);

    Iterable<T> search(QueryBuilder var1);

    Page<T> search(QueryBuilder var1, Pageable var2);

    Page<T> search(SearchQuery var1);

    Page<T> searchSimilar(T var1, String[] var2, Pageable var3);

    void refresh();

    Class<T> getEntityClass();
}

業(yè)務邏輯接口:


package com.example.demo.service;

import com.example.demo.entity.Poem;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

/**
 * Created by linziyu on 2018/5/19.
 * 業(yè)務邏輯
 *
 */
public interface PoemService {
   //保存Poem實體
   void save (Poem poem);

   //基于title和content進行搜索腮恩,返回分頁
   Page<Poem> search(String title, String content, Pageable pageable);

   //基于content進行搜索梢杭,返回分頁
   Page<Poem> search(String content,Pageable pageable);

   //返回所有數(shù)據(jù)集合
   Page<Poem> findAll(Pageable pageable);
}

業(yè)務邏輯實現(xiàn)類:


package com.example.demo.service;

import com.example.demo.entity.Poem;
import com.example.demo.repository.PoemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

/**
 * Created by linziyu on 2018/5/19.
 */

@Service
public class PoemServiceImpl implements PoemService{

    @Autowired
    private PoemRepository poemRepository;

    @Override
    public void save(Poem poem) {
        poemRepository.save(poem);
    }

    @Override
    public Page<Poem> search(String title, String content, Pageable pageable) {
        return poemRepository.findByTitleLikeOrContentLike(title,content,pageable);
    }

    @Override
    public Page<Poem> search(String content, Pageable pageable) {
        return poemRepository.findByContentLike(content,pageable);
    }

    @Override
    public Page<Poem> findAll(Pageable pageable) {
        return poemRepository.findAll(pageable);
    }
}

Controller層:

package com.example.demo.controller;

import com.example.demo.entity.Poem;
import com.example.demo.service.PoemServiceImpl;
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.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by linziyu on 2018/5/19.
 * 控制層
 *
 */

@Controller
public class WebController {
    @Autowired
    private PoemServiceImpl poemService;

//    @RequestMapping("/")
//    public String index(){
//        List<Poem> poems = new ArrayList<>();
//        poems.add(new Poem(4,"湘春夜月·近清明","近清明,翠禽枝上消魂,可惜一片清歌,都付與黃昏庆揪。欲共柳花低訴式曲,怕柳花輕薄,不解傷春缸榛。念楚鄉(xiāng)旅宿吝羞,柔情別緒,誰與溫存内颗。"));
//        poems.add(new Poem(5,"卜算子·不是愛風塵","不是愛風塵钧排,似被前緣誤【模花落花開自有時恨溜,總賴東君主。\n" +
//                "去也終須去找前,住也如何自阍!若得山花插滿頭躺盛,莫問奴歸處"));
//        poems.add(new Poem(6,"御街行·秋日懷舊","紛紛墜葉飄香砌项戴。夜寂靜,寒聲碎槽惫。真珠簾卷玉樓空周叮,天淡銀河垂地辩撑。年年今夜,月華如練仿耽,長是人千里合冀。"));
//
//        for(int i=0;i<poems.size();i++){
//            poemService.save(poems.get(i));
//        }
//
//
//        return "/index";
//
//    }

    @RequestMapping("/tt")
    public String index1(
                       @RequestParam(value="pageIndex",required=false,defaultValue="0") int pageIndex,
                       @RequestParam(value="pageSize",required=false,defaultValue="10") int pageSize,
    Model model) {
        Pageable pageable = new PageRequest(pageIndex,pageSize);
        Page<Poem> poems = poemService.findAll(pageable);
        List<Poem> poems1 = poems.getContent();
        model.addAttribute("poems",poems);
        return "/index";
    }

    @RequestMapping("/t")
    public String index2(@RequestParam(value="content",required=false,defaultValue="香") String content,
                         @RequestParam(value="pageIndex",required=false,defaultValue="0") int pageIndex,
                         @RequestParam(value="pageSize",required=false,defaultValue="10") int pageSize,
                         Model model) {
        Pageable pageable = new PageRequest(pageIndex,pageSize);
        Page<Poem> poems = poemService.search(content,pageable);
        List<Poem> list = poems.getContent();
        model.addAttribute("poems",list);
        return "/t";
    }

    @RequestMapping("/search")
    public String search(String content, @RequestParam(value="pageIndex",required=false,defaultValue="0") int pageIndex,
                         @RequestParam(value="pageSize",required=false,defaultValue="10") int pageSize,Model model) {
                Pageable pageable = new PageRequest(pageIndex,pageSize);
                Page<Poem> poems = poemService.search(content,pageable);
                List<Poem> list = poems.getContent();
                model.addAttribute("poems",list);
                return "/list";

    }



}

配置文件:

#存儲索引的位置
#spring.data.elasticsearch.properties.path.home=target/elastic
#連接超時的時間
#server.port=8081
spring.data.elasticsearch.properties.transport.tcp.connect_timeout=120s
spring.data.elasticsearch.repositories.enabled=true

spring.data.elasticsearch.cluster-nodes=localhost:9300 //連接本地elasticsearch


運行整個Demo是需要先開啟本地的elasticsearch服務

整個Demo在我的GitHub:
https://github.com/LinZiYU1996/Spring-Boot-Elasticsearch/tree/master

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市项贺,隨后出現(xiàn)的幾起案子君躺,更是在濱河造成了極大的恐慌,老刑警劉巖敬扛,帶你破解...
    沈念sama閱讀 219,366評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件晰洒,死亡現(xiàn)場離奇詭異,居然都是意外死亡啥箭,警方通過查閱死者的電腦和手機谍珊,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,521評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來急侥,“玉大人砌滞,你說我怎么就攤上這事』倒郑” “怎么了贝润?”我有些...
    開封第一講書人閱讀 165,689評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長铝宵。 經(jīng)常有香客問我打掘,道長,這世上最難降的妖魔是什么鹏秋? 我笑而不...
    開封第一講書人閱讀 58,925評論 1 295
  • 正文 為了忘掉前任尊蚁,我火速辦了婚禮,結(jié)果婚禮上侣夷,老公的妹妹穿的比我還像新娘横朋。我一直安慰自己,他們只是感情好百拓,可當我...
    茶點故事閱讀 67,942評論 6 392
  • 文/花漫 我一把揭開白布琴锭。 她就那樣靜靜地躺著,像睡著了一般衙传。 火紅的嫁衣襯著肌膚如雪决帖。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,727評論 1 305
  • 那天蓖捶,我揣著相機與錄音古瓤,去河邊找鬼。 笑死,一個胖子當著我的面吹牛落君,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播亭引,決...
    沈念sama閱讀 40,447評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼绎速,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了焙蚓?” 一聲冷哼從身側(cè)響起纹冤,我...
    開封第一講書人閱讀 39,349評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎购公,沒想到半個月后萌京,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,820評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡宏浩,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,990評論 3 337
  • 正文 我和宋清朗相戀三年知残,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片比庄。...
    茶點故事閱讀 40,127評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡求妹,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出佳窑,到底是詐尸還是另有隱情制恍,我是刑警寧澤,帶...
    沈念sama閱讀 35,812評論 5 346
  • 正文 年R本政府宣布神凑,位于F島的核電站净神,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏溉委。R本人自食惡果不足惜鹃唯,卻給世界環(huán)境...
    茶點故事閱讀 41,471評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望薛躬。 院中可真熱鬧俯渤,春花似錦、人聲如沸型宝。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,017評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽趴酣。三九已至梨树,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間岖寞,已是汗流浹背抡四。 一陣腳步聲響...
    開封第一講書人閱讀 33,142評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人指巡。 一個月前我還...
    沈念sama閱讀 48,388評論 3 373
  • 正文 我出身青樓淑履,卻偏偏與公主長得像,于是被迫代替她去往敵國和親藻雪。 傳聞我的和親對象是個殘疾皇子秘噪,可洞房花燭夜當晚...
    茶點故事閱讀 45,066評論 2 355

推薦閱讀更多精彩內(nèi)容

  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,823評論 6 342
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn)勉耀,斷路器指煎,智...
    卡卡羅2017閱讀 134,667評論 18 139
  • 摘要: 原創(chuàng)出處 www.bysocket.com 「泥瓦匠BYSocket 」歡迎轉(zhuǎn)載至壤,保留摘要,謝謝枢纠! 『 預...
    子木聊出海閱讀 4,763評論 1 52
  • 讀經(jīng)時間: 2017年4月1日 星期六 晴 讀經(jīng)人員: 媽媽 讀經(jīng)內(nèi)容: 復習《易經(jīng)》63像街、64卦;《詩詞啟蒙...
    161d968e601f閱讀 131評論 0 0
  • 25年了,我依然沒有命中注定般 爬上那個關(guān)乎希望的山頂 我全知道京郑,你們有關(guān)天下一家的夢想 雖然我確實在想宅广,這可能嗎...
    一首詩和小H閱讀 201評論 0 0