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

elasticsearch

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

            org.springframework.boot
            spring-boot-starter-data-elasticsearch
        
实现效果:
Spring Boot+Elasticsearch实现简单全文搜索_第1张图片
微信截图_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{
    Page findByTitleLikeOrContentLike(String title, String content, Pageable pageable);
    Page 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 extends ElasticsearchCrudRepository {
     S index(S var1);

    Iterable search(QueryBuilder var1);

    Page search(QueryBuilder var1, Pageable var2);

    Page search(SearchQuery var1);

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

    void refresh();

    Class 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 search(String title, String content, Pageable pageable);

   //基于content进行搜索,返回分页
   Page search(String content,Pageable pageable);

   //返回所有数据集合
   Page 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.
 */

@Service
public class PoemServiceImpl implements PoemService{

    @Autowired
    private PoemRepository poemRepository;

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

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

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

    @Override
    public Page 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 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 = poemService.findAll(pageable);
        List 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 poems = poemService.search(content,pageable);
        List 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 poems = poemService.search(content,pageable);
                List 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

你可能感兴趣的:(Spring Boot+Elasticsearch实现简单全文搜索)