2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

pymongo / motor でプライマリ読みを強制したいときのコード

2
Posted at

背景

クラスタ構成のmongodb(実際にはAWSのDocumentDB)に接続するアプリ。
セカンダリ読み優先の接続設定になっているときに、プライマリに書き込んだ値がセカンダリに反映されるまでのラグによって後続処理に失敗していた。

基本はセカンダリ読み、必要に応じてプライマリ読みに変えたいと思ったので調べて試してみた。

pymongoのマニュアルを読み込んでみる

choosing which member of a replica set to read from.

そのものな名前のマニュアルを発見。
ただ、最初のDB接続のときのお話なので、今回のケースには不適。

マニュアルを探し回ると、with_optionsメソッドを使うと良い様子。
Causally Consistent Reads

Causally Consistent Reads = 結果がちゃんと一貫性のある読み取り、なのでぴったり。

変更したコード

差分は以下のようになりました。

-        hoge_cursor = db.hoges.find(
+        db_primary = db.with_options( # 非アトミックなのでPrimaryから読み出し
+            read_preference=pymongo.read_preferences.Primary())
+        hoge_cursor = db_primary.hoges.find(

マニュアルではcollectionレベルで切り替えていましたが、DBのレベルで書き換えたほうがコードの差分が読み取りやすかったのでちょっと変えています。

Databaseクラスのドキュメントにオプション詳細とサンプルがあるので、ほぼそのまま使えます。

pymongo.database.Database.with_options

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?