繁体   English   中英

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

[英]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 }

通过python-arango的db.aql.execute

你不能只用这样的东西吗?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM