如何向Tarantool空间添加新字段

我在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。有什么方法可以做到?

点赞
用户11592715
用户11592715

在回答问题之前,我们先讨论一下 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) -- 错误:我们的元组仅有两个字段

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:第三个值的缺失是可以接受的

您可以选择上述一种方法。

我添加了一些注释:

  • 您无法通过缺少字段添加某些值(例如,您已有第一个和第二个值,您应该在添加第四个之前先添加第三个)
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 方法的信息。

2020-09-24 06:42:56