如何用Python向RethinkDB的嵌套数组中追加元素
在RethinkDB嵌套数组中追加元素的解决方案
问题说明
已实现通过Python向RethinkDB的vendors数组添加新供应商,但现在需要给已有供应商的价格列表追加新的价格数据。
添加新供应商的可用代码
newData = {vendor: [{"salePrice": price, "available": available, "timestamp": r.now()}]} r.table('UPC').get(uid).update({"vendors": r.row["vendors"].append(newData)}).run(conn)
当前数据库结构
{ "id": "049a9b69-3378-4e67-98ce-7c76c4feb2f7", "name": "5-Year Protection Plan - Geek Squad", "upc": "400010179442", "vendors": [ { "Best Buy": [ { "available": false, "salePrice": 309.99, "timestamp": "Wed Jul 12 2023 12:09:58 GMT+00:00" } ] }, { "Target": [ { "available": false, "salePrice": 309.99, "timestamp": "Wed Jul 12 2023 12:10:22 GMT+00:00" } ] } ] }
预期数据库结构
{ "id": "049a9b69-3378-4e67-98ce-7c76c4feb2f7", "name": "5-Year Protection Plan - Geek Squad", "upc": "400010179442", "vendors": [ { "Best Buy": [ { "available": false, "salePrice": 309.99, "timestamp": "Wed Jul 12 2023 12:09:58 GMT+00:00" } ] }, { "Target": [ { "available": false, "salePrice": 309.99, "timestamp": "Wed Jul 12 2023 12:10:22 GMT+00:00" }, { "available": false, "salePrice": 307.96, "timestamp": "Wed Jul 13 2023 12:10:22 GMT+00:00" } ] } ] }
尝试过的方法及错误
尝试1
newData = {"salePrice": price, "available": available, "timestamp": r.now()} r.table('UPC').get(uid).update({"vendors": r.row["vendors"][vendor].append(newData)}).run(conn)
尝试2
newData = {"salePrice": price, "available": available, "timestamp": r.now()} r.table('UPC').get(uid).update({"vendors": {vendor:[r.row[vendor].append(newData)]}}).run(conn)
尝试3
newData = {"salePrice": price, "available": available, "timestamp": r.now()} r.table('UPC').get(uid).update({"vendors": {vendor: r.row[vendor].append(newData)}}).run(conn)
以上尝试均返回错误:
'first_error': 'No attribute `Target` in object'
正确解决方案
问题出在vendors是数组结构,每个元素是仅含单个供应商键的对象,无法直接通过r.row[vendor]访问。需要遍历数组找到目标供应商,再追加价格数据:
# 构造新的价格数据 new_price_data = {"salePrice": price, "available": available, "timestamp": r.now()} # 目标供应商名称 target_vendor = "Target" # 更新语句 r.table('UPC').get(uid).update({ "vendors": r.row["vendors"].map(lambda vendor_item: # 分支判断:当前元素是否包含目标供应商 r.branch( vendor_item.has_fields(target_vendor), # 包含则追加新价格数据到对应数组 {target_vendor: vendor_item[target_vendor].append(new_price_data)}, # 不包含则保持原元素不变 vendor_item ) ) }).run(conn)
代码说明
- 使用
map遍历vendors数组中的每个供应商对象 r.branch实现条件判断:通过has_fields检查当前对象是否包含目标供应商的键- 匹配时,将新价格数据追加到该供应商对应的价格数组;不匹配时直接返回原对象,保证其他供应商数据不受影响
内容的提问来源于stack exchange,提问作者Charles Beyor
相关产品推荐
相关产品推荐

