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

Update specific data from list rethinkdb ~python

我的 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: Expected type SELECTION but found 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"}, {})))
     })

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

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