如何向Tarantool空间添加新字段

问题描述

我在Tarantool中有以下空间模式

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

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

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添加到此空间。我该怎么做?

解决方法

在回答问题之前,我们应该讨论一种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',{name = 'first_name',}

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',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',box.NULL},{'=','value'}})
- --
- ['1','Ivanov',null,'value']

...
  • 如果您有大量数据,则使用默认值填充字段可能会花费很长时间。应用偏头痛时请小心。

详细了解format方法in the documentation