【发布时间】:2021-08-06 19:12:15
【问题描述】:
tl;dr 如何在测试副本集上对单操作读取事务启用读取首选项 SECONDARY?
我已经从 MongoDB deploy replica set for testing 创建了一个 MongoDB 副本集。
然后尝试从MongoDB Transactions 进行简单的单文档事务,我只更改了一些内容,例如将读取偏好设置为辅助。
# Step 1: Define the callback that specifies the sequence of operations to perform inside the transactions.
def callback(session):
collection_one = session.client.mydb1.foo
# Important:: You must pass the session to the operations.
collection_one.find_one({'id': 0}, session=session)
# Step 2: Start a client session.
with client.start_session() as session:
# Step 3: Use with_transaction to start a transaction, execute the callback, and commit (or abort on error).
session.with_transaction(
callback, read_concern=ReadConcern('snapshot'), # <- changed from 'local' to 'snapshot'
write_concern=wc_majority,
read_preference=ReadPreference.SECONDARY) # <- changed from PRIMARY to SECONDARY
我收到以下错误
...
pymongo.errors.InvalidOperation: read preference in a transaction must be primary, not: Secondary(tag_sets=None, max_staleness=-1, hedge=None)
如果我更改为阅读偏好 PRIMARY,它可以正常工作。 如果读取偏好必须是主要的,那么拥有这个选项根本没有任何意义......
我做错了什么或理解不正确?这似乎很基本,但 IMO 文档没有解释这一点。
【问题讨论】:
-
您期望事务中的二次读取会有什么行为?
-
我期望正常读取,即我从特定文档接收数据。只要是有效的读取,它就可以是过时的读取。我不再研究为什么事务不允许我从辅助读取。我相信问题可能来自收藏。不确定。
标签: python mongodb mongodb-replica-set