Elasticsearch springboot整合ES

起因:在項(xiàng)目開(kāi)發(fā)過(guò)程中憎兽,要使用到搜索 引擎來(lái)對(duì)一些關(guān)鍵字實(shí)現(xiàn)逆向查詢(xún)撑蚌,如果僅用模糊搜索,那么搜索的時(shí)間會(huì)根據(jù)數(shù)據(jù)量的增大而增大刽肠,對(duì)比之下就學(xué)了elasticsearch溃肪,也記錄一下,常骋粑澹回顧惫撰。


1. Springboot整合Elasticsearch進(jìn)行索引操作

POM中增加依賴(lài)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

yaml配置

# 端口一定要9300
spring:
  data:
    elasticsearch:
      cluster-name: icoding-es
      cluster-nodes: 47.92.163.109:9300

創(chuàng)建映射的po

package com.icodingedu.po;

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;

//indexName相當(dāng)于給索引明名
//type相當(dāng)于文檔類(lèi)型
@Data
@Document(indexName = "index_user",type = "_doc",shards = 3,replicas = 1)
public class UserBo {
    //index的doc的id和數(shù)據(jù)的id一致
    @Id
    private String id;

    //默認(rèn)不是存儲(chǔ)節(jié)點(diǎn),要聲明
    @Field(store = true,index = true,analyzer = "ik_max_word",searchAnalyzer = "ik_max_word")
    private String nickname;

    @Field(store = true)
    private Integer sex;

    @Field(store = true)
    private Double consume;

    @Field(store = true,index = true,analyzer = "ik_max_word",searchAnalyzer = "ik_max_word")
    private String review;
}

創(chuàng)建索引的controller

package com.icodingedu.controller;

import com.icodingedu.po.UserBo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ESUserController {

    @Autowired
    ElasticsearchTemplate elasticsearchTemplate;

    @GetMapping("/create_index")
    @ResponseBody
    public String createIndex(){
        UserBo userBo = new UserBo();
        userBo.setId("1001");
        userBo.setConsume(1899.66);
        userBo.setNickname("空中雄鷹");
        userBo.setReview("icoding edu 艾編程課程非常不錯(cuò)躺涝,學(xué)起來(lái)很給力");
        userBo.setSex(1);

        IndexQuery indexQuery = new IndexQueryBuilder()
                .withObject(userBo)
                .build();
        elasticsearchTemplate.index(indexQuery);
        return "index/mapping/document 一起創(chuàng)建完成";
    }
}

更新索引的mapping

// 只需要在po里加上字段既可以
// 創(chuàng)建的時(shí)候給賦值
// 更新的時(shí)候elasticsearchTemplate會(huì)根據(jù)po的變化判斷是否更新
// 在elasticsearchTemplate.index(indexQuery)操作時(shí)如果沒(méi)有index則新建厨钻,如果有就創(chuàng)建數(shù)據(jù)

刪除index

@GetMapping("/delete-index")
@ResponseBody
public String deleteIndex(){
  elasticsearchTemplate.deleteIndex(UserBo.class);
  return "刪除成功";
}

ElasticsearchTemplate一般用于對(duì)文檔數(shù)據(jù)進(jìn)行檢索應(yīng)用

  • 對(duì)于index的mapping還是使用json來(lái)創(chuàng)建
  • ET的部分注解不一定生效

2. Springboot對(duì)ES文檔進(jìn)行操作

更新document

    @GetMapping("/update")
    @ResponseBody
    public String updateIndex(){

        Map<String,Object> data = new HashMap<String,Object>();
        data.put("username","jackwang");
        data.put("consume",7888.99);

        IndexRequest indexRequest = new IndexRequest();
        indexRequest.source(data);

        UpdateQuery updateQuery = new UpdateQueryBuilder()
                .withClass(UserBo.class)
                .withId("1001")
                .withIndexRequest(indexRequest)
                .build();

        elasticsearchTemplate.update(updateQuery);
        return "更新成功";
    }

刪除document

    @GetMapping("/delete/{id}")
    @ResponseBody
    public String deleteDocument(@PathVariable("id") String uid){
        elasticsearchTemplate.delete(UserBo.class,uid);
        return "刪除id:"+uid;
    }

根據(jù)id獲得doc數(shù)據(jù)

    @GetMapping("/get/{id}")
    @ResponseBody
    public String getIndex(@PathVariable("id") String uid){

        GetQuery query = new GetQuery();
        query.setId(uid);

        UserBo userBo = elasticsearchTemplate.queryForObject(query,UserBo.class);
        return userBo.toString();
    }

3. Springboot對(duì)ES文檔進(jìn)行分頁(yè)查詢(xún)

// ES中已有的index映射對(duì)象
package com.icodingedu.po;

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;

@Data
@Document(indexName = "index_customer",type = "_doc")
public class CustomerPo {
    @Id
    private String id;

    @Field(store=true)
    private Integer age;

    @Field(store=true)
    private String username;

