#tarantool
#tarantool
Вопрос:
У меня уже есть пробел с некоторыми индексами.
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
индекс. Что я должен делать?
Ответ №1:
Рассмотрите возможность использования функции 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', type = 'string'}, -- 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', type = 'string'},
{field = 'name', type = 'string', is_nullable = true},
},
})
Также я вижу, что вы используете 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
помощью флага.