在插入一条Blog后,使用浏览器打开 http://localhost:9200/website/_mapping/blog?pretty 显示信息如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 1{
2 "website": {
3 "mappings": {
4 "blog": {
5 "properties": {
6 "author": {
7 "type": "text",
8 "fields": {
9 "keyword": {
10 "type": "keyword",
11 "ignore_above": 256
12 }
13 }
14 },
15 "date": {
16 "type": "long"
17 },
18 "id": {
19 "type": "long"
20 },
21 "likes": {
22 "type": "long"
23 },
24 "text": {
25 "type": "text",
26 "fields": {
27 "keyword": {
28 "type": "keyword",
29 "ignore_above": 256
30 }
31 }
32 }
33 }
34 }
35 }
36 }
37}
38
上面JSON格式的内容中描述了四项关键信息:索引、类型、字段和映射。
- 索引(index)
内容中的"website",类比关系数据库中的库
- 类型(type)
内容中的"blog",类比关系数据库中的表
- 字段(field)
内容中的author、date、id、likes和text,类比关系数据库中的列
- 映射(mapping)
描述字段的保存方式等,如"type": "long",类比关系数据库中的列的数据类型。
注意author和text字段,除了本身被映射为text类型,还另外为其添加了名称为keyword、type为keyword的field,这使得查询时既可以对字段本身做Match Query,也可以对author.keyword做Term Query。
不同于关系型数据库要预先创建库和表,在添加第一个Blog时,Elasticsearch即使用动态映射猜测字段类型,得出上述映射。映射在创建后不可修改,如果需要自己指定映射类型,可以通过下面的方式。
1 删除原索引
1
2 1elasticsearchTemplate.deleteIndex("website");
2
2 通过注解设置字段类型
1
2
3
4
5
6
7
8
9
10
11 1@Document(indexName = "website", type = "blog")
2public class Blog {
3
4 private int id;
5 private String author;
6 private String text;
7 private int likes;
8
9 @Field(type = FieldType.Date)
10 private Date date;
11
3 创建索引并设置映射
1
2
3 1elasticsearchTemplate.createIndex("website");
2elasticsearchTemplate.putMapping(Blog.class);
3
重新用 http://localhost:9200/website/_mapping/blog?pretty 查看映射,可以看到date字段已经设置为日期类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14 1{
2 "website" : {
3 "mappings" : {
4 "blog" : {
5 "properties" : {
6 "date" : {
7 "type" : "date"
8 }
9 }
10 }
11 }
12 }
13}
14