es 使用ik停词_使用Spring Boot + ElasticSearch实现博客的全文检索(开始项目编码)...

a76ff3a8f84e6dc10fcc1b0d872d7b68.png

1)使用Spring Boot的DevTools实现热部署

在项目创建之初我们就已经在pom文件中引入了spring-boot-devtools这个Spring Boot提供的热部署插件,但是可能会遇到热部署不生效的问题,如果你使用的是Intellij Idea开发工具,参见《使用Spring Boot Devtools实现热部署》。

2)创建数据表的实体类

虽说我们要做的是对于博客的全文检索,但是在用户没有给定搜索条件之前,我们还是应该使用Mysql通过主键索引的方式查询出博客数据(当然,简单起见这里没有实现分页查询功能),Mysql的主键查询是很快的,无需使用ES;当用户输入查询条件时,表示需要进行全文检索时我们才使用ES。

Mysql自不用说,ES也是需要实体类来承载数据的,他们的字段结构都是相同的,不同的只是标注在字段上的注解,下面来快速创建他们的实体类:

2.1)创建博客文章Mysql实体类

@Data
@Table(name = "t_article")       // 指定实体类对应的数据表
@Entity
public class MysqlArticle {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) // 使用数据表定义的增长策略(自增)
    private Integer id;          // 文章ID

    private String author;       // 文章作者

    private String title;        // 文章标题

    // String类型默认映射的是varchar类型,content字段使用到了mediumtext,需要显式指定一下
    @Column(name = "content", columnDefinition = "mediumtext")
    private String content;      // 文章正文内容

    private Date createTime;     // 文章创建时间

    private Date updateTime;     // 文章更新时间
}

2.2)创建博客文章ElasticSearch实体类

@Data
// 指定实体类对应ES的索引名称为blog,类型type是文档类型,使用服务器远程配置
// 为避免每次重启项目都将ES中的数据删除后再同步,createIndex指定为false
@Document(indexName = "blog", type = "_doc",
        useServerConfiguration = true, createIndex = false)
public class ElasticArticle {
    
    @Id // org.springframework.data.annotation.Id
    private Integer id;          // 文章ID

    // 指定字段对应的ES类型是Text,analyzer指定分词器为ik_max_word
    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String author;       // 文章作者

    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String title;        // 文章标题

    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String content;      // 文章正文内容

    // 指定字段对应ES中的类型是Date,使用自定义的日期格式化,pattern指定格式化
    // 规则是“日期时间”或“日期”或“时间毫秒”
    @Field(type = FieldType.Date, format = DateFormat.custom,
            pattern = "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis")
    private Date createTime;     // 文章创建时间

    @Field(type = FieldType.Date, format = DateFormat.custom,
            pattern = "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis")
    private Date updateTime;     // 文章更新时间
}

3)编写Mysql和ES的数据操作接口

由于使用了Spring-Data-JPA,这项工作将十分简单,只需要自建接口继承自对应的JpaRepositoryElasticsearchRepository接口即可。

创建Mysql数据访问接口

public interface MysqlArticleRepository
        extends JpaRepository<MysqlArticle, Integer> {
    
}

创建ES数据访问接口

public interface ElasticArticleRepository
        extends ElasticsearchRepository<ElasticArticle, Integer> {
    
}

4&

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值