ElasticSearch教程(5)——关于动态Mapping和Templates
1. 类型判定
ElasticSearch在创建index的时候是可以不指定schema的,那么它是怎么知道你使用的是什么类型呢?实际上它是通过给定document的json来判定的,例如,string的话是用引号引起来的,数字是光溜溜的,boolean类型是true或者false等等。这个规则非常的简单,但是非常有效。例如有如下的json:
1 |
{ |
2 |
"field1" : "hello" , |
3 |
"field2" : 1024 |
4 |
} |
ES能够很容易判定field1为string类型,field2为数字类型,但是有些情况下,需要把所有的格式都存为string,true和false就不行了,因为ES会优先将其存为boolean类型,这就需要我们手动指定schema,另外一个问题是,如果我们对某个index首次插入数据的时候为某个field插入了一个数字类型,例如:
1 |
curl -XPUT localhost: 9200 /blog/article/ 1 ?pretty -d '{ "field1" : 1024}' |
我们可以查看其mapping:
1 |
curl -XGET localhost: 9200 /blog/_mapping?pretty |
我们可以看到其schem如下:
1 |
{ |
2 |
"blog" : { |
3 |
"article" : { |
4 |
"properties" : { |
5 |
"field1" : { |
6 |
"type" : "long" , |
7 |
"ignore_malformed" : false |
8 |
} |
9 |
} |
10 |
} |
11 |
} |
12 |
} |
这说明ES已经将该字段的类型定义为long了,然后如果我们插入string,那么就会报错,说类型不匹配:
1 |
curl -XPUT localhost: 9200 /blog/article/ 2 ?pretty -d '{ |
2 |
"field1" : "test string" |
3 |
}' |
返回结果为:
1 |
{ |
2 |
"error" : "MapperParsingException[Failed to parse [field1]]; |
3 |
nested: NumberFormatException[For input string: |
4 |
\ "test string\"]; " , |
5 |
"status" : 400 |
6 |
} |
但是,如果继续插入float型数据是可以的,因为long可以转换为float,如下:
1 |
curl -XPUT localhost: 9200 /blog/article/ 2 ?pretty -d '{ |
2 |
"field1" : 3.14 |
3 |
}' |
这时,我们在查看schema,可以看到ES将schema修改了。这就会对我们的数据精度造成影响,为了防止这种情况,或者为了防止已经存在的index添加字段,我们可以将动态schema关闭,如下:
1 |
{ |
2 |
"blog" : { |
3 |
"article" : { |
4 |
"dynamic" : "false" , |
5 |
"properties" : { |
6 |
... |
7 |
} |
8 |
} |
9 |
} |
10 |
} |
2.动态mapping
有时,我们需要通过json中的field和type来决定我们使用的mapping,这时,动态templates就派上用场了。动态templates和普通的mapping类似,它有一个自己的模式,如果一个field的名字匹配了该模式,该template就会使用,下面是定义模式的两种手段:
-
match
: template在field名匹配的时候起用。 -
unmatch
: template在field名不匹配的时候起用。
当然,也可以使用path_match
和path_unmatch对嵌套field使用。
定义field的使用可以使用
-
{name}
: document最初写入数据的field的名字。 -
{dynamic_type}
: document最初写入数据的field的type。
需要提醒的是,ES是按照你写的templates的顺序来匹配的,因此,匹配范围越广的应该放在越后,不然就会将所有后面的正则拦掉了。例如*应该放在最后:
1 |
{ |
2 |
"mappings" : { |
3 |
"article" : { |
4 |
"dynamic_templates" : [ |
5 |
{ |
6 |
"template_test" : { |
7 |
"match" : "*" , |
8 |
"mapping" : { |
9 |
"type" : "multi_field" , |
10 |
"fields" : { |
11 |
"{name}" : { "type" : "{dynamic_type}" }, |
12 |
"str" : { "type" : "string" } |
13 |
} |
14 |
} |
15 |
} |
16 |
} |
17 |
] |
18 |
} |
19 |
} |
20 |
} |
from http://www.dengchuanhua.com/234.html