Python 3.x 使用ArangoDB的python arango驱动程序升级

Python 3.x 使用ArangoDB的python arango驱动程序升级,python-3.x,arangodb,python-arango,Python 3.x,Arangodb,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 a

我正在使用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')))
注意在我的例子中,我确保所有文档在插入之前都有一个
\u key
的值,因此我可以假设这是有效的。如果其他人想使用此功能,请相应地修改


编辑:删除了
\u id
字段的使用,因为这对问题不重要。

您不能使用类似的内容吗

try:
    collection.update({'_key': xxx, ...})
except db_exception.DocumentInsertError as e:
    document.insert({'_key': xxx, ...})

使用
upsert
的要点是保存来自应用程序的数据库往返,这是因为
try/except
方法没有那么好

然而,目前还没有提供升级,因此python arango无法为您提供API

相反,您应该使用以下方法来实现这一点:

UPSERT { name: "test" }
    INSERT { name: "test" }
    UPDATE { } IN users
LET opType = IS_NULL(OLD) ? "insert" : "update"
RETURN { _key: NEW._key, type: opType }

通过

FWIW,id始终是
{collection}/{u key}
,因此您只需设置
\u key
。我知道的唯一其他方法是在查询中使用AQL和upsert:谢谢,@AndrewGrothe,这是一个很好的观点。在升级之前,我在模型之间的逻辑中使用了
\u id
值,我认为应该指出这一点,以防有人天真地试图实现我函数的副本。(在上面的示例中,它只用于记录错误,因此我想我可以在问题中忽略它。)感谢您添加了关于为什么
try/except
不是一个好方法的良好解释。