六、spring boot 集成elasticsearch

1. 新增依赖

我本地使用的spring boot版本为1.5.8.RELEASE

compile("org.springframework.boot:spring-boot-starter-data-elasticsearch")

2. 新增配置

application.yml新增关于es的一些配置

# elasticsearch
spring:
    data:
        elasticsearch:
            cluster-name: elasticsearch
            cluster-nodes: 127.0.0.1:9300

3. 新增model

package com.mk.model;

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.FieldIndex;
import org.springframework.data.elasticsearch.annotations.FieldType;

import java.util.Date;

@Document(indexName = "mk_spring_es", type = "article", shards = 1, replicas = 0, refreshInterval = "-1")
public class ArticleInfo {

    @Id
    private String id;

    @Field(type = FieldType.String, store = true, analyzer = "ik", index = FieldIndex.analyzed)
    private String articleAuthor;

    @Field(type = FieldType.String, store = true, analyzer = "ik", index = FieldIndex.analyzed)
    private String articleTitle;

    @Field(type = FieldType.String, store = true, analyzer = "ik", index = FieldIndex.analyzed)
    private String articleContent;

    @Field
    private Date createTime;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getArticleAuthor() {
        return articleAuthor;
    }

    public void setArticleAuthor(String articleAuthor) {
        this.articleAuthor = articleAuthor;
    }

    public String getArticleTitle() {
        return articleTitle;
    }

    public void setArticleTitle(String articleTitle) {
        this.articleTitle = articleTitle;
    }

    public String getArticleContent() {
        return articleContent;
    }

    public void setArticleContent(String articleContent) {
        this.articleContent = articleContent;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ArticleInfo that = (ArticleInfo) o;

        if (id != null ? !id.equals(that.id) : that.id != null) return false;
        if (articleAuthor != null ? !articleAuthor.equals(that.articleAuthor) : that.articleAuthor != null)
            return false;
        if (articleTitle != null ? !articleTitle.equals(that.articleTitle) : that.articleTitle != null) return false;
        if (articleContent != null ? !articleContent.equals(that.articleContent) : that.articleContent != null)
            return false;
        return createTime != null ? createTime.equals(that.createTime) : that.createTime == null;
    }

    @Override
    public int hashCode() {
        int result = id != null ? id.hashCode() : 0;
        result = 31 * result + (articleAuthor != null ? articleAuthor.hashCode() : 0);
        result = 31 * result + (articleTitle != null ? articleTitle.hashCode() : 0);
        result = 31 * result + (articleContent != null ? articleContent.hashCode() : 0);
        result = 31 * result + (createTime != null ? createTime.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "ArticleInfo{" +
                "id='" + id + '\'' +
                ", articleAuthor='" + articleAuthor + '\'' +
                ", articleTitle='" + articleTitle + '\'' +
                ", articleContent='" + articleContent + '\'' +
                ", createTime=" + createTime +
                '}';
    }
}

4. 新增dao

package com.mk.dao;

import com.mk.model.ArticleInfo;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;

@Component("elasticsearchArticleDao")
public interface ElasticsearchArticleDao extends ElasticsearchRepository<ArticleInfo, String> {

}

5. 新增service

package com.mk.service;

import com.mk.entity.Page;
import com.mk.model.ArticleInfo;

import java.util.List;

public interface ElasticsearchArticleService {

    void createMapping() throws Exception;

    // 保存一条数据
    void saveArticle(ArticleInfo info);

    // 保存多条数据
    void saveArticles(List<ArticleInfo> list);

    // 根据ID获取文章
    ArticleInfo findArticleInfoById(String id);

    // 根据关键字查询
    List<ArticleInfo> findAllArticle();

    // 根据关键字查询
    List<ArticleInfo> findArticleByKeyword(String keyword);

    // 根据关键字查询(分页)
    Page<ArticleInfo> findArticleByKeywordWithPage(String keyword, int pageNo, int pageSize);
}

6. 新增service实现

package com.mk.service.impl;

import com.mk.dao.ElasticsearchArticleDao;
import com.mk.entity.Page;
import com.mk.model.ArticleInfo;
import com.mk.service.ElasticsearchArticleService;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("elasticsearchArticleService")
public class ElasticsearchArticleServiceImpl implements ElasticsearchArticleService{

