【问题标题】:How to remove a field in Tarantool space?如何删除 Tarantool 空间中的字段?
【发布时间】:2020-10-03 01:39:03
【问题描述】:

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

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

如果field_2 已编入索引且未编入索引,如何删除?

【问题讨论】:

    标签: tarantool tarantool-cartridge


    【解决方案1】:

    没有任何方便的方法。

    第一种方式,只需将该字段声明为可为空,并将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', 'unsigned'},
        {'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', 'unsigned'},
        {'field_3', 'string'},
    })
    

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

    local space = box.schema.space.create('new_my_space', {if_not_exists = true})
    space:create_index('id', {parts = {{field = 1, type = 'unsigned'}}})
    space:format({
        {'field_1', 'unsigned'},
        {'field_3', 'string'},
    })
    
    -- 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'}})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-01
      • 1970-01-01
      相关资源
      最近更新 更多