Mongodb Read preferences

☆樱花仙子☆ 提交于 2019-12-07 12:00:35

The read preferences are as follows:

  • PRIMARY: Queries are sent to the primary of the replica set.
  • PRIMARY_PREFERRED: Queries are sent to the primary if available, otherwise a secondary.
  • SECONDARY: Queries are distributed among secondaries. An error is raised if no secondaries are available.
  • SECONDARY_PREFERRED: Queries are distributed among secondaries, or the primary if no secondary is available.
  • NEAREST: Queries are distributed among all members.

So theres no specific one for the nearest secondary. You could achieve this by combining NEAREST and tag_sets and tagging the secondaries.

Then if the secondaries have been tagged {'secondaries': 1} you can read from the nearest secondary like so:

from pymongo import ReplicaSetConnection
from pymongo import ReadPreference

db = ReplicaSetConnection('localhost:27017', replicaSet='rs1')['my_db']
db.read_preference = ReadPreference.NEAREST
db.tag_sets = [{'secondaries': 1}]

Update:

You should note that if an election occurs and the topology of your replicaset changes then you'd have to manually change the tag_sets to represent the new secondaries.

This answer is very specific to my situation, because my nearest secondary is in the same region as my web server (as good as running on the same machine), so the data transfer would be insanely fast, plus I don't have to pay for bandwidth usage (which over the month might become significant considering the amount of data).

Otherwise the default value for 'secondary_acceptable_latency_ms' = 15ms. So it doesn't really matter.

So in case someone finds himself/herself in the same situation, this is what to do:

    from pymongo import ReplicaSetConnection
    from pymongo import ReadPreference

    db = ReplicaSetConnection('localhost:27017', replicaSet='rs1')['my_db']
    db.read_preference = ReadPreference.SECONDARY
    db.secondary_acceptable_latency_ms = 0.001

Thanks!!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!