为了账号安全,请及时绑定邮箱和手机立即绑定

Spring Boot+Elasticsearch实现简单全文搜索

标签:
SpringBoot

elasticsearch

ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于[云计算]中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。
spring boot操作elasticsearch需要通过spring data elasticsearch来实现
添加依赖:
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
实现效果:

webp

微信截图_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;@NoRepositoryBeanpublic 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();
}

业务逻辑接口:

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.
 * 业务逻辑
 *
 */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);   //返回所有数据集合
   Page<Poem> findAll(Pageable pageable);
}

业务逻辑实现类:

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.
 */@Servicepublic 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.
 * 控制层
 *
 */@Controllerpublic class WebController {    @Autowired
    private PoemServiceImpl poemService;//    @RequestMapping("/")//    public String index(){//        List<Poem> poems = new ArrayList<>();//        poems.add(new Poem(4,"湘春夜月·近清明","近清明,翠禽枝上消魂,可惜一片清歌,都付与黄昏。欲共柳花低诉,怕柳花轻薄,不解伤春。念楚乡旅宿,柔情别绪,谁与温存。"));//        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=8081spring.data.elasticsearch.properties.transport.tcp.connect_timeout=120s
spring.data.elasticsearch.repositories.enabled=truespring.data.elasticsearch.cluster-nodes=localhost:9300 //连接本地elasticsearch



作者:Cool_Pomelo
链接:https://www.jianshu.com/p/29944f3e9f95


点击查看更多内容
1人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消