我正在使用python-arango作为ArangoDB的驱动程序,而且似乎没有UPSERT接口。
我打算用python-arango,标记它,但是我没有足够的代表来创建新的标记。
我正在管理类似于下面所示的函数,但是我想知道是否有更好的方法来做到这一点?
def upsert_document(collection, document, get_existing=False):
"""Upserts given document to a collection. Assumes the _key field is already set in the document dictionary."""
try:
# Add insert_time to document
document.update(insert_time=datetime.now().timestamp())
id_rev_key = collection.insert(document)
return document if get_existing else id_rev_key
except db_exception.DocumentInsertError as e:
if e.error_code == 1210:
# Key already exists in collection
id_rev_key = collection.update(document)
return collection.get(document.get('_key')) if get_existing else id_rev_key
logging.error('Could not save document {}/{}'.format(collection.name, document.get('_key')))注意到,在我的例子中,我确保所有文档在插入之前和插入之前都有一个值,因此我可以假设这是成立的。如果其他人想要使用这个,相应地进行修改。
编辑:删除对_id字段的使用,因为这对问题并不重要。
发布于 2019-02-26 14:06:45
使用upsert的要点是保存来自应用程序的数据库往返,这是因为try/except方法不太好。
然而,目前ArangoDB HTTP并不提供高端服务,因此python无法为其提供API。
相反,您应该使用重新插入文档的AQL查询来实现这一点:
UPSERT { name: "test" }
INSERT { name: "test" }
UPDATE { } IN users
LET opType = IS_NULL(OLD) ? "insert" : "update"
RETURN { _key: NEW._key, type: opType }发布于 2022-04-22 14:26:28
如果您使用的是python-arango,您应该能够执行以下操作:
collection.insert({'_key': xxx, ...}, overwrite_mode='replace')或
collection.insert({'_key': xxx, ...}, overwrite_mode='update') :param overwrite_mode: Overwrite behavior used when the document key
exists already. Allowed values are "replace" (replace-insert) or
"update" (update-insert). Implicitly sets the value of parameter
**overwrite**.发布于 2017-09-27 22:26:18
你就不能用这样的东西吗?
try:
collection.update({'_key': xxx, ...})
except db_exception.DocumentInsertError as e:
document.insert({'_key': xxx, ...})https://stackoverflow.com/questions/45939062
复制相似问题