kapieciiのブログ

日々学んだことを残しておくためのブログです。このブログはGoogle Analyticsを利用しています。

Cloud Firestore入門。Pythonから読み書きと運用周り調査

所用があり、Cloud Firestoreについて調べたので、メモを残しておきます。

目次

読み書きサンプル(Python

まずは機能を知るために、読み書きを試してみます。
こちらを見ながら進めます。

firebase.google.com

プロジェクトの作成

検証用のプロジェクトを追加

f:id:kapiecii:20190822231459p:plain

プロジェクト名を入力

f:id:kapiecii:20190822231631p:plain

検証用プロジェクトなのでアナリティクス不要

f:id:kapiecii:20190822231830p:plain

データベースの作成

Database --> データベースの作成

f:id:kapiecii:20190822231941p:plain

今回は検証なのでテストモード

f:id:kapiecii:20190822232105p:plain

ロケーションを指定

f:id:kapiecii:20190822232208p:plain

クライアント用ライブラリインストール

ウェブ、iOSJava Android、 Kotlin AndroidJavaPython、Node.js、Go、PHPC#Rubyが選択できます。 今回はPythonを使ってみます。

「pipenv」の使い方については、こちらをご参照ください。

kapiecii.hatenablog.com

$ pipenv --three
$ pipenv install firebase-admin
$ pipenv shell

SDKの環境設定

firebase.google.com

設定-->ユーザーと権限

f:id:kapiecii:20190822232456p:plain

サービスアカウントのリンクをクリック

f:id:kapiecii:20190822232702p:plain

新しい秘密鍵の生成

f:id:kapiecii:20190822232932p:plain

秘密鍵環境変数に設定

$ export GOOGLE_APPLICATION_CREDENTIALS="{秘密鍵jsonのパス}"

データの書き込み、読み出し

サンプルコード

$ cat sample.py 
import firebase_admin
from firebase_admin import firestore

firebase_admin.initialize_app()

db = firestore.client()

doc_ref = db.collection(u'users').document(u'alovelace')
doc_ref.set({
    u'first': u'Ada',
    u'last': u'Lovelace',
    u'born': 1815
})

doc_ref = db.collection(u'users').document(u'aturing')
doc_ref.set({
    u'first': u'Alan',
    u'middle': u'Mathison',
    u'last': u'Turing',
    u'born': 1912
})

users_ref = db.collection(u'users')
docs = users_ref.get()

for doc in docs:
    print(u'{} => {}'.format(doc.id, doc.to_dict()))
$ python sample.py 
sample.py:28: DeprecationWarning: 'Collection.get' is deprecated:  please use 'Collection.stream' instead.
  docs = users_ref.get()
alovelace => {'first': 'Ada', 'last': 'Lovelace', 'born': 1815}
aturing => {'first': 'Alan', 'last': 'Turing', 'born': 1912, 'middle': 'Mathison'}

ログについて

Cloud Firestoreにデータを読み書きしてみましたが、Firebase ConsoleやCLIツールで、ログを確認する機能を見つけることができませんでした。

$ firebase 
Usage: firebase [options] [command]

Options:
  -V, --version                                   output the version number
  -P, --project <alias_or_project_id>             the Firebase project to use for this command
  -j, --json                                      output JSON instead of text, also triggers non-interactive mode
  --token <token>                                 supply an auth token for this command
  --non-interactive                               error out of the command instead of waiting for prompts
  --interactive                                   force interactive shell treatment even when not detected
  --debug                                         print verbose debug output and keep a debug log file
  -h, --help                                      output usage information

Commands:
  auth:export [options] [dataFile]                Export accounts from your Firebase project into a data file
  auth:import [options] [dataFile]                import users into your Firebase project from a data file(.csv or .json)
  database:get [options] <path>                   fetch and print JSON data at the specified path
  database:instances:create <instanceName>        create a realtime database instance
  database:instances:list                         list realtime database instances
  database:profile [options]                      profile the Realtime Database and generate a usage report
  database:push [options] <path> [infile]         add a new JSON object to a list of data in your Firebase
  database:remove [options] <path>                remove data from your Firebase at the specified path
  database:set [options] <path> [infile]          store JSON data at the specified path via STDIN, arg, or file
  database:settings:get [options] <path>          read the realtime database setting at path
  database:settings:set [options] <path> <value>  set the realtime database setting at path.
  database:update [options] <path> [infile]       update some of the keys for the defined path in your Firebase
  deploy [options]                                deploy code and assets to your Firebase project
  emulators:exec [options] <script>               start the local Firebase emulators, run a test script, then shut down the emulators
  emulators:start [options]                       start the local Firebase emulators
  experimental:functions:shell [options]          launch full Node shell with emulated functions. (Alias for `firebase functions:shell.)
  firestore:delete [options] [path]               Delete data from Cloud Firestore.
  firestore:indexes [options]                     List indexes in your project's Cloud Firestore database.
  functions:config:clone [options]                clone environment config from another project
  functions:config:get [path]                     fetch environment config stored at the given path
  functions:config:set [values...]                set environment config with key=value syntax
  functions:config:unset [keys...]                unset environment config at the specified path(s)
  functions:delete [options] [filters...]         delete one or more Cloud Functions by name or group name.
  functions:log [options]                         read logs from deployed functions
  functions:shell [options]                       launch full Node shell with emulated functions
  help [command]                                  display help information
  hosting:disable [options]                       stop serving web traffic to your Firebase Hosting site
  init [feature]                                  setup a Firebase project in the current directory
  list                                            list the Firebase projects you have access to
  login [options]                                 log the CLI into Firebase
  login:ci [options]                              generate an access token for use in non-interactive environments
  logout                                          log the CLI out of Firebase
  open [link]                                     quickly open a browser to relevant project resources
  serve [options]                                 start a local server for your static assets
  setup:emulators:database                        downloads the database emulator
  setup:emulators:firestore                       downloads the firestore emulator
  setup:web                                       display this project's setup information for the Firebase JS SDK
  target [type]                                   display configured deploy targets for the current project
  target:apply <type> <name> <resources...>       apply a deploy target to a resource
  target:clear <type> <target>                    clear all resources from a named resource target
  target:remove <type> <resource>                 remove a resource target
  tools:migrate [options]                         ensure your firebase.json format is up to date
  use [options] [alias_or_project_id]             set an active Firebase project for your working directory

運用上「いつ、誰が、何をしたのか」を知りたい場面は多いと思います。
運用事例について調べたところ、下記の記事でログ取得について記載されていました。
Firestoreには誰がどんな操作をしたか、ログを残す機能が無いようです。

techlife.cookpad.com

こちらの記事では、「Cloud Firestoreを使った場合のログ運用」だけでなく、「Cloud Firestoreのデータを検索する」、「Cloud FirestoreとCloud Functionsを連携させた場合のパフォーマンス改善」など、とても参考になる知見が多数公開されていました。
知見を共有いただいてありがとうございます。

バックアップについて

運用することを想定した場合、バックアップをとっておきたいです。
2018年8月頃から「gcloud」コマンドでバックアップとリストアができるようになったようです。
バックアップするには、課金を有効にする必要があり、バックアップデータは、Google Cloud Storageのbucketに保存されるようです。

medium.com

firebase.google.com

以上、Cloud Firestore入門と、気になった点のメモ書きでした。

kapieciiのブログについてお問い合わせがある場合、下記のフォームからご連絡をお願い致します。
お問い合わせはこちら