spingboot elastic data 项目
实体类
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.DateFormat;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import java.util.Date;
@NoArgsConstructor
@Data
@Document(indexName = "customer",
type = "customer",
shards = 2,
refreshInterval = "10s")
public class Customer {
@Id
private String id;
@Field(type = FieldType.Keyword)
private String firstName;
private String lastName;
private Boolean valid;
private Integer age;
private String des;
@Field(type = FieldType.Date,
format = DateFormat.custom,
pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date createTime;
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.createTime = new Date();
}
public Customer(String firstName, String lastName , Integer age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.createTime = new Date();
}
}
启动springboot项目
然后查看mapping
## 执行查询
GET /customer/_mapping?pretty=true
## 返回结果
{
"customer": {
"mappings": {
"customer": {
"properties": {
"createTime": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss"
},
"firstName": {
"type": "keyword"
}
}
}
}
}
}
说明自动创建了 mapping
测试
1.添加了新字段是否可以 自动创建 mapping
entity 添加 字段
private String hobby;
重启后 再查看mapping
没有发现 hobby 字段
说明 启动时候没有创建新的字段(type)。
2.在此情况下,保存数据看看怎么样
执行保存操作
@Test
public void testSave() {
Customer customer = new Customer("river", "007", 12);
customer.setHobby("read book");
customerService.save(customer);
}
查看结果
GET /customer/_search?pretty
{
"query": {
"match_all": {}
}
}
已经有了数据了,并且字段 hobby 也存入了
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 2,
"successful": 2,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "customer",
"_type": "customer",
"_id": "JHAq6GoB-x8VcNnrDKNn",
"_score": 1,
"_source": {
"id": null,
"firstName": "river",
"lastName": "007",
"valid": null,
"age": 12,
"des": null,
"hobby": "read book",
"createTime": "2019-05-24 12:47:10"
}
}
]
}
}
最后再看看 mapping
GET /customer/_mapping?pretty=true
{
"customer": {
"mappings": {
"customer": {
"properties": {
"age": {
"type": "long"
},
"createTime": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss"
},
"firstName": {
"type": "keyword"
},
"hobby": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"lastName": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
}
}
}
看来在保存数据的时候,创建了 mapping 。
结论
spring-data-elastic search
实体类添加了新的字段,在保存数据的时候,会创建新的mapping。

网友评论