使用spring-data-elasticsearch操作Elasticsearch
pom依赖
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot<groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.1.5.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombook</groupId>
<artifactId>lombook<artifactId>
</dependency>
</dependencies>
yml配置
spring:
data:
elasticsearch:
cluster-name: elasticsearch
cluster-nodes: 127.0.0.1:9300
po映射
import lombok.Data;
import java.io.Serializable;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.DateFormat;
@Data
@Document(indexName="user_index", type="user_type", shards=1, replicas=0)
public class User implements Serializable{
private static final long serialVersionUID = 627994168197554442L;
@Id
private long id;
@Field(type=FieldType.Keyword)
private String name;
@Field(type=FieldType.Integer)
private int age;
@Field(type=FieldType.Text,analyzer="ik_max_word")
private String desc;
@Field(type=FieldType.Date, format=DateFormat.custom, pattern="yyyy-MM-dd HH:mm:ss SSS")
private String createTime;
@Field(type=FieldType.Date, format=DateFormat.custom, pattern="yyyy-MM-dd HH:mm:ss SSS")
private String updateTime;
}
注意:
- 使用@Id表示该字段同时会被映射到Elasticsearch中document的_id字段(也就是说在Elasticearch中_id的值与id值一样);
- 如果document字段与实体类字段名称不统一,在Spring Data Elasticsearch 3.2版本及其之后直接使用@Field的name属性指定,3.2版本之前则需要使用@JsonProperty指定
import org.springframework.data.elasticsearch.annotation.*; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonProperty; @Date @Document(indexName="user_index",type="user_type") public class User implements Serializable{ private static final long serialVersionUID = 627994168197554442L; //3.2版本及之后 @Field(name="address_city", type=FieldType.Keyword) private String addressCity; //3.2版本之前 @Field(type=FieldType.Keyword) @JsonProperty("address_city") private String addressCity; }