Search code examples
luatarantool

How to select data in Tarantool?


I have created a space with two indexes:

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 })
box.space.users:create_index('age', { parts = { 'age' }, if_not_exists = true })

Have inserted some records :

box.space.users:insert({ box.sequence.user_seq:next(), 'Artur Barsegyan', 24})
box.space.users:insert({ box.sequence.user_seq:next(), 'Kostya Nazarov', 32})

How I should select data?


Solution

  • If you need to iterate by an index, you should call a pairs method on the needed index. For example:

    for _, tuple in box.space.users.index.age:pairs({30}, { iterator = 'LT' }) do
        print(tuple)
    end
    

    You will get the following result:

    [1, 'Artur Barsegyan', 24]
    ---
    ... 
    

    What did we do? We have iterated by index age by all tuples with the age that less than 30. More details about iterators and other parameters and filters are in the documentation.

    If you want to select all tuples in a space, call pairs method on space object without parameters:

    tarantool> for i, tuple in box.space.users:pairs() do
             > print(tuple)
             > end
    [1, 'Artur', 'Barsegyan', 24, {'gender': 'male', 'position': 'Product Manager'}]
    [2, 'Kostya', 'Nazarov', 32, {'gender': 'male', 'position': 'Lead of Tarantool Solutions'}]
    ---
    ...
    

    Explore more parameters and filters in documentation and in the following SO questions: