gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:01:05 25 4
gpt4 key购买 nike

我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com