首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有python驱动程序的ArangoDB UPSERT

带有python驱动程序的ArangoDB UPSERT
EN

Stack Overflow用户
提问于 2017-08-29 12:23:15
回答 3查看 1.2K关注 0票数 5

我正在使用python-arango作为ArangoDB的驱动程序,而且似乎没有UPSERT接口。

我打算用python-arango,标记它,但是我没有足够的代表来创建新的标记。

我正在管理类似于下面所示的函数,但是我想知道是否有更好的方法来做到这一点?

代码语言:javascript
复制
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')))

注意到,在我的例子中,我确保所有文档在插入之前和插入之前都有一个值,因此我可以假设这是成立的。如果其他人想要使用这个,相应地进行修改。

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-02-26 14:06:45

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

然而,目前ArangoDB HTTP并不提供高端服务,因此python无法为其提供API。

相反,您应该使用重新插入文档的AQL查询来实现这一点:

代码语言:javascript
复制
UPSERT { name: "test" }
    INSERT { name: "test" }
    UPDATE { } IN users
LET opType = IS_NULL(OLD) ? "insert" : "update"
RETURN { _key: NEW._key, type: opType }

通过-interface

票数 2
EN

Stack Overflow用户

发布于 2022-04-22 14:26:28

如果您使用的是python-arango,您应该能够执行以下操作:

代码语言:javascript
复制
collection.insert({'_key': xxx, ...}, overwrite_mode='replace')

代码语言:javascript
复制
collection.insert({'_key': xxx, ...}, overwrite_mode='update')
代码语言:javascript
复制
 :param overwrite_mode: Overwrite behavior used when the document key
            exists already. Allowed values are "replace" (replace-insert) or
            "update" (update-insert). Implicitly sets the value of parameter
            **overwrite**.
票数 1
EN

Stack Overflow用户

发布于 2017-09-27 22:26:18

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

代码语言:javascript
复制
try:
    collection.update({'_key': xxx, ...})
except db_exception.DocumentInsertError as e:
    document.insert({'_key': xxx, ...})
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45939062

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档