如何将新字段添加到现有索引?

问题描述

我已经有了一些索引的空格。

Box.schema.sequence.create('user_seq')
Box.schema.space.create('user',{
    if_not_exists = true,format = {
        { name = 'id',type = 'unsigned'},{ name = 'user_id',type = 'string'}
    }
})
Box.space.user:create_index('id',{
     sequence = 'user_seq',parts = {'id'}
})
Box.space.user:create_index('user_id',{
     parts = {'user_id'},if_not_exists = true,unique = false
})

想要向user_id索引中添加新字段。我该怎么办?

解决方法

考虑使用index.alter函数(https://www.tarantool.io/en/doc/latest/reference/reference_lua/box_index/#box-index-alter

例如您要将“ id”字段添加到“ user_id”索引中。

box.space.user.index.user_id:alter({
    parts = {
        {field = 'user_id',type = 'string'},{field = 'id',type = 'unsigned'}},-- Add "id" field to your index
})

或例如您要向架构中添加新字段,然后向架构中添加新字段(例如“名称”)。 首先,您应该更新格​​式:

box.space.user:format({
    { name = 'id',type = 'unsigned'},{ name = 'user_id',-- Preserve to existing fields
    -- Add a new one
    -- It's important to define them as nullable because
    -- you don't have them physically
    -- If you want to define them as non-nullable
    -- You should append "name" to each tuple before
    -- It's possible because format checks only defined fields
    -- But basically tuple is a list of values and
    -- it can have arbitrary length.
    -- For simplification I say it as nullable.
    { name = 'name',type = 'string',is_nullable = true},})

-- Then you can to alter your index
box.space.user.index.user_id:alter({
    parts = {
        {field = 'user_id',{field = 'name',},})

我还看到您使用parts = {'id'}parts = {'user_id'}。这是定义索引的正确方法-提供应建立索引的字段数组。但是,这会使您的模式表现力降低,并允许您犯错。相反,我建议您使用严格的架构定义。 -明确指定零件{field = <field_name/field_number>,type = <type>,collation = <collation>,is_nullable = <true/false>}。如果已经定义了格式,则可以省略类型说明。 如第二个示例所示,它很重要。您不能使用parts={'user_id','name'}标志来指定is_nullable=true