我使用python-arango作为ArangoDB的驱动程序,似乎没有UPSERT
界面。
我打算用python-arango标记这个,但我没有足够的rep来创建新标签。
我正在管理类似下面显示的功能,但我想知道是否有更好的方法来做到这一点?
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
字段,因为这不是问题的必要条件。
使用upsert
的关键是从应用程序中保存数据库往返,这是因为try/except
方法不太好。
但是,当时the ArangoDB HTTP-API不提供upsert,因此python-arango无法为您提供API。
您应该使用AQL query to upsert your document来实现此目的:
UPSERT { name: "test" }
INSERT { name: "test" }
UPDATE { } IN users
LET opType = IS_NULL(OLD) ? "insert" : "update"
RETURN { _key: NEW._key, type: opType }
难道你不能只使用这样的东西吗?
try:
collection.update({'_key': xxx, ...})
except db_exception.DocumentInsertError as e:
document.insert({'_key': xxx, ...})