    @Field(store=true)
    private String nickname;
    @Field(store=true)
    private Float consume;

    @Field(store=true)
    private String desc;

    @Field(store=true)
    private Integer sex;

    @Field(store=true)
    private String birthday;

    @Field(store=true)
    private String city;

    @Field(store=true)
    private String faceimg;
}

查詢(xún)分頁(yè)的controller

    @GetMapping("/list")
    @ResponseBody
    public String getList(){
        //3.定義分頁(yè)
        Pageable pageable = PageRequest.of(0,2);
        //2.定義query對(duì)象
        SearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery("desc","艾編程 學(xué)習(xí)"))
                .withPageable(pageable)
                .build();
        //1.先寫(xiě)查詢(xún)
        AggregatedPage<CustomerPo> customerPos = elasticsearchTemplate.queryForPage(query,CustomerPo.class);
        System.out.println("總頁(yè)數(shù):"+customerPos.getTotalPages());
        System.out.println("總記錄數(shù):"+customerPos.getTotalElements());
        List<CustomerPo> customerPoList = customerPos.getContent();
        for (CustomerPo customerPo:customerPoList) {
            System.out.println(customerPo.toString());

        }
        return "查詢(xún)完成";
    }

4. Springboot對(duì)ES文檔實(shí)現(xiàn)高亮查詢(xún)

//目前已加入高亮的字符,但會(huì)報(bào)錯(cuò)坚嗜,無(wú)法獲得值
    @GetMapping("/listhiglight")
    @ResponseBody
    public String getListHighLight(){
        //4.定義高亮的字符
        String preTag = "<font color='red'>";
        String postTag = "</font>";
        //3.定義分頁(yè)
        Pageable pageable = PageRequest.of(0,2);
        //2.定義query對(duì)象
        SearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery("desc","艾編程 學(xué)習(xí)"))
                .withHighlightFields(new HighlightBuilder.Field("desc").preTags(preTag).postTags(postTag))
                .withPageable(pageable)
                .build();
        //1.先寫(xiě)查詢(xún),參數(shù)里增加高亮的實(shí)現(xiàn)
        AggregatedPage<CustomerPo> customerPos = elasticsearchTemplate.queryForPage(query, CustomerPo.class, new SearchResultMapper() {
            @Override
            public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                return null;
            }

            @Override
            public <T> T mapSearchHit(SearchHit searchHit, Class<T> aClass) {
                return null;
            }
        });
        System.out.println("總頁(yè)數(shù):"+customerPos.getTotalPages());
        System.out.println("總記錄數(shù):"+customerPos.getTotalElements());
        List<CustomerPo> customerPoList = customerPos.getContent();
        for (CustomerPo customerPo:customerPoList) {
            System.out.println(customerPo.toString());

        }
        return "查詢(xún)完成";
    }

實(shí)現(xiàn)高亮完整代碼

    @GetMapping("/listhiglight")
    @ResponseBody
    public String getListHighLight(){
        //4.定義高亮的字符
        String preTag = "<font color='red'>";
        String postTag = "</font>";
        //3.定義分頁(yè)
        Pageable pageable = PageRequest.of(0,2);
        //2.定義query對(duì)象
        SearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery("desc","艾編程 學(xué)習(xí)"))
                .withHighlightFields(new HighlightBuilder.Field("desc").preTags(preTag).postTags(postTag))
                .withPageable(pageable)
                .build();
        //1.先寫(xiě)查詢(xún),參數(shù)里增加高亮的實(shí)現(xiàn)
        AggregatedPage<CustomerPo> customerPos = elasticsearchTemplate.queryForPage(query, CustomerPo.class, new SearchResultMapper() {
            @Override
            public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                List<CustomerPo> customerPoList = new ArrayList<CustomerPo>();
                SearchHits searchHits = searchResponse.getHits();
                for (SearchHit h: searchHits) {
                    HighlightField highlightField = h.getHighlightFields().get("desc");
                    String desc = highlightField.fragments()[0].toString();
                    CustomerPo customerPoHighlight = new CustomerPo();
                    customerPoHighlight.setAge((Integer)h.getSourceAsMap().get("age"));
                    customerPoHighlight.setBirthday(h.getSourceAsMap().get("birthday").toString());
                    customerPoHighlight.setCity(h.getSourceAsMap().get("city").toString());
                    customerPoHighlight.setConsume(Float.valueOf(h.getSourceAsMap().get("consume").toString()));
                    customerPoHighlight.setDesc(desc);//這就是把高亮的字段替換給原字段
                    customerPoHighlight.setFaceimg(h.getSourceAsMap().get("faceimg").toString());
                    customerPoHighlight.setId(h.getSourceAsMap().get("id").toString());
                    customerPoHighlight.setNickname(h.getSourceAsMap().get("nickname").toString());
                    customerPoHighlight.setSex((Integer)h.getSourceAsMap().get("sex"));
                    customerPoHighlight.setUsername(h.getSourceAsMap().get("username").toString());
                    customerPoList.add(customerPoHighlight);
                }
                if(customerPoList.size()>0){
                    return new AggregatedPageImpl<>((List<T>) customerPoList);
                }
                return null;
            }

            @Override
            public <T> T mapSearchHit(SearchHit searchHit, Class<T> aClass) {
                return null;
            }
        });
        System.out.println("總頁(yè)數(shù):"+customerPos.getTotalPages());
        System.out.println("總記錄數(shù):"+customerPos.getTotalElements());
        List<CustomerPo> customerPoList = customerPos.getContent();
        for (CustomerPo customerPo:customerPoList) {
            System.out.println(customerPo.toString());

        }
        return "查詢(xún)完成";
    }

