本文章主要介绍SpringBoot集成elasticsearch进行全文检索的功能处理。
一、首先是yml配置文件进行数据配置如下模式。
spring:
elasticsearch:
rest:
uris: http://127.0.0.1:9300
# cluster.nodes: hadoop137:9300,hadoop138:9300,hadoop139:9300
1、cluster.nodes: 127.0.0.1:9300是配置的本地模式。
2、cluster.nodes: hadoop137:9300,hadoop138:9300,hadoop139:9300是配置的集群模式
ps:我这里采用的是配置的本地模式
二、需要引入对应的elasticsearch的依赖,请注意SpringBoot对应的elasticsearch版本,对应关系如下:
我是用的是2.3.12的Springboot,7.6.2的elasticsearch,知道了对应版本关系就需要引入对应的依赖了在你的pom.xml下添加如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>`
前俩个是Springboot和elasticsearch的依赖,下面这个是对应实体内有需要这个包下的注解,最后一个是lombok包实体需要使用对应注解@Data
ps:如果注解有报错,可以搜索一下看看差那些依赖,自己引入下就好
三、依赖和配置完善之后咱们可是代码类处理:
先从实体开始,新建实体,标记索引:
在这里插入代码片
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import java.io.Serializable;
import java.util.List;
import lombok.Data;
/**
* @description:test
* @author: YangYang
* @time: 2021/11/16 15:51
*/
@Data
@Document(indexName = "testdoct", type = "elasticsearch")
public class Elasticsearch implements Serializable {
public Elasticsearch() {
}
public Elasticsearch(long id, String name, Integer age, String sex, String desc) {
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
this.desc = desc;
}
/**
*必须指定一个id
*/
@Id
private long id;
/**
*这里配置了分词器,字段类型,可以不配置,默认也可
*/
@Field(analyzer = "ik_smart", type = FieldType.Text)
private String name;
private In