【问题标题】:UPSERT with python-arango driver for ArangoDBUPSERT 与用于 ArangoDB 的 python-arango 驱动程序
【发布时间】:2018-02-06 21:47:04
【问题描述】:

我正在使用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 字段的使用,因为这对问题来说并不重要。

【问题讨论】:

  • FWIW,id 总是{collection}/{_key},所以你应该只需要设置_key。我知道的唯一其他方法是使用 AQL 并在查询中使用 upsert:docs.arangodb.com/3.0/AQL/Operations/Upsert.html
  • 谢谢,@AndrewGrothe,这是一个很好的观点。在更新插入之前,我在模型之间的逻辑中使用了_id 值,并认为我应该指出它以防有人天真地尝试实现我的函数的副本。 (在上面的示例中,它仅用于记录错误,所以我想我可以在问题中省略它。)

标签: python-3.x arangodb python-arango


【解决方案1】:

使用upsert 的目的是节省应用程序的数据库往返,这就是try/except 方法不太好。

但是,目前 the ArangoDB HTTP-API 不提供 upsert,因此 python-arango 无法为您提供 API。

您应该改用AQL query to upsert your document 来实现此目的:

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

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

【讨论】:

  • 感谢您为try/except 不是一个好方法添加了很好的解释。
【解决方案2】:

你不能用这样的东西吗?

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

【讨论】:

    猜你喜欢
    • 2021-08-24
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多