2
1

More than 3 years have passed since last update.

【Firestore】Rubyでコレクションをwhere条件で抽出してレコード削除

Last updated at Posted at 2020-09-05

概要

RubyでFirestoreのAPIを使用する際、指定したコレクションのうちwhere条件に当てはまるものだけ削除したい場合どうすればいいのか、というのをまとめました。

前提など

  • RubyでFirestoreのAPIを使用するため環境設定やクエリの投げ方などは、こちらのドキュメントやRailsからFirestoreをいじりたいを参考にしてます。
  • 今回はbatchの仕組みを使用します。batchでの更新は500件が限界だそうなので、その点も考慮してみます。JavaScriptでの実装ですがFirestoreでCollectionを削除するが参考になります。
  • Rubyでのbatchの仕様はこちらのドキュメントを参考にしています。

実装サンプル

sample.rb
def delete_sample
  # firestoreオブジェクトの取得
  firestore = Google::Cloud::Firestore.new
  # 削除対象のdoc配列格納用
  doc_array = []
  # コレクションの取得
  col_ref = firestore.col 'sample_collection'
  # コレクションの抽出条件
  query = col_ref.where 'category', '==', 'test'
  query.get do |r|
    # 対象のdocを配列に格納
    doc_array.push r.ref
  end
  # 500個までしか削除できないことを考慮
  document_index = 0
  batch_index = 0
  # バッチで削除
  while document_index < doc_array.size
    firestore.batch do |b|
      # 501個目のindexで中断
      break if batch_index == 500

      b.delete doc_array[document_index]
      document_index += 1
      batch_index += 1
    end
    batch_index = 0
  end
end

2
1
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
1