如何删除Tarantool空间中的字段?

问题描述

我不再需要tarantool空间中的字段。

local space = Box.schema.space.create('my_space',{if_not_exists = true})
space:format({
        {'field_1','unsigned'},{'field_2',{'field_3','string'},})

如果field_2已被索引和未被索引,如何删除

解决方法

没有任何方便的方法。

第一种方法,只需将该字段声明为可为空,然后将NULL值插入此字段。是的,它将被物理存储,但是您可以将其隐藏给用户。 简单而又不昂贵。

第二种方式,编写就地迁移。如果您要删除的字段后面有索引字段,则不可能(在示例中为field_3)。 如果您在此空间中拥有大量数据,那将很危险。

local space = box.schema.space.create('my_space',{if_not_exists = true})
space:create_index('id',{parts = {{field = 1,type = 'unsigned'}}})
space:format({
    {'field_1','unsigned'},{'field_2',{'field_3','string'},})

-- Create key_def instance to simplify primary key extraction
local key_def = require('key_def').new(space.index[0].parts)

-- drop previous format
space:format({})

-- Migrate your data
for _,tuple in space:pairs() do 
    space:depete(key_def:extract_key(tuple))
    space:replace({tuple[1],tuple[3]})
end

-- Setup new format
space:format({
    {'field_1',})

第三种方法是创建新空间,将数据迁移到其中并删除先前的空间。 还是很危险的。

local space = box.schema.space.create('new_my_space',})

-- Migrate your data
for _,tuple in box.space['my_space']:pairs() do 
    space:replace({tuple[1],tuple[3]})
end

-- Drop the old space
box.space['my_space']:drop()

-- Rename new space
local space_id = box.space._space.index.name:get({'my_new_space'}).id

-- In newer version of Tarantool (2.6+) space.alter method available
-- But in older versions you could update name via system "_space" space 
box.space._space:update({space_id},{{'=','name','my_space'}})