小白学ES 14 - ES底层怎么处理不同type的数据

1 type的作用

在Elasticsearch的index中, 通过标识元字段_type来区分不同的type, 即可以把具有相同field的文档划分到同一个type下.

—— 因而_type也称作映射类型, 即每个type都有各自的mapping.

但即使是类似的数据, 也有可能存在不同的field, 例如: 商品中有电子商品, 服装商品, 生鲜商品…

前面的博文中有提到: 同一index的不同type中, 同名的field的映射配置必须相同.


2 type的底层数据结构

Lucene没有type的说法, 它在建立索引的时候, 会把所有field的值当做opaque bytes(不透明字节)类型来处理.

在存储document时, ES会将该document所属的type作为一个type field来存储;

在搜索document时, ES通过_type来进行过滤和筛选.

每个index中的所有type都是存储在一起的, 因此:

在同一个index的不同type中, 同名的field的映射配置(_type)必须相同.


3 type存储结构的演示

3.1 创建索引并配置映射

PUT website
{
    "mappings": {
        "writer": {
            "properties": {
                "id": { "type": "long" },
                "name": { "type": "text" },
                "age": { "type": "integer" },
                "sex": { "type": "text", "index": false }
            }
        }, 
        "manager": {
            "properties": {
                "id": { "type": "long" },
                "name": { "type": "text" },
                "age": { "type": "integer" },
                "sex": { "type": "text", "index": false }, 
                "authorize": { "type": "text", "index": false}
            }
        }
    }
}

3.2 添加数据

PUT website/writer/1
{
    "id": 1001,
    "name": "tester",
    "age": 18,
    "sex": "female"
}
PUT website/manager/1
{
    "id": 1001,
    "name": "shou feng",
    "age": 20,
    "sex": "male",
    "authorize": "all"
}

3.3 查看存储结构

// 搜索所有数据
GET website/_search

// 搜索结果如下: 
{
    "_index": "website",
    "_type": "writer",			// _type为writer
    "_id": "1",
    "_score": 1,
    "_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"
    }
}

4 关于type的最佳实践

将类似结构的type存放在同一个index下 —— 这些type的大部分field应该是相同的.

如果将两个field完全不同的type存入同一个index下, 在Lucene底层存储时, 每个document中都将有一大部分field是空值, 这将导致严重的性能问题, 并且占用磁盘空间:

例如: 上述website/writer的每个document中, 都有"authorize"字段, 只是它们的值都为空.

版权声明

作者: ma_shoufeng(马瘦风)

出处: CSDN 马瘦风的博客

您的支持是对博主的极大鼓励, 感谢您的阅读.

本文版权归博主所有, 欢迎转载, 但未经博主同意必须保留此段声明, 且在文章页面明显位置给出原文链接, 否则博主保留追究相关人员法律责任的权利.

猜你喜欢

转载自blog.csdn.net/ma_shou_feng/article/details/85065149