在Elasticsearch的索引(index)中, 经过标识元字段_type
来区分不一样的type, 因此咱们能够把具备相同字段(field)的文档划分到同一个type下.json
==> 于是_type
也称做映射类型, 即每一个type都有各自的mapping.数据结构
但即便是相似的数据, 也有可能存在不一样的field, 好比:app
商品中有电子商品有电压field;
服装商品有洗涤方式field;
生鲜商品有养分成分field… 这些不一样的field要如何处理呢?工具
==> 在以前的博文中有提到过: 同一index的不一样type中, 同名的field的映射配置必须相同. 这是为何呢?性能
Elasticsearch底层所使用的核心工具库——Lucene中并无type的说法, 它在创建索引的时候, 会把全部field的值当作opaque bytes(不透明字节)类型来处理:code
在存储document时, ES会将该document所属的type做为一个
type
字段进行存储;blog在搜索document时, ES经过
_type
来进行过滤和筛选.索引
每一个index中的全部type都是存储在一块儿的, 所以:文档
在Elasticsearch 6.0以前: 同一个index的不一样type中, 同名的field的映射配置(
_type
)必须相同.在Elasticsearch 6.0开始: 一个index中不能拥有多个type.
说明: 从Elasticsearch 6.0开始, 不容许在一个index中建立多个type ——只能建立一个, 不然将发生错误:
{ "error": { "root_cause": [ { "type": "illegal_argument_exception", "reason": "Rejecting mapping update to [website] as the final mapping would have more than 1 type: [manager, writer]" } ], "type": "illegal_argument_exception", "reason": "Rejecting mapping update to [website] as the final mapping would have more than 1 type: [manager, writer]" }, "status": 400 }
这里演示所用的版本是6.6.10, 特此说明.
PUT website { "mappings": { // Elasticsearch 6.0以后的版本中, 只添加这一个type "writer": { "properties": { "id": { "type": "long" }, "name": { "type": "text" }, "age": { "type": "integer" }, "sex": { "type": "text", "index": false } } }, "manager": { // 省去此type "properties": { "id": { "type": "long" }, "name": { "type": "text" }, "age": { "type": "integer" }, "sex": { "type": "text", "index": false }, "authorize": { "type": "text", "index": false} } } } }
PUT website/writer/1 { "id": 1001, "name": "tester", "age": 18, "sex": "female" } // Elasticsearch 6.0以后的版本中, 不添加下述文档: PUT website/manager/1 { "id": 1001, "name": "shou feng", "age": 20, "sex": "male", "authorize": "all" }
// 搜索全部数据 GET website/_search // 搜索结果以下: { "hits" : { "total" : 1, "max_score" : 1.0, "hits" : [ { "_index" : "website", "_type" : "writer", // _type是writer "_id" : "1", "_score" : 1.0, "_source" : { "id" : 1001, "name" : "tester", "age" : 18, "sex" : "female" } }, { "_index": "website", "_type": "manager", // _type为manager "_id": "1", "_score": 1, "_source": { "id": 1001, "name": "shou feng", "age": 20, "sex": "male", "authorize": "all" } } ] } }
将结构相似的type存放在同一个index下 —— 这些type的大部分field应该是相同的.
若是将两个field彻底不一样的type存入同一个index下, 在Lucene底层存储时, 每一个document中都将有一大部分field是空值, 这将致使严重的性能问题, 而且占用磁盘空间:
例如: 上述website/writer
的每一个document中, 都有"authorize"字段, 只是它们的值都为空.
—— 从这个角度出发, 大概就能猜出 ES限制一个index中只能有一个type 的缘由了吧, 也就是更方便地组织文档数据、节省磁盘空间😊
版权声明
做者: 马瘦风
出处: 博客园 马瘦风的博客
您的支持是对博主的极大鼓励, 感谢您的阅读.
本文版权归博主全部, 欢迎转载, 但请保留此段声明, 并在文章页面明显位置给出原文连接, 不然博主保留追究相关人员法律责任的权利.