gpt4 book ai didi

sql - 如何从 tarantool 中选择有限数量的记录,就像 SQL 中的 SELECT LIMIT 一样?

转载 作者:行者123 更新时间:2023-12-02 03:14:29 25 4
gpt4 key购买 nike

我想在 Tarantool 空间上执行选择,使用过滤和限制结果,就像我可以使用简单的 SQL 查询一样“从年龄 > 33 LIMIT 1 的用户中选择*”。我怎样才能实现这一目标?

最佳答案

可以使用 Lua 和 SQL 来完成。

1) 这是 Lua 中的示例。假设我们有一个名为“users”的空间,其中包含“name”、“surname”、“age”字段。首先,让我们创建并填充空间:

$ tarantool
Tarantool 2.1.1-465-gbd1a43fbc
type 'help' for interactive help
tarantool> box.cfg({})
...
2019-06-10 14:51:33.827 [47393] main/102/interactive I> ready to accept requests
...
2019-06-10 14:51:33.827 [47393] main/104/checkpoint_daemon I> scheduled next checkpoint for Mon Jun 10 16:14:44 2019
---
...

tarantool> s = box.schema.space.create('users', {temporary=true})
---
...

tarantool> box.space.users:format({{'id','unsigned'},{'name','string'},{'surname','string'},{'age','unsigned'}})
---
...

tarantool> s:create_index('primary', {unique = true, parts = {1, 'unsigned'}})
---
- unique: true
parts:
- type: unsigned
is_nullable: false
fieldno: 1
id: 0
space_id: 512
name: primary
type: TREE
...

tarantool> s:insert({1,'Pasha','Yudin',33})
---
- [1, 'Pasha', 'Yudin', 33]
...

tarantool> s:insert({3,'Kostya','Nazarov',34})
---
- [2, 'Kostya', 'Nazarov', 34]
...

tarantool> s:insert({2,'Oleg','Babin',23})
---
- [3, 'Oleg', 'Babin', 23]
...

tarantool> s:insert({4,'Roma','Babaev',34})
---
- [4, 'Roma', 'Babaev', 34]
...

让我们从空间中选择所有记录:

tarantool> s:select()
---
- - [1, 'Pasha', 'Yudin', 33]
- [2, 'Kostya', 'Nazarov', 23]
- [3, 'Oleg', 'Babin', 34]
- [4, 'Roma', 'Babaev', 34]
...

接下来,我们选择所有年龄超过 33 岁的用户。 LuaFun可以使用库:

tarantool> fun = require('fun')
---
...

tarantool> fun.iter(s:select()):filter(function (tuple) return tuple.age > 33 end):totable()
---
- - [3, 'Oleg', 'Babin', 34]
- [4, 'Roma', 'Babaev', 34]
...

但正如 @AlexanderTurenko 下面提到的,最好使用 pairs 迭代器,以免将额外的元组加载到内存中:

tarantool> s:pairs():filter(function (tuple) return tuple.age > 33 end):totable()
---
- - [3, 'Oleg', 'Babin', 34]
- [4, 'Roma', 'Babaev', 34]
...

此外,此变体更短且更具可读性。

最后,让我们只选择一个符合条件的用户,这相当于 SQL 查询“SELECT * FROM users WHEREage > 33 LIMIT 1”:

tarantool> s:pairs():filter(function (tuple) return tuple.age > 33 end):take_n(1):totable()
---
- - [3, 'Oleg', 'Babin', 34]
...

2) 从 Tarantool 2.0 开始,可以做到 using SQL (前提是你有空格格式):

box.execute('select * from users where age > 33 limit 1;')

关于sql - 如何从 tarantool 中选择有限数量的记录,就像 SQL 中的 SELECT LIMIT 一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56584050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com