带有用于 ArangoDB 的 python-arango 驱动程序的 UPSERT

Tho*_*ger 5 python-3.x arangodb python-arango

我使用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')))
Run Code Online (Sandbox Code Playgroud)

请注意,在我的情况下,我确保所有文档都具有_key插入之前和之前的值,因此我可以假设这是成立的。如果其他人想使用它,请相应地修改。

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

dot*_*art 2

使用的要点upsert是保存来自应用程序的数据库往返,这就是该try/except方法不太好的原因。

然而,目前ArangoDB HTTP-API不提供更新插入,因此 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 }
Run Code Online (Sandbox Code Playgroud)

通过python-arango s db.aql.execute-interface