    private static final Logger logger = LoggerFactory.getLogger(ElasticsearchArticleServiceImpl.class);


    @Resource
    private ElasticsearchArticleDao elasticsearchArticleDao;

    @Resource
    private ElasticsearchTemplate elasticsearchTemplate;

    @Override
    public void createMapping() throws Exception{
        String index = "mk_spring_es";
        String type = "article";
        elasticsearchTemplate.getClient().admin().indices().prepareCreate(index).execute().actionGet();
        XContentBuilder builder= XContentFactory.jsonBuilder()
                .startObject()
                .startObject(type)
                .startObject("properties")
                .startObject("articleTitle").field("type", "string").field("store", "yes").field("analyzer","ik").field("index","analyzed").endObject()
                .startObject("articleContent").field("type", "string").field("store", "yes").field("analyzer","ik").field("index","analyzed").endObject()
                .endObject()
                .endObject()
                .endObject();
        PutMappingRequest mapping = Requests.putMappingRequest(index).type(type).source(builder);
        elasticsearchTemplate.getClient().admin().indices().putMapping(mapping).actionGet();

    }

    @Override
    public void saveArticle(ArticleInfo info) {
        info.setCreateTime(new Date());
        elasticsearchArticleDao.save(info);
    }

    @Override
    public void saveArticles(List<ArticleInfo> list) {
        for (ArticleInfo info : list) {
            info.setCreateTime(new Date());
        }
        elasticsearchArticleDao.save(list);
    }

    @Override
    public ArticleInfo findArticleInfoById(String id) {
        return elasticsearchArticleDao.findOne(id);
    }

    @Override
    public List<ArticleInfo> findAllArticle() {
        Iterable<ArticleInfo> iterable = elasticsearchArticleDao.search(QueryBuilders.matchAllQuery());
        List<ArticleInfo> list = new ArrayList<>();
        if(iterable != null){
            iterable.forEach(list::add);
        }
        return list;
    }

    @Override
    public List<ArticleInfo> findArticleByKeyword(String keyword) {
        logger.info("query by keyword:{}",keyword);
        HighlightBuilder.Field field = new HighlightBuilder.Field("articleTitle");
        field.preTags("<span>");
        field.postTags("</span>");
        HighlightBuilder.Field[] fields = {field};
        QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(keyword, "articleAuthor", "articleTitle", "articleContent");
        SortBuilder sortBuilder = new FieldSortBuilder("createTime");
        sortBuilder.order(SortOrder.DESC);
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder)
                .withHighlightFields(fields)
                .withSort(sortBuilder)
                .build();
        List<ArticleInfo> list = new ArrayList<>();
        Iterable<ArticleInfo> iterable = elasticsearchArticleDao.search(searchQuery);
        if(iterable != null){
            iterable.forEach(list::add);
        }
        return list;
    }

    @Override
    public Page<ArticleInfo> findArticleByKeywordWithPage(String keyword, int pageNo, int pageSize) {
        Page<ArticleInfo> result = new Page<>();
        result.setPageNo(pageNo);
        result.setPageSize(pageSize);
        // 查询
        QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(keyword, "articleAuthor", "articleTitle", "articleContent");
        // 分页
        Pageable pageable = new PageRequest(pageNo-1, pageSize);
        // 排序
        SortBuilder sortBuilder = new FieldSortBuilder("createTime");
        sortBuilder.order(SortOrder.DESC);
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder)
                .withPageable(pageable)
                .withSort(sortBuilder)
                .build();
        org.springframework.data.domain.Page<ArticleInfo> queryResult = elasticsearchArticleDao.search(searchQuery);
        if(queryResult.getTotalElements() > 0){
            List<ArticleInfo> list = new ArrayList<>();
            queryResult.forEach(list::add);
            result.setTotal(Long.valueOf(queryResult.getTotalElements()).intValue());
            result.setList(list);
        }
        return result;
    }
}

