如何将数组解压缩到变量中

时间:2016-05-22 11:00:57

标签: rethinkdb rethinkdb-python

我们说我们有这份文件:

doc = {'foo': 1, 'bar': 2, id: 123}

我怎么能这样做,我可以拥有一对foo和bar值,id并将它们分配给2个变量?我需要这个,以便我可以在复杂的查询中使用这些变量,而无需多次复制/粘贴相同的reql命令。

这就是我的尝试:

(
    r.expr(doc) # doc as input
    .do(lambda d: [
        # create the pair
        [d['id'], r.uuid(d['id'].coerce_to('string'))],
        # create the "values"
        d.without('id').values()
    ])
    .do(lambda x, y:  # unpacking should happen here
        # x should be the pair
        # y should be the values of foo and bar

        r.branch(
            # do something with x,
            # use y here,
            ...)
    )
    .map(lambda z:
        # use also x and y here
        # etc...
    .run(conn)
)

但我无法完成这项工作。 为了便于阅读,我们的想法是将值分配给要在查询中使用的变量。 有些想法?

1 个答案:

答案 0 :(得分:1)

您可以使用r.do在ReQL中绑定多个变量,例如:

r.expr(doc).do(lambda d: # doc as input
  r.do(
    [d['id'], r.uuid(d['id'].coerce_to('string'))],
    d.without('id').values(),
    lambda x, y:
      # x is the pair
      # y is the values of bar and foo
      ...))