咱们习惯上对ElasticSearch和数据库作了一些对比,索引(index)至关于数据库,类型(type)至关于数据表,映射(Mapping)至关于数据表的表结构。数据库
ElasticSearch中的映射(Mapping)用来定义一个文档,能够定义所包含的字段以及字段的类型、分词器及属性等等。数组
映射能够分为动态映射和静态映射:app
动态映射:咱们知道,在关系数据库中,须要事先建立数据库,而后在该数据库实例下建立数据表,而后才能在该数据表中插入数据。而ElasticSearch中不须要事先定义映射(Mapping),文档写入ElasticSearch时,会根据文档字段自动识别类型,这种机制称之为动态映射。spa
静态映射:在ElasticSearch中也能够事先定义好映射,包含文档的各个字段及其类型等,这种方式称之为静态映射。设计
咱们新建立一个索引informationcode
PUT information
建立成功响应:orm
{ "acknowledged": true, "shards_acknowledged": true, "index": "information" }
查看mapping结构:对象
GET information/_mapping
查询到mapping结构为空:索引
{ "information": { "mappings": {} } }
插入文档信息:ip
PUT information/record/1 { "ip":"10.192.168.4", "attack_type":"scan_ip", "count": 400, "create_time":"2018-03-07 00:00:00" }
建立成功:
{ "_index": "information", "_type": "record", "_id": "1", "_version": 1, "result": "created", "_shards": { "total": 2, "successful": 2, "failed": 0 }, "_seq_no": 0, "_primary_term": 1 }
而后咱们再次查询mapping结构:
{ "information": { "mappings": { "record": { "properties": { "attack_type": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "count": { "type": "long" }, "create_time": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "ip": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } } } } } } }
在添加文档时ElasticSearch会推测添加文档中每一个属性字段是什么类别:
record推测结果:
attack_type:text类型
count:long类型
create_time:text类型(实际应该为date类型,推测并非很是准确)
ip:text类型
动态映射能够帮助咱们在建立索引后直接将文档数据写入ElasticSearch,让咱们尽快享受到ElasticSearch检索功能。在实际项目中,若是在导入数据前不能肯定包含哪些字段或者不方便肯定字段类型,可使用动态映射。当向ElasticSearch写入一个新文档时,须要一个以前没有的字段,会经过动态映射来推断该字段类型。
JSON数据 | 自动推测的类型 |
---|---|
null | 没有字段被添加 |
true或false | boolean型 |
小数 | float型 |
数字 | long型 |
日期 | date或text |
字符串 | text |
数组 | 由数组第一个非空值决定 |
JSON对象 | object类型 |
动态映射的自动类型推测功能并非100%正确的,这就须要静态映射机制。静态映射与关系数据库中建立表语句类型,须要事先指定字段类型。相对于动态映射,静态映射能够添加更加详细字段类型、更精准的配置信息等。
新建静态映射:
首先删除已经建立的information索引,而后再建立索引是定义mapping结构
PUT information { "mappings": { "record":{ "properties": { "ip":{"type": "text"}, "count":{"type": "long"}, "create_type":{"type": "date"}, "i_type":{"type": "text"} } } } }
执行成功:
{ "acknowledged": true, "shards_acknowledged": true, "index": "information" }
查看索引mapping结构:
GET information/_mapping
响应结果:
{ "information": { "mappings": { "record": { "properties": { "count": { "type": "long" }, "create_type": { "type": "date" }, "i_type": { "type": "text" }, "ip": { "type": "text" } } } } } }
类型是Elasticsearch的一个设计失误,6.0开始后面的版本将再也不支持,在6.x中建立的索引只容许每一个索引有单一类型。任何名字均可以用于这个类型,可是只能有一个。