【发布时间】:2018-02-06 21:47:04
【问题描述】:
我正在使用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')))
注意,在我的情况下,我确保所有文档在插入之前都具有 _key 的值,因此我可以假设这成立。如果其他人想使用它,请相应地修改。
编辑:删除了对_id 字段的使用,因为这对问题来说并不重要。
【问题讨论】:
-
FWIW,id 总是
{collection}/{_key},所以你应该只需要设置_key。我知道的唯一其他方法是使用 AQL 并在查询中使用 upsert:docs.arangodb.com/3.0/AQL/Operations/Upsert.html -
谢谢,@AndrewGrothe,这是一个很好的观点。在更新插入之前,我在模型之间的逻辑中使用了
_id值,并认为我应该指出它以防有人天真地尝试实现我的函数的副本。 (在上面的示例中,它仅用于记录错误,所以我想我可以在问题中省略它。)
标签: python-3.x arangodb python-arango