ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] # 简介 ES是依靠JSON文档的字段类型来实现自动识别字段类型,支持的类型如下: ![](https://img.kancloud.cn/62/3e/623e7772e7ce48cc8ebe58d94d43b15d_421x435.png) ~~~ POST my_index/doc { "username":"whirly", "age":22, "birthday":"1995-01-01" } GET my_index/_mapping # 结果 { "my_index": { "mappings": { "doc": { "properties": { "age": { "type": "long" }, "birthday": { "type": "date" }, "username": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } } } } } } } ~~~ ## 日期的自动识别 * dynamic\_date\_formats 参数为自动识别的日期格式,默认为 \[ "strict\_date\_optional\_time","yyyy/MM/dd HH:mm:ss Z||yyyy/MM/dd Z"\] * date\_detection可以关闭日期自动识别机制 ~~~ # 自定义日期识别格式 PUT my_index { "mappings": { "_doc": { "dynamic_date_formats": ["MM/dd/yyyy"] } } } # 关闭日期自动识别机制 PUT my_index { "mappings": { "_doc": { "date_detection": false } } } ~~~ ## 数字的自动识别 * 字符串是数字时,默认不会自动识别为整形,因为字符串中出现数字完全是合理的 * numeric\_detection 参数可以开启字符串中数字的自动识别 ## Dynamic templates 允许根据ES自动识别的数据类型、字段名等来动态设定字段类型,可以实现如下效果: * 所有字符串类型都设定为keyword类型,即不分词 * 所有以message开头的字段都设定为text类型,即分词 * 所有以long\_开头的字段都设定为long类型 * 所有自动匹配为double类型的都设定为float类型,以节省空间 **Dynamic templates API** ~~~ "dynamic_templates": [ { "my_template_name": { ... match conditions ... "mapping": { ... } } }, ... ] ~~~ 匹配规则一般有如下几个参数: * match\_mapping\_type 匹配ES自动识别的字段类型,如boolean,long,string等 * match, unmatch 匹配字段名 * match\_pattern 匹配正则表达式 * path\_match, path\_unmatch 匹配路径 ~~~ # double类型的字段设定为float以节省空间 PUT my_index { "mappings": { "_doc": { "dynamic_templates": [ { "integers": { "match_mapping_type": "double", "mapping": { "type": "float" } } } ] } } } ~~~ **自定义Mapping的建议** 1. 写入一条文档到ES的临时索引中,获取ES自动生成的Mapping 2. 修改步骤1得到的Mapping,自定义相关配置 3. 使用步骤2的Mapping创建实际所需索引 ## 动态映射 ~~~ PUT /library { "mappings": { "books": { "dynamic": "strict", "properties": { "title": {"type": "string"}, "name": {"type": "string", "index": "not_analyzed"}, "publish_date": {"type": "date","index": "not_analyzed"}, "price": {"type": "double"}, "number": { "type": "object", "dynamic": true } } } } } ~~~