springboot整合elasticsearch实现全文检索

硅谷探秘者 1335 0 0

版本说明,不同的springboot版本也对应着不同的elasticsearch版本,如果版本不对应客户端和服务端都会报相应的错误,对应关系请自行百度,本次测试的版本如下:springboot版本:2.3.1.RELEASE,elasticsearch版本:7.6.0

demo下载参考:springboot+elasticsearch  demo

开始前请阅读 : elasticsearch官方文档  

项目pom文件添加依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
application.yml配置文件
spring:
  elasticsearch:
    repositories: 
      enabled: true
    rest: 
      uris: 192.168.166.130:9200
    #cluster-nodes: 192.168.166.130:9300  #配置集群节点
    #cluster-name: my-application   #配置集群节点
创建索引库的实体类
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.util.Date;
@Data
@Accessors(chain = true)
@Document(indexName = "blog", type = "java")
public class BlogModel implements Serializable {
    private static final long serialVersionUID = 6320548148250372657L;
    @Id
    private Integer id;//id

    private String title;//标题

    private String content;//内容

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    private Date time;//时间
}
创建用于查询的接口

该接口的实现会帮你自动实现,你只要按照规则定义好方法就行。

定义方法请参考:官方文档

import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import java.util.List;

public interface BlogRepository extends ElasticsearchRepository<BlogModel, String> {

    BlogModel findTop1ById(String id);//根据id查询一条

    List<BlogModel> findByTitleLike(String keyword);//更具title模糊查询

    //根据title和content字段模糊查询
    List<BlogModel> findByTitleLikeOrContentLike(String title,String content);

    //查询分页
    List<BlogModel> findByTitleLikeOrContentLike(String title, String content, Pageable pageable);

    //查询分页 根据时间排序
    List<BlogModel> findByTitleLikeOrContentLikeOrderByTimeDesc(String title, String content, Pageable pageable);

    //查询分页 根据时间排序    
    List<BlogModel> findByTitleLikeOrContentLikeOrderByTimeAsc(String title, String content, Pageable pageable);
}
返回实体类
import lombok.Data;
@Data
public class Result<T> {
    private int code;
    private String message;
    private T data;
    public Result(int code,String message,T data){
        this.code=code;
        this.message=message;
        this.data=data;
    }
    public static <T> Result<T> ok(T data){
        return new Result<T>(0,null,data);
    }
    public static <T> Result<T> ok(T data,String message){
        return new Result<T>(0,message,data);
    }
    public static <T> Result<T> ok(String message){
        return new Result<T>(0,message,null);
    }
    public static <T> Result<T> err(String message){
        return new Result<T>(1,message,null);
    }
}
测试控制器
import com.elasticsearch.entity.Result;
import com.elasticsearch.model.BlogModel;
import com.elasticsearch.model.BlogRepository;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.List;
/**
 *  测试
 */
@RestController
public class SearchController {

    @Autowired
    private BlogRepository blogRepository;

    /**
     * 删除
     * @return
     */
    @RequestMapping("delete")
    public Result deleteAll(){
        blogRepository.deleteAll();
        return Result.ok("删除成功");
    }

    /**
     * 根据id进行查找
     * @param id
     * @return
     */
    @RequestMapping("selectById")
    public Result selectById(String id){
        BlogModel b=blogRepository.findTop1ById(id);
        return Result.ok(b);
    }

    /**
     * 根据id修改
     * @param id
     * @return
     */
    @RequestMapping("update")
    public Result update(String id){
        BlogModel b=blogRepository.findTop1ById(id);
        if(b!=null){
            b.setContent("我已经修改了");
            blogRepository.save(b);
        }
        return Result.ok(b,"修改成功");
    }

    /**
     * 多字段进行查找(方法1)
     * @param key
     * @return
     */
    @RequestMapping("test2")
    public Result test2(String key){
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.should(QueryBuilders.matchQuery("title",key));
        boolQueryBuilder.should(QueryBuilders.matchQuery("content",key));
        Page<BlogModel> page = blogRepository.search(boolQueryBuilder, PageRequest.of(0,10));
        return Result.ok(page.getContent());
    }

    /**
     * 多字段进行查找(方法1)
     * @param key
     * @return
     */
    @RequestMapping("test3")
    public Result test3(String key){
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.should(QueryBuilders.matchQuery("title",key));
        boolQueryBuilder.should(QueryBuilders.matchQuery("content",key));
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.field("content");
        highlightBuilder.preTags("<red>");
        highlightBuilder.postTags("</red>");
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withPageable(PageRequest.of(0,10)).withHighlightBuilder(highlightBuilder).withQuery(boolQueryBuilder).build();
        return Result.ok(null);
    }

    /**
     * 多字段进行查找(方法2)
     * @param key
     * @return
     */
    @RequestMapping("allLike")
    public Result allLike(String key){
        List<BlogModel> list = blogRepository.findByTitleLikeOrContentLike(key,key);
        return Result.ok(list);
    }