7. 新增controller

package com.mk.controller;

import com.mk.entity.Page;
import com.mk.entity.Response;
import com.mk.model.ArticleInfo;
import com.mk.model.User;
import com.mk.service.ElasticsearchArticleService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private ElasticsearchArticleService elasticsearchArticleService;

    @ApiOperation(value = "创建mapping",notes = "创建mapping")
    @RequestMapping(value = "/createMapping",method = {RequestMethod.GET})
    public Response createMapping(){
        Response response = new Response();
        try {
            elasticsearchArticleService.createMapping();
        } catch (Exception e){
            response.setResult(false);
            response.setMessage(e.getMessage());
        }
        return response;
    }

    @ApiOperation(value = "保存一篇文章",notes = "保存一篇文章")
    @ApiImplicitParam(name = "articleInfo",value = "文章信息", required = true, dataType = "ArticleInfo")
    @RequestMapping(value = "/save",method = {RequestMethod.GET,RequestMethod.POST})
    public Response save(@ModelAttribute ArticleInfo articleInfo){
        Response response = new Response();
        try {
            elasticsearchArticleService.saveArticle(articleInfo);
        } catch (Exception e){
            response.setResult(false);
            response.setMessage(e.getMessage());
        }
        return response;
    }

    @ApiOperation(value = "根据ID查询一篇文章",notes = "根据ID查询一篇文章")
    @ApiImplicitParam(name = "id",value = "文章id", required = true, dataType = "String")
    @RequestMapping(value = "/findById",method = {RequestMethod.GET})
    public Response findById(@RequestParam String id){
        Response<ArticleInfo> response = new Response<>();
        try {
            ArticleInfo info = elasticsearchArticleService.findArticleInfoById(id);
            response.setData(info);
        } catch (Exception e){
            response.setResult(false);
            response.setMessage(e.getMessage());
        }
        return response;
    }

    @ApiOperation(value = "查询所有文章",notes = "查询所有文章")
    @RequestMapping(value = "/findAll",method = {RequestMethod.GET})
    public Response findAll(){
        Response<List> response = new Response<>();
        try {
            List<ArticleInfo> list = elasticsearchArticleService.findAllArticle();
            response.setData(list);
        } catch (Exception e){
            response.setResult(false);
            response.setMessage(e.getMessage());
        }
        return response;
    }

    @ApiOperation(value = "根据关键字查询文章",notes = "根据关键字查询文章")
    @ApiImplicitParam(name = "keyword",value = "关键字", required = true, dataType = "String")
    @RequestMapping(value = "/findByKeyword",method = {RequestMethod.GET})
    public Response findByKeyword(@RequestParam String keyword){
        Response<List> response = new Response<>();
        try {
            List<ArticleInfo> list = elasticsearchArticleService.findArticleByKeyword(keyword);
            response.setData(list);
        } catch (Exception e){
            response.setResult(false);
            response.setMessage(e.getMessage());
        }
        return response;
    }

    @ApiOperation(value = "根据关键字查询文章(带分页)",notes = "根据关键字查询文章(带分页)")
    @ApiImplicitParam(name = "keyword",value = "关键字", required = true, dataType = "String")
    @RequestMapping(value = "/findByKeywordWithPage",method = {RequestMethod.GET})
    public Response findByKeywordWithPage(@RequestParam("keyword") String keyword,
                                          @RequestParam("pageNo") int pageNo,
                                          @RequestParam("pageSize") int pageSize){
        Response<Page> response = new Response<>();
        try {
            Page<ArticleInfo> list = elasticsearchArticleService.findArticleByKeywordWithPage(keyword,pageNo,pageSize);
            response.setData(list);
        } catch (Exception e){
            response.setResult(false);
            response.setMessage(e.getMessage());
        }
        return response;
    }
}

8. 测试

  • save
save
  • findById
findById
  • findByKeywordWithPage
findByKeywordWithPage
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,711评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,079评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,194评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,089评论 1 286
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,197评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,306评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,338评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,119评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,541评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,846评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,014评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,694评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,322评论 3 318
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,026评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,257评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,863评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,895评论 2 351