如何向Tarantool空间添加新字段

3

我在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",我该怎么做?

1个回答

2

在回答问题之前,我们应该讨论一下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方法的信息,请参见文档


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接