0%

Jpa整合ElasticSearch

文章字数:476,阅读全文大约需要1分钟

SpringBoot中可以使用jpa整合ElasticSearch

环境

  • jdk 1.8
  • ElasticSearch 2.4需要和springBoot版本匹配
  • com.sun.jna

继承依赖

1
2
3
spring-boot-starter-data-elasticsearch
com.sun.jna
org.springframework.boot:spring-boot-starter-web

配置实体

data-elasticsearch的依赖自带了ES的jar,如果不配置ES实例SpringBoot会自动生成一个。但是性能不如自己搭建的。

1
2
3
4
5
spring:
data:
elasticsearch:
cluster-name: elasticsearch
cluster-nodes: localhost:9300

实体类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Data  //lombok
@Document(indexName = "shop", type = "user", refreshInterval = "0s")
public class User {

@Id
private Long id;

private String username;

private String realname;

private String password;

private Integer age;

//这三个注解是为了前台序列化java8 LocalDateTime使用的,需要引入jsr310的包才可以使用
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
private LocalDateTime birth;

}
  • @Document加在类上
类型 属性名 默认值 说明
String indexName 索引库的名称,建议以项目的名称命名
String type “” 类型,建议以实体的名称命名
short shards 5 默认分区数
short replica 1 每个分区默认的备份数
String refreshInterval “1s” 刷新间隔
String indexStoreType “fs” 索引文件存储类型
  • @Field属性上加的,相当于@Column,可以不写,默认全部添加到ES中。主键上是@Id
类型 属性名 默认值 说明
FieldType type FieldType.Auto 自动检测属性的类型
FieldIndex index FieldIndex.analyzed 默认情况下分词
boolean store false 默认情况下不存储原文
String searchAnalyzer “” 指定字段搜索时使用的分词器
String indexAnalyzer “” 指定字段建立索引时指定的分词器
String[] ignoreFields {} 如果某个字段需要被忽略

DAO

1
2
3
@Repository
public interface UserRepository extends ElasticsearchRepository<UserInfo,String> {
}