LoginSignup
44
38

More than 5 years have passed since last update.

Cloud FirestoreのデータをPythonで取得する

Posted at

Cloud Firestoreに登録されているデータをPythonで取得する方法を紹介します。

環境

$ python -V
Python 3.5.2 :: Anaconda 4.2.0 (x86_64)

準備

ライブラリ

必要なライブラリをインストールします。

$ pip install firebase-admin
$ pip install google-cloud-firestore

認証ファイルをダウンロード

firebaseのコンソール画面を開きます。

Sign in - Google Accounts

プロジェクトの設定をクリックします。

20180616152619.png

サービスアカウントのタブを開きます。

20180616152631.png

Pythonにチェックをし、新しい秘密鍵の生成をクリックします。

20180616152645.png

秘密鍵(ファイル名:〜.json)がダウンロードできたか確認しましょう。

実装

usersコレクションのデータを取得してみます。

20180616152707.png

まずは必要なライブラリをインポートし、秘密鍵を読み込みます。

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

cred = credentials.Certificate("./〜.json") # ダウンロードした秘密鍵
firebase_admin.initialize_app(cred)

usersコレクションのデータを取得します。

db = firestore.client()
docs = db.collection('users').get()
for doc in docs:
    print(doc.to_dict())

条件を追加してデータを取得します。

query = db.collection('users').where('active', '==', True)
docs = query.get()
for doc in docs:
    print(doc.to_dict())

複数条件を設定します。

query = db.collection('users').where('active', '==', True).where('created_at', '>', datetime.datetime.now())
docs = query.get()
for doc in docs:
    print(doc.to_dict())

上記のように等価演算子(==)と範囲比較(<、<=、>、>=)を組み合わせる場合はカスタムインデックスを作成する必要があります。
インデックスを作成してない状態で実行するとエラーが発生します。

google.api_core.exceptions.FailedPrecondition: 400 The query requires an index. You can create it here: https://console.firebase.google.com/project/〜

表示されたURLに遷移するとインデックス作成画面に遷移しますので、そのままCreate indexをクリックしましょう。

20180616152726.png

まとめ

複合クエリの実行は癖ありますが、比較的簡単に実装できますね。

44
38
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
44
38