【问题标题】:How to move document between 2 different collection in Firestore?如何在 Firestore 中的 2 个不同集合之间移动文档?
【发布时间】:2021-05-03 16:35:04
【问题描述】:

我正在尝试在 Firestore 中将文档从一个集合“移动”到另一个集合。这意味着复制/粘贴文档,然后删除原件。我正在尝试使用 Python 实现这个服务器端。

我知道我应该使用事务,所以我实现了一个。当我运行脚本时,我可以在 Firestore 中看到我所针对的文档确实已从旧集合中删除,并且已在新集合中创建了一个新文档。

成功了吗?

如何测试我编码的交易?我对事务逻辑本身有点困惑。特别是,我不确定我是如何在我的事务中实现“复制部分”的(见下文)。为什么 get() 和 delete() 有事务的引用而 set() 没有?

到目前为止,这是我的代码,使用事务来移动文档:

from google.cloud import firestore
import time

@firestore.transactional
def move_in_transaction(transaction, doc1, doc2):
    # get the data
    doc = doc1.get(transaction=transaction)
    if doc.exists:
        print(f'Document data: {doc.to_dict()}')
    else:
        print(u'No such document!')

    # copy the data
    doc2.set(doc.to_dict())
    # delete the original
    transaction.delete(doc.reference)


def main():
    db = firestore.Client()
    transaction = db.transaction()
    doc1 = db.collection(u'AAA').document(u'111')
    doc2 = db.collection(u'BBB').document(u'111')

    transaction_attempts = 0
    while True:
        try:
            # apply transaction
            move_in_transaction(transaction, doc1, doc2)
            print("Successfully applied transaction")
            break
        except Exception as e:
            print(f"Could not apply transaction. Error: {e}")
            time.sleep(5)
            transaction_attempts += 1
            if transaction_attempts > 10:
                print(f"Stop trying transactions")
                exit()

它完成了这项工作,但我不确定事务本身中的“复制部分”。

【问题讨论】:

    标签: python firebase google-cloud-firestore


    【解决方案1】:

    现在您的doc2.set(doc.to_dict()) 发生在交易之外。这意味着doc1 可以被修改(并且事务重试),但doc2 已经被写入。最终状态可能是正确的(因为doc2 将在事务重试时更新),但您将暂时处于doc1doc2 都存在的状态,并且具有不同的内容。正如我对您之前问题的回答:这是否可以接受由您决定。

    如果您希望写入doc2 作为事务的一部分,SDK 中也有一个transaction.set(...) 方法。看 https://googleapis.dev/python/firestore/latest/transaction.html

    【讨论】:

    • 好的,知道了!我将 set() 更改为:transaction.set(doc2, doc.to_dict())。谢谢@Frank
    猜你喜欢
    • 2021-05-02
    • 2020-01-21
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    相关资源
    最近更新 更多