SpringBoot+ElasticSearch 实现全文检索

本文介绍Spring Boot集成ElasticSearch的实战过程,包括在pom.xml引入依赖、配置文件添加配置、添加实体ESBlog、对应的ESBlogSearchRepository,还说明了在Service或Controller中的使用方法,并给出操作效果示例,如查询特定关键词的blog,最后提醒数据同步相关注意事项。

ElasticSearch环境搭建:https://blog.csdn.net/u014553029/article/details/106009344

SpringBoot集成ElasticSearch实战

一、在pom.xml中引入依赖

<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-elasticsearch -->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-elasticsearch</artifactId>
    <version>3.2.6.RELEASE</version>
</dependency>

spring-boot-starter-data-elasticsearch包,引用的是spring-data-elasticsearch包,而spring-data-elasticsearch包的版本与elasticsearch服务版本是有兼容性问题的。具体可参考:https://github.com/spring-projects/spring-data-elasticsearch

二、在配置文件中添加相关配置

spring:
  data:
    elasticsearch:
      cluster-name: elasticsearch
      cluster-nodes: 127.0.0.1:9300
      repositories:
        enabled: true

三、添加实体ESBlog

使用@Document注解,参数indexName是索引名称,type是type名称。

注解说明:

  • @Document 作用在类,标记实体类为文档对象,一般有两个属性
    • indexName:对应索引库名称
    • type:对应在索引库中的类型
    • shards:分片数量,默认5
    • replicas:副本数量,默认1
  • @Id 作用在成员变量,标记一个字段作为id主键
  • @Field 作用在成员变量,标记为文档的字段,并指定字段映射属性:
    • type:字段类型,是是枚举:FieldType,可以是text、long、short、date、integer、object等
      • text:存储数据时候,会自动分词,并生成索引
      • keyword:存储数据时候,不会分词建立索引
      • Numerical:数值类型,分两类
        • 基本数据类型:long、interger、short、byte、double、float、half_float
        • 浮点数的高精度类型:scaled_float
          • 需要指定一个精度因子,比如10或100。elasticsearch会把真实值乘以这个因子后存储,取出时再还原。
      • Date:日期类型
        • elasticsearch可以对日期格式化为字符串存储,但是建议我们存储为毫秒值,存储为long,节省空间。
    • index:是否索引,布尔类型,默认是true
    • store:是否存储,布尔类型,默认是false
    • analyzer:分词器名称,这里的ik_max_word即使用ik分词器
    • searchAnalyzer :搜索使用分词器
package com.oycbest.springbootelasticsearch.document;

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;

/**
 * @Author: oyc
 * @Date: 2020-04-30 9:37
 * @Description: Blog 文档实体类
 */
@Data
@Document(indexName = "blog_index", type = "blog")
public class EsBlog {

    @Id
    private int id;
    /**
     * 是否索引: 看该域是否能被搜索, index = true(默认为true)
     * 是否分词: 表示搜索的时候是整体匹配还是单词匹配
     * 是否存储: 是否在页面上显示
     */
    @Field(index = true, analyzer = "ik_smart", searchAnalyzer = "ik_smart")
    private String title;

    @Field(analyzer = "ik_smart
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值