【问题标题】:How to add new field to Tarantool space如何向 Tarantool 空间添加新字段
【发布时间】:2020-09-24 14:42:56
【问题描述】:

我在 Tarantool 中有以下空间架构

box.schema.space.create('customer')

format = {
    {name = 'id', type = 'string'},
    {name = 'last_name', type = 'string'},
}

box.space.customer:format(format)
box.space.customer:create_index('id', {parts = {{field = 'id', is_nullable = false}}})
box.space.customer:replace({'1', 'Ivanov'})

我想将新字段 first_name 添加到此空间。我有什么办法可以做到这一点?

【问题讨论】:

    标签: lua nosql tarantool


    【解决方案1】:

    在回答问题之前,我们应该讨论一个format 方法。

    format - 这是一个空格选项,可让您按名称从元组中获取值。实际上元组是一个值的“列表”,任何字段都可以通过字段编号访问。

    接下来是什么?例如。你有一个简单的架构。

    box.schema.space.create('customer')
    box.space.customer:format(format)
    box.space.customer:create_index('id', {parts = {{field = 'id', is_nullable = false}}})
    box.space.customer:replace({'1', 'Ivanov'})
    

    让我们定义具有第三个字段 - first_name 的新格式。

    new_format = {
        {name = 'id', type = 'string'},
        {name = 'last_name', type = 'string'},
        {name = 'first_name', type = 'string'},
    }
    
    box.space.customer:format(new_format) -- error: our tuple have only two fields
    
    tarantool> box.space.customer:format(new_format)
    - --
    - error: Tuple field 3 required by space format is missing
    ...
    

    有两种方法可以修复它。

    1. 使用默认值将新字段添加到元组的末尾。
    box.space.customer:update({'1'}, {{'=', 3, 'Ivan'}})
    box.space.customer:format(new_format) -- OK
    
    1. 将新字段定义为可为空
    new_format = {
        {name = 'id', type = 'string'},
        {name = 'last_name', type = 'string'},
        {name = 'first_name', type = 'string', is_nullable = true},
    }
    
    box.space.customer:format(new_format) -- OK: absence of the third value is acceptable
    

    您可以选择上述变体之一。

    我刚刚添加了一些注释:

    • 您不能通过缺席字段添加一些值(例如,您有第一个和第二个值,您应该在添加第四个之前添加第三个)
    tarantool> box.tuple.new({'1', 'Ivanov'}):update({{'=', 4, 'value'}})
    - --
    - error: Field 4 was not found in the tuple
    
    ...
    
    tarantool> box.tuple.new({'1', 'Ivanov'}):update({{'=', 3, box.NULL}, {'=', 4, 'value'}})
    - --
    - ['1', 'Ivanov', null, 'value']
    
    ...
    
    • 如果您有大量数据,使用默认值填写该字段可能是一个相当长的操作。申请任何迁移时请小心。

    详细了解format 方法in the documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多