Search code examples
luatarantool

How to create a space in Tarantool?


I've started Tarantool and have called box.cfg{} for the first configuring.

The next step: I want to create a space in Tarantool. I read the documentation but I didn't quite understand everything.

How I should do it?


Solution

  • Create it via Box API:

    box.schema.sequence.create('user_seq', { if_not_exists = true })
    box.schema.create_space('users', { if_not_exists = true, format={
        { name = 'id', type = 'unsigned'},
        { name = 'name', type = 'string'}, 
        { name = 'age', type = 'unsigned'}} 
    })
    box.space.users:create_index('pk', { parts = { 'id' }, if_not_exists = true })
    

    With if_not_exists, tarantool won't try to create space if it already exists.

    Creating the index is mandatory because Tarantool doesn't allow you to insert data in space without any indexes.

    After creating the space, you can insert and select data:

    box.space.users:insert({ box.sequence.user_seq:next(), 'Artur Barsegyan', 24 })
    box.space.users:get({1})
    
    ---
    - - [1, 'Artur Barsegyan']
    ...
    

    You can read more in the documentation.