5. Springboot對(duì)ES文檔進(jìn)行數(shù)據(jù)排序

只需要加入排序的構(gòu)建就ok了

    @GetMapping("/list")
    @ResponseBody
    public String getList(){
        //4.加入排序構(gòu)建
        SortBuilder sortBuilder1 = new FieldSortBuilder("consume")
                .order(SortOrder.DESC);
        SortBuilder sortBuilder2 = new FieldSortBuilder("age")
                .order(SortOrder.ASC);

        //3.定義分頁(yè)
        Pageable pageable = PageRequest.of(0,6);
        //2.定義query對(duì)象
        SearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery("desc","學(xué)習(xí)"))
                .withPageable(pageable)
                .withSort(sortBuilder1)
                .withSort(sortBuilder2)
                .build();
        //1.先寫(xiě)查詢(xún)
        AggregatedPage<CustomerPo> customerPos = elasticsearchTemplate.queryForPage(query,CustomerPo.class);
        System.out.println("總頁(yè)數(shù):"+customerPos.getTotalPages());
        System.out.println("總記錄數(shù):"+customerPos.getTotalElements());
        List<CustomerPo> customerPoList = customerPos.getContent();
        for (CustomerPo customerPo:customerPoList) {
            System.out.println(customerPo.toString());

        }
        return "查詢(xún)完成";
    }

不要以為每天把功能完成了就行了夯膀,這種思想是要不得的,互勉~苍蔬!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末诱建,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子碟绑,更是在濱河造成了極大的恐慌俺猿,老刑警劉巖茎匠,帶你破解...
    沈念sama閱讀 206,723評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異押袍,居然都是意外死亡诵冒,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,485評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門(mén)谊惭,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)造烁,“玉大人,你說(shuō)我怎么就攤上這事午笛〔洋” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 152,998評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵药磺,是天一觀的道長(zhǎng)告组。 經(jīng)常有香客問(wèn)我,道長(zhǎng)癌佩,這世上最難降的妖魔是什么木缝? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,323評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮围辙,結(jié)果婚禮上我碟,老公的妹妹穿的比我還像新娘。我一直安慰自己姚建,他們只是感情好矫俺,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,355評(píng)論 5 374
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著掸冤,像睡著了一般厘托。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上稿湿,一...
    開(kāi)封第一講書(shū)人閱讀 49,079評(píng)論 1 285
  • 那天铅匹,我揣著相機(jī)與錄音,去河邊找鬼饺藤。 笑死包斑,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的涕俗。 我是一名探鬼主播罗丰,決...
    沈念sama閱讀 38,389評(píng)論 3 400
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼咽袜!你這毒婦竟也來(lái)了丸卷?” 一聲冷哼從身側(cè)響起枕稀,我...
    開(kāi)封第一講書(shū)人閱讀 37,019評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤询刹,失蹤者是張志新(化名)和其女友劉穎谜嫉,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體凹联,經(jīng)...
    沈念sama閱讀 43,519評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡沐兰,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,971評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了蔽挠。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片住闯。...
    茶點(diǎn)故事閱讀 38,100評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖澳淑,靈堂內(nèi)的尸體忽然破棺而出比原,到底是詐尸還是另有隱情,我是刑警寧澤杠巡,帶...
    沈念sama閱讀 33,738評(píng)論 4 324
  • 正文 年R本政府宣布量窘,位于F島的核電站,受9級(jí)特大地震影響氢拥,放射性物質(zhì)發(fā)生泄漏蚌铜。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,293評(píng)論 3 307
  • 文/蒙蒙 一嫩海、第九天 我趴在偏房一處隱蔽的房頂上張望冬殃。 院中可真熱鬧,春花似錦叁怪、人聲如沸审葬。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,289評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)耳璧。三九已至,卻和暖如春展箱,著一層夾襖步出監(jiān)牢的瞬間旨枯,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,517評(píng)論 1 262
  • 我被黑心中介騙來(lái)泰國(guó)打工混驰, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留攀隔,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,547評(píng)論 2 354
  • 正文 我出身青樓栖榨,卻偏偏與公主長(zhǎng)得像昆汹,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子婴栽,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,834評(píng)論 2 345