python - 从列表 rethinkdb ~python 更新特定数据

标签 python rethinkdb

我的 rethinkdb 中有这样的数据结构:

{
    "id":"123",
    "otherId":"asd",                <== based on this
    "list": [
        {
            "id":"a",
            "list_id":"1",          <== and based on this
            "status":"available"    <== update this
        },
        {
            "id":"b",
            "list_id":"2",
            "status":"available"
        },
        {
            "id":"c",
            "list_id":"3",
            "status":"available"
        },
        {
            "id":"d",
            "list_id":"4",
            "status":"available"
        }
    ]
}

如果我想更新 list_id = 1 的状态,在 python 中该怎么做?

我尝试这样做:

r.db('mydb').table('mytable').filter(r.row['Otherid'].eq("asd"))['list'].nth(0).default([]).filter(lambda doc: doc['list_id'] == "1").nth(0).default([]).update({"status":"offline"}).run()

但它给我带来错误rethinkdb.errors.ReqlQueryLogicError:预期类型选择但发现DATUM

更新

我无法使用 id(主键)进行查询,因为未给出数据。

我也尝试过这种方法:

currentData = r.db('myDb').table('myTable') \
        .filter(r.row['otherId'].eq("asd"))['list'].nth(0).default([]) \
        .filter(lambda doc: doc['list_id'] == "1").run(con, time_format='raw')

currentData["status"] = "offline"

r.db('mydb').table('mytable').filter(r.row['otherId'].eq("asd"))['list'].nth(0).default([]) \
        .update(lambda row: row.merge({'list': row['list'].map(lambda row2: r.branch(row2['list_id'].eq("1"), currentData, row2))})) \
        .run(con, time_format='raw')

但它附加新数据而不是 udpdate

谢谢...

最佳答案

您需要使用map()merge()。像这样的事情:

r.table("mytable") \
 .filter(r.row['otherId'] == "asd") \
 .update({
     "list": r.row["list"].map(lambda item: item.merge(
         r.branch(item["list_id"] == "1", {"status": "offline"}, {})))
     })

我还建议在表中使用索引和 get_all() 而不是 filter()

如果 list_ididlist 键下的数组中始终是唯一的,您也可以只使用一个对象(由唯一的 id)而不是数组,让您的生活更轻松。

关于python - 从列表 rethinkdb ~python 更新特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43846267/

相关文章:

python - 在 pygame 中暂停游戏和用户输入

python - VIM + Python - "gd"命令无法正常工作

python - Numpy - 导入错误 : cannot import name _distributor_init

rethinkdb - 我应该明确关闭 RethinkDB 连接吗?

performance - RethinkDB 更改提要性能 : architectural advice?

javascript - 我应该如何向 koa 后端发送 GET 请求以返回条件结果?

python - 将 Pandas 数据框 reshape 为与重复行一样多的列

python - 有人可以告诉我算法的名称(如果存在)或告诉我如何找到它

node.js - 与 deepstream.io 记录服务器端交互

java - 检索表名列表