    /**
     * 多字段进行查找 并且分页(方法3)
     * @param key
     * @return
     */
    @RequestMapping("allLikePage")
    public Result allLikePage(String key,Integer page,Integer limit){
        //page 当前第几页(从0开始)
        //limit 限制行数
        List<BlogModel> list = blogRepository.findByTitleLikeOrContentLike(key,key,PageRequest.of(page,limit));
        return Result.ok(list);
    }

    /**
     * 多字段进行查找 并且分页 并且排序(方法3)
     * @param key
     * @return
     */
    @RequestMapping("allLikePageOrderBy")
    public Result allLikePageOrderBy(String key,Integer page,Integer limit,Boolean desc){
        if(desc){
            return Result.ok(blogRepository.findByTitleLikeOrContentLikeOrderByTimeDesc(key,key,PageRequest.of(page,limit)));
        }else{
            return Result.ok(blogRepository.findByTitleLikeOrContentLikeOrderByTimeAsc(key,key,PageRequest.of(page,limit)));
        }
    }

    /**
     * 插入数据
     * @param id
     * @param title
     * @param content
     * @return
     */
    @RequestMapping("insert")
    public Result insert(Integer id,String title,String content){
        blogRepository.save(new BlogModel().setId(id).setTitle(title).setContent(content).setTime(new Date()));
        return Result.ok("插入成功");
    }

    /**
     *  根据title查询
     * @param title
     * @return
     */
    @RequestMapping("selectByTitle")
    public Result selectByTitle(String title){
        List<BlogModel> list = blogRepository.findByTitleLike(title);
        return Result.ok(list);
    }

}

linux系统安装elasticsearch服务器      http://www.jiajiajia.club/blog/artical/AXnwhI/377


评论区
请写下您的评论...
暂无评论...
猜你喜欢
java框架 1378 springbootelasticsearch框架引demo配置说明参考:http://www.jiajiajia.club/blog/artical/Ja4t7X/378
框架 974 lucene依赖jardependencygroupIdorg.apache.lucene/groupIdartifactIdlucene-highlighter
工具 1664 流程分析图引库中是如何存储的?数据库的一行数据会存储为一个document对象,一条记录的一列会存储为一个field,不会将数据库的所有数据都存储到引库。引是如何创建过程流程图1.分析
框架 2555 springbootmybatis1.创建maven项目2.sql件SETNAMESutf8mb4;SETFOREIGN_KEY_CHECKS=0
框架 2663 1.配置springboot支持websocketpackagecom.example.demo.websocket
其他 1240 一、表格 省 简称 省市 河北 冀A 河北石家庄 河北 冀B 河北唐山 河北 冀C 河北秦皇岛 河北 冀D 河北邯郸 河北 冀E 河北邢台 河北 冀F 河北保定 河北 冀G 河北张家口 河北 冀H 河北承德 河北 冀J 河北沧州 河北 冀R 河北廊坊 河北 冀T 河北衡水 山西 晋A 山西太原 山西 晋B 山西大同 山西 晋C 山西
weblog 1017 pomparent groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-parent/artifactId version2.1.3.RELEASE/version /parentdependencies dependency groupIdorg.springframework.boot/group
框架 1477 1.pom件dependencygroupIdorg.apache.shiro/groupIdartifactIdshiro-spring/artifactIdversion1.4.0
归档
2018-11  12 2018-12  33 2019-01  28 2019-02  28 2019-03  32 2019-04  27 2019-05  33 2019-06  6 2019-07  12 2019-08  12 2019-09  21 2019-10  8 2019-11  15 2019-12  25 2020-01  9 2020-02  5 2020-03  16 2020-04  4 2020-06  1 2020-07  7 2020-08  13 2020-09  9 2020-10  5 2020-12  3 2021-01  1 2021-02  5 2021-03  7 2021-04  4 2021-05  4 2021-06  1 2021-07  7 2021-08  2 2021-09  8 2021-10  9 2021-11  16 2021-12  14 2022-01  7 2022-05  1 2022-08  3 2022-09  2 2022-10  2 2022-12  5 2023-01  3 2023-02  1 2023-03  4 2023-04  2 2023-06  3 2023-07  4 2023-08  1 2023-10  1 2024-02  1 2024-03  1 2024-04  1
标签
算法基础 linux 前端 c++ 数据结构 框架 数据库 计算机基础 储备知识 java基础 ASM 其他 深入理解java虚拟机 nginx git 消息中间件 搜索 maven redis docker dubbo vue 导入导出 软件使用 idea插件 协议 无聊的知识 jenkins springboot mqtt协议 keepalived minio mysql ensp 网络基础 xxl-job rabbitmq haproxy srs 音视频 webrtc javascript
目录
没有一个冬天不可逾越,没有一个春天不会来临。最慢的步伐不是跬步,而是徘徊,最快的脚步不是冲刺,而是坚持。