繁体   English   中英

RethinkDB-是否有更好的方法在嵌套数组上执行此非原子更新?

[英]RethinkDB - is there a better way of doing this non-atomic update on a nested array?

我在RethinkDB数据库中有两个表-“联盟”和“玩家”,其文档结构如下:

播放器

{
  id: 1,
  name: "Bob",
  email: "bob@bob.com"
}

联盟

{
  id: 1,
  name: "L1",
  standings: [{
    "player_id": 1,
    "position": 1
  },{
    "player_id": 2,
    "position": 2
  }]
}

我要实现的是删除播放器时,有一个很简单的ReQL查询来删除播放器:

r.table("players").get(1).delete().run(conn, callback);

但是我还需要将该球员从他们所参加的所有联赛中删除,然后更新该联赛中所有其他球员的位置,以使他们再次变得有序。

这是我必须删除ID为“ 2”的玩家的查询:

r.table("leagues").getAll(2, { index: "player_id" }).update({
  standings: r.row("standings").filter(function(standing) {
    return standing("player_id").ne(2)
  }).map(function(standing) {
    return r.branch (
      standing("position").gt(
        r.table("leagues").getAll(2, { index: "player_id" }).nth(0)("standings").filter(function(s) {
            return s("player_id").eq(2)
            }).nth(0)("position")
      ),
      standing.merge({ position: standing("position").sub(1) }),
      standing
    )
  })
}, {
  nonAtomic: true 
})

这很有效,它将删除已删除的播放器,然后重新排列其余播放器的位置以填补空白并再次变为连续播放。

我的问题是,有没有更好的方法? 我不必将查询指定为nonAtomic的地方吗? 我只能认为我需要先做一些单独的查询,才能找到要删除的播放器的位置,以便可以将其作为变量而不是子查询传递,因为我认为那是那一部分使这种非原子性。

干杯

我认为排名总是与数组中的位置匹配?

如果是这样,您可以这样写:

r.table('leagues').getAll(2, {index: 'player_id'}).update(function(row) {
  return {
    standings: row('standings').filter(function (standing) {
      return standing('player_id').ne(2);
    }.map(r.range(), function(standing, index) {
      return standing.merge({position: index.add(1)});
    })
  };
});

如果没有,您可以这样写:

r.table('leagues').getAll(2, {index: 'player_id'}).update(function(row) {
  return row('standings').filter(function (standing) {
    return standing('player_id').eq(2);
  }).nth(0)('position').do(function(pos) {
    return {
      standings: row('standings').filter(function (standing) {
        return standing('player_id').ne(2);
      }).map(function(standing) {
        return r.branch(
          standing('position').gt(pos),
          standing.merge({position: standing('position').sub(1)}),
          standing);
      })
    };
  });
});

{排行榜:row('standings')。filter(function(standing){return Standing('player_id')。ne(2)} .map(r.range(),function(standing,index){return Standing.merge ({position:index.add(1)});})};})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM