[英]Difference between ArangoDB graph traversal results in arangosh vs arango http
[英]UPSERT with python-arango driver for ArangoDB
我使用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
字段的使用,因為這對於問題不是必需的。
使用upsert
的要點是從應用程序中保存數據庫往返,這是因為try/except
方法不太好。
但是,當時ArangoDB HTTP-API不提供upsert,因此python-arango不能為您提供API。
您應該改用AQL查詢來增補您的文檔以實現此目的:
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, ...})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.