如何在Tarantool中选择数据?

问题描述

我用两个索引创建了一个空间:

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 })

已插入一些记录:

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

我应该如何选择数据?

解决方法

如果需要按索引进行迭代,则应在所需的索引上调用pairs方法。例如:

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

您将得到以下结果:

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

我们做了什么?我们对所有元组的索引age进行了迭代,其中age小于30。有关迭代器以及其他参数和过滤器的更多详细信息是in the documentation.

如果要选择一个空间中的所有元组,请在不带参数的空间对象上调用pairs方法:

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,'position': 'Lead of Tarantool Solutions'}]
---
...

在以下SO问题中探索更多参数和过滤器in documentation

,

为什么不做简单的事情?

box.schema.space.create "users"
box.space.users:format { { name="id",type="unsigned"} --[[and so on]] }
box.space.users:create_index("primary",{ sequence = true })
box.space.users:insert { nil,"John Doe",20 }
box.space.users:insert { nil,"Jon Snow",20 }

local all_users = box.space.users:select()