SpringBoot集成ElasticSearch7.9.2教程和简单增删改查案例
(基于E。。。
另外,es的更新⾮常快,⽬前官⽹最新的版本已经到7.13了,每个版本的API可能都会有所改动。
本⽂基于SpringBoot 2.3.1.RELEASE,ES 7.9.2做演⽰。
开始吧!
⾸先,肯定要先安装es,kibana,基础的安装步骤、配置、分词器插件配置,这⾥就不在介绍,百度⼀搜⼀⼤把。
⼀、pom引⼊spring-data-elasticsearch
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
注意:不同版本spring-data对应的es的默认配置版本不⼀样,如:我当前使⽤的spring-data 版本为4.0,其中默认的es版本为7.6.2,因此我们需要⾃⼰指定需要使⽤的es版本。
在我们项⽬的l⾥⾯指定es的版本:
⼆、配置连接参数
1、yml配置⽂件(主要是为了⽅便修改),注意这⾥的缩进,因为没有使⽤spring⾃带的es配置,所以节点名称都可以⾃定义,同时⽗节点为⼀级节点。
elasticsearch:
scheme: http
host: localhost
port: 9200
connection-request-timeout: 30000
socket-timeout: 6000000
connect-timeout: 5000000
如果使⽤spring的es配置,格式如下:
spring:
data:
elasticsearch:
xxxx:zzzz
xxxx:zzzz
2、新建配置⽂件读取配置客户端连接。
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import t.annotation.Bean;
import t.annotation.Configuration;
@Configuration
public class ElasticSearchClientConfig {
@Value("${elasticsearch.host}")
private String host;
@Value("${elasticsearch.port}")
private Integer port;
@Value("${elasticsearch.scheme}")
private String scheme;
@Value("${t-timeout}")
private Integer connectTimeout;
@Value("${elasticsearch.socket-timeout}")
private Integer socketTimeout;
@Bean
@Qualifier("highLevelClient")
public RestHighLevelClient restHighLevelClient() {
// 该⽅法接收⼀个RequestConfig.Builder对象,对该对象进⾏修改后然后返回。
RestHighLevelClient highLevelClient = new RestHighLevelClient(
RestClient.builder(new HttpHost(host, port, scheme))
.setRequestConfigCallback(requestConfigBuilder -> {
return requestConfigBuilder.setConnectTimeout(connectTimeout) // 连接超时(默认为1秒)
.setSocketTimeout(socketTimeout);// 套接字超时(默认为30秒)//更改客户端的超时限制默认30秒现在改为100*1000分钟
}));// 调整最⼤重试超时时间(默认为30秒).setMaxRetryTimeoutMillis(60000);
return highLevelClient;
}
}
⾄此,springboot配置es就完成了,启动项⽬即可看到如下信息:因为我们设置了版本和springdata默认的版本⼀直,所以会警告版本不匹配,不⽤理会。
三、新建⼀个实体类,并配置索引映射,这样我们可以直接⽤这个类去创建索引,并且配置索引字段的mapping
在创建实体类和映射规则前,有必要先了解⼀下elasticsearch的⼏个常⽤注解和枚举:
1、@Document,位于org.springframework.data.elasticsearch.annotations包下。
@Persistent
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
public @interface Document {
/**
* Name of the Elasticsearch index.
* <ul>
* <li>Lowercase only</li>
* <li><Cannot include \, /, *, ?, ", <, >, |, ` ` (space character), ,, #/li>
* <li>Cannot start with -, _, +</li>
* <li>Cannot be . or ..</li>
* <li>Cannot be longer than 255 bytes (note it is bytes, so multi-byte characters will
* count towards the 255 limit
* faster)</li>
* </ul>
*/
String indexName(); //索引名称,好⽐MySQL的数据库名
@Deprecated
String type() default ""; //类型 ,当前版本已弃⽤
/**
* Use server-side settings when creating the index.
* 翻译过来就是:创建索引时使⽤服务器端设置。
* 这⾥默认为false,如果改为true,表⽰在Spring创建索引时,Spring不会在创建的索引中设置以下设
* 置:shards、replicas、refreshInterval和indexStoreType。这些设置将是 Elasticsearch 默认
* 值(服务器配置),也就是说,我们⾃定义的某些配置将不会⽣效。
*/
boolean useServerConfiguration() default false;
short shards() default 1; // 默认分区数
short replicas() default 1;// 默认每个分区的备份数
String refreshInterval() default "1s"; //索引默认的刷新时间间隔
String indexStoreType() default "fs"; //索引⽂件存储类型
/**
* Configuration whether to create an index on repository bootstrapping.
*/
boolean createIndex() default true; //当spring容器启动时,如果索引不存在,则⾃动创建索引
VersionType versionType() default VersionType.EXTERNAL;//默认的版本管理类型
}
2、@Field,位于org.springframework.data.elasticsearch.annotations包下:这个注解的字段⽐较多,这⾥只列举⼏个⽐较常⽤的
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
@Inherited
public @interface Field {
/**
* Alias for {@link #name}.
*
* @since 3.2
*/
@AliasFor("name")
String value() default "";
/**
* The <em>name</em> to be used to store the field inside the document.
* <p>
* √5 If not set, the name of the annotated property is used.
*
* @since 3.2
*/
@AliasFor("value")
String name() default "";
//上⾯两个注解,可互为别名使⽤。
//主要的作⽤就是指定我们创建索引时,当前字段在索引中的名称,如果不设置,它会默认使⽤实体类⾥    // ⾯使⽤了@Field这个注解的属性名作为索引字段名。例如:
// class User{
//
//    @Field(name = "name" * 或者:value = "name"* )
//    private String userName;
// }
// 如上,如果设置了name(或value)值,那么索引⾥⾯对应userName的字段名就是“name”,否则就是    // “userName”
FieldType type() default FieldType.Auto; //⾃动检测索引字段的数据类型,可以根据实际情况⾃⼰设置。
DateFormat format() ;//⽇期时间格式化,默认不做任何处理
String searchAnalyzer() default "";//检索时的分词策略
jfinal增删改查String analyzer() default "";//创建索引时指定分词策略
.
.
.
}
3、@Field中提到的FieldType 枚举:
public enum FieldType {
Auto, //根据内容⾃动判断
Text, //索引全⽂字段,如产品描述。这些字段会被分词器进⾏分词处理。
Keyword, //⽤于索引结构化内容(如电⼦邮件地址,主机名,状态码,等)的字段。他们通常⽤于过滤、排序、聚合。关键字字段只能根据期确切的值进⾏    Long, //
Integer, //
Short, //
Byte, //
Double, //
Float, //
Half_Float, //
Scaled_Float, //
Date, //
Date_Nanos, //
Boolean, //
Binary, //
Integer_Range, //
Float_Range, //
Long_Range, //
Double_Range, //
Date_Range, //
Ip_Range, //
Object, //
Nested, //
Ip, //可以索引和存储IPV4和IPv6地址
TokenCount, //
Percolator, //
Flattened, //
Search_As_You_Type //
}
好了,了解了基础的注解之后,新建实体类并映射规则,为创建索引做准备:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。