如何在RethinkDB中获取指定记录的上一条和下一条记录
使用rethinkdb-dash获取指定ID的相邻记录
假设你的数据存储在名为records的表中,目标记录ID为3,以下是获取其上一条和下一条记录的实现方案:
1. 基础查询(分别获取上/下一条)
先初始化rethinkdb-dash连接:
const r = require('rethinkdb-dash')({ host: 'localhost', port: 28015, db: '你的数据库名' });
获取上一条记录
查询ID小于目标ID的最大那条记录,适配ID不连续的场景:
r.table('records') .filter(r.row('id').lt(3)) .orderBy(r.desc('id')) .limit(1) .run() .then(prevRecord => console.log('上一条记录:', prevRecord)) .catch(err => console.error(err));
获取下一条记录
查询ID大于目标ID的最小那条记录:
r.table('records') .filter(r.row('id').gt(3)) .orderBy('id') .limit(1) .run() .then(nextRecord => console.log('下一条记录:', nextRecord)) .catch(err => console.error(err));
2. 合并查询(一次获取两条记录)
通过union合并两个查询,一次拿到上/下相邻记录:
r.union( r.table('records').filter(r.row('id').lt(3)).orderBy(r.desc('id')).limit(1), r.table('records').filter(r.row('id').gt(3)).orderBy('id').limit(1) ) .run() .then(neighbors => { const prev = neighbors.find(item => item.id < 3); const next = neighbors.find(item => item.id > 3); console.log('上一条:', prev, '\n下一条:', next); }) .catch(err => console.error(err));
补充说明
如果你的ID是连续自增的,可以直接用eq(3-1)和eq(3+1)简化查询,但上述通用方法更适配ID不连续(比如存在删除记录)的场景,能确保获取到真实有效的相邻记录。
内容的提问来源于stack exchange,提问作者Jay-R Joseph Gabunada
相关产品推荐
相关产品推荐

