サーバー クライアント ライブラリを使用して Cloud Firestore Standard エディションを使ってみる

このクイックスタートでは、Cloud Firestore Enterprise エディションを設定し、データを追加して、C#、Go、Java、Node.js、PHP、Python、Ruby のサーバー クライアント ライブラリを使用して、追加したデータを Firebase コンソールで表示する方法について説明します。

データベースへの完全アクセス権を備えた特権的サーバー環境を設定するには、これらのクライアント ライブラリを使用します。

Cloud Firestore データベースを作成する

  1. まだ Firebase プロジェクトを作成していない場合は作成します。Firebase コンソールで[プロジェクトを追加] をクリックし、画面上の指示に沿って、Firebase プロジェクトを作成するか、Google Cloud プロジェクトに Firebase サービスを追加します。

  2. Firebase コンソールでプロジェクトを開きます。左側のパネルで [ビルド] を展開し、[Firestore データベース] を選択します。

  3. [データベースを作成] をクリックします。

  4. データベースのロケーションを選択します。

    ロケーションを選択できない場合は、プロジェクトに「デフォルトの Google Cloud リソースのロケーション」がすでに設定されています。プロジェクトのリソースの一部(デフォルトの Cloud Firestore インスタンスなど)は、共通のロケーション依存関係を共有します。また、これらのロケーションは、プロジェクトの作成時またはこのロケーション依存関係を共有する別のサービスの設定時に設定できます。

  5. Cloud Firestore Security Rules の開始モードを選択します。

    テストモード

    モバイルおよびウェブ クライアント ライブラリを使用する場合に適していますが、すべてのユーザーがデータを読み書きできます。テストが終わったら、必ずデータのセキュリティ保護セクションを確認してください。

    ウェブ、Apple プラットフォーム、Android SDK を使用する場合は、テストモードを選択します。

    本番環境モード

    モバイルおよびウェブ クライアントからのすべての読み書きを拒否します。認証されたアプリケーション サーバー(C#、Go、Java、Node.js、PHP、Python、Ruby)は引き続きデータベースにアクセスできます。

    C#、Go、Java、Node.js、PHP、Python、または Ruby サーバー クライアント ライブラリを使用する場合は、本番環境モードを選択します。

    デフォルトの Cloud Firestore データベースには、Cloud Firestore Security Rules の初期セットが適用されます。プロジェクトに複数のデータベースを作成する場合は、データベースごとに Cloud Firestore Security Rules をデプロイできます。

  6. [作成] をクリックします。

Cloud Firestore を有効にすると、Cloud API Manager で API も有効になります。

開発環境を設定する

必要な依存関係とクライアント ライブラリをアプリに追加します。

Java
  1. アプリに Firebase Admin SDK を追加します。
    • Gradle を使用する:
      implementation 'com.google.firebase:firebase-admin:9.7.1'
    • Maven を使用する:
      <dependency>
        <groupId>com.google.firebase</groupId>
        <artifactId>firebase-admin</artifactId>
        <version>9.7.1</version>
      </dependency>
           
  2. 以下の手順に従い、ご使用の環境で適切な認証情報を使用して Cloud Firestore を初期化します。
Python
  1. Firebase Admin SDK を Python アプリに追加します。
    pip install --upgrade firebase-admin
  2. 以下の手順に従い、ご使用の環境で適切な認証情報を使用して Cloud Firestore を初期化します。
Node.js
  1. アプリに Firebase Admin SDK を追加します。
    npm install firebase-admin --save
  2. 以下の手順に従い、ご使用の環境で適切な認証情報を使用して Cloud Firestore を初期化します。
Go
  1. Go アプリに Firebase Admin SDK を追加します。
    go get firebase.google.com/go
  2. 以下の手順に従い、ご使用の環境で適切な認証情報を使用して Cloud Firestore を初期化します。
PHP
  1. Cloud Firestore サーバーのクライアント ライブラリ(Java、Node.js、Python、Go、PHP、C#、Ruby)は、認証に Google アプリケーションのデフォルト認証情報を使用します。
    • 開発環境から認証するには、JSON サービス アカウント キーファイルを指すように GOOGLE_APPLICATION_CREDENTIALS 環境変数を設定します。キーファイルは、API Console の認証情報ページで作成できます。
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • 本番環境では、Cloud Firestore で使用するプロジェクトと同じプロジェクトを使用して App Engine または Compute Engine でアプリケーションを実行する場合は、認証する必要はありません。それ以外の場合は、サービス アカウントの設定が必要です。
  2. PHP 用の gRPC 拡張機能をインストールして有効にします。この機能は、クライアント ライブラリを使用する場合に必要です。
  3. アプリに Cloud Firestore PHP ライブラリを追加します。
    composer require google/cloud-firestore
Ruby
  1. Cloud Firestore サーバーのクライアント ライブラリ(Java、Node.js、Python、Go、PHP、C#、Ruby)は、認証に Google アプリケーションのデフォルト認証情報を使用します。
    • 開発環境から認証するには、JSON サービス アカウント キーファイルを指すように GOOGLE_APPLICATION_CREDENTIALS 環境変数を設定します。キーファイルは、API Console の認証情報ページで作成できます。
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • 本番環境では、Cloud Firestore で使用するプロジェクトと同じプロジェクトを使用して App Engine または Compute Engine でアプリケーションを実行する場合は、認証する必要はありません。それ以外の場合は、サービス アカウントの設定が必要です。
  2. Gemfile でアプリに Cloud Firestore Ruby ライブラリを追加します。
    gem "google-cloud-firestore"
  3. 以下のようにして、Gemfile から依存関係をインストールします。
    bundle install

(省略可)Firebase Local Emulator Suite でプロトタイピングとテストを行う

モバイルのデベロッパー向けに、アプリが Cloud Firestore に対して書き込みと読み取りを行う方法を説明する前に、Cloud Firestore の機能のプロトタイピングとテストに使用できる一式のツールである Firebase Local Emulator Suite について紹介します。異なるデータモデルの試行や、セキュリティ ルールの最適化、あるいはバックエンドとのやり取りで費用対効果の高い方法の検出を行う場合は、ライブサービスをデプロイせずにローカルで作業できるようにすると、大きなメリットが得られます。

Cloud Firestore エミュレータは Local Emulator Suite の一部であり、これを使用すると、アプリはエミュレートしたデータベースのコンテンツや構成とやり取りできるほか、エミュレートされたプロジェクトのリソース(関数、他のデータベース、セキュリティ ルール)とも任意でやり取りできます。

いくつかの手順を実施するだけで、Cloud Firestore エミュレータを使用できます。

  1. アプリのテスト構成にコード行を追加して、エミュレータに接続します。
  2. ローカル プロジェクトのディレクトリのルートから、firebase emulators:start を実行します。
  3. 通常どおり、Cloud Firestore プラットフォーム SDK を使用してアプリのプロトタイプ コードから呼び出しを行います。

詳細な Cloud FirestoreCloud Functions に関するチュートリアルをご覧ください。Local Emulator Suite の概要もご覧ください。

Cloud Firestore を初期化する

Cloud Firestore のインスタンスを初期化します。

Java
Cloud Firestore SDK を初期化する方法は環境に応じて異なります。最も一般的な方法を以下に示します。完全なリファレンスについては、Admin SDK の初期化をご覧ください。
  • Google Cloud で初期化する
    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.cloud.firestore.Firestore;
    
    import com.google.firebase.FirebaseApp;
    import com.google.firebase.FirebaseOptions;
    
    // Use the application default credentials
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
    FirebaseOptions options = new FirebaseOptions.Builder()
        .setCredentials(credentials)
        .setProjectId(projectId)
        .build();
    FirebaseApp.initializeApp(options);
    
    Firestore db = FirestoreClient.getFirestore();
  • 各自のサーバーで初期化する

    各自のサーバーで Firebase Admin SDK を使用するには、サービス アカウントを使用します。

    Google Cloud コンソールで [IAM と管理] > [サービス アカウント] にアクセスします。新しい秘密鍵を生成し、JSON ファイルを保存します。次に、このファイルを使用して SDK を初期化します。

    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.cloud.firestore.Firestore;
    
    import com.google.firebase.FirebaseApp;
    import com.google.firebase.FirebaseOptions;
    
    // Use a service account
    InputStream serviceAccount = new FileInputStream("path/to/serviceAccount.json");
    GoogleCredentials credentials = GoogleCredentials.fromStream(serviceAccount);
    FirebaseOptions options = new FirebaseOptions.Builder()
        .setCredentials(credentials)
        .build();
    FirebaseApp.initializeApp(options);
    
    Firestore db = FirestoreClient.getFirestore();
  • Python
    Cloud Firestore SDK を初期化する方法は環境に応じて異なります。最も一般的な方法を以下に示します。完全なリファレンスについては、Admin SDK の初期化をご覧ください。
  • Google Cloud で初期化する
    import firebase_admin
    from firebase_admin import firestore
    
    # Application Default credentials are automatically created.
    app = firebase_admin.initialize_app()
    db = firestore.client()

    既存のアプリケーションのデフォルト認証情報も SDK を初期化する際に使用できます。

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore
    
    # Use the application default credentials.
    cred = credentials.ApplicationDefault()
    
    firebase_admin.initialize_app(cred)
    db = firestore.client()
  • 各自のサーバーで初期化する

    各自のサーバーで Firebase Admin SDK を使用するには、サービス アカウントを使用します。

    Google Cloud コンソールで [IAM と管理] > [サービス アカウント] にアクセスします。新しい秘密鍵を生成し、JSON ファイルを保存します。次に、このファイルを使用して SDK を初期化します。

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore
    
    # Use a service account.
    cred = credentials.Certificate('path/to/serviceAccount.json')
    
    app = firebase_admin.initialize_app(cred)
    
    db = firestore.client()
  • Python

    Cloud Firestore SDK を初期化する方法は環境に応じて異なります。最も一般的な方法を以下に示します。完全なリファレンスについては、Admin SDK の初期化をご覧ください。
  • Google Cloud で初期化する
    import firebase_admin
    from firebase_admin import firestore_async
    
    # Application Default credentials are automatically created.
    app = firebase_admin.initialize_app()
    db = firestore_async.client()

    既存のアプリケーションのデフォルト認証情報も SDK を初期化する際に使用できます。

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore_async
    
    # Use the application default credentials.
    cred = credentials.ApplicationDefault()
    
    firebase_admin.initialize_app(cred)
    db = firestore_async.client()
  • 各自のサーバーで初期化する

    各自のサーバーで Firebase Admin SDK を使用するには、サービス アカウントを使用します。

    Google Cloud コンソールで [IAM と管理] > [サービス アカウント] にアクセスします。新しい秘密鍵を生成し、JSON ファイルを保存します。次に、このファイルを使用して SDK を初期化します。

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore_async
    
    # Use a service account.
    cred = credentials.Certificate('path/to/serviceAccount.json')
    
    app = firebase_admin.initialize_app(cred)
    
    db = firestore_async.client()
  • Node.js
    Cloud Firestore SDK を初期化する方法は環境に応じて異なります。最も一般的な方法を以下に示します。完全なリファレンスについては、Admin SDK の初期化をご覧ください。
    • Cloud Functions で初期化する
      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      initializeApp();
      
      const db = getFirestore();
      
    • Google Cloud で初期化する
      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      initializeApp({
        credential: applicationDefault()
      });
      
      const db = getFirestore();
    • 各自のサーバーで初期化する

      各自のサーバー(またはその他の Node.js 環境)で Firebase Admin SDK を使用するには、サービス アカウントを使用します。Google Cloud コンソールで [IAM と管理] > [サービス アカウント] にアクセスします。新しい秘密鍵を生成し、JSON ファイルを保存します。次に、このファイルを使用して SDK を初期化します。

      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      const serviceAccount = require('./path/to/serviceAccountKey.json');
      
      initializeApp({
        credential: cert(serviceAccount)
      });
      
      const db = getFirestore();
      
    Go
    Cloud Firestore SDK を初期化する方法は環境に応じて異なります。最も一般的な方法を以下に示します。完全なリファレンスについては、Admin SDK の初期化をご覧ください。
  • Google Cloud で初期化する
    import (
      "log"
    
      firebase "firebase.google.com/go"
      "google.golang.org/api/option"
    )
    
    // Use the application default credentials
    ctx := context.Background()
    conf := &firebase.Config{ProjectID: projectID}
    app, err := firebase.NewApp(ctx, conf)
    if err != nil {
      log.Fatalln(err)
    }
    
    client, err := app.Firestore(ctx)
    if err != nil {
      log.Fatalln(err)
    }
    defer client.Close()
  • 各自のサーバーで初期化する

    各自のサーバーで Firebase Admin SDK を使用するには、サービス アカウントを使用します。

    Google Cloud コンソールで [IAM と管理] > [サービス アカウント] にアクセスします。新しい秘密鍵を生成し、JSON ファイルを保存します。次に、このファイルを使用して SDK を初期化します。

    import (
      "log"
    
      firebase "firebase.google.com/go"
      "google.golang.org/api/option"
    )
    
    // Use a service account
    ctx := context.Background()
    sa := option.WithCredentialsFile("path/to/serviceAccount.json")
    app, err := firebase.NewApp(ctx, nil, sa)
    if err != nil {
      log.Fatalln(err)
    }
    
    client, err := app.Firestore(ctx)
    if err != nil {
      log.Fatalln(err)
    }
    defer client.Close()
  • PHP

    PHP

    Cloud Firestore クライアントのインストールと作成の詳細については、Cloud Firestore クライアント ライブラリをご覧ください。

    use Google\Cloud\Firestore\FirestoreClient;
    
    /**
     * Initialize Cloud Firestore with default project ID.
     */
    function setup_client_create(string $projectId = null)
    {
        // Create the Cloud Firestore client
        if (empty($projectId)) {
            // The `projectId` parameter is optional and represents which project the
            // client will act on behalf of. If not supplied, the client falls back to
            // the default project inferred from the environment.
            $db = new FirestoreClient();
            printf('Created Cloud Firestore client with default project ID.' . PHP_EOL);
        } else {
            $db = new FirestoreClient([
                'projectId' => $projectId,
            ]);
            printf('Created Cloud Firestore client with project ID: %s' . PHP_EOL, $projectId);
        }
    }
    C#

    C#

    Cloud Firestore クライアントのインストールと作成の詳細については、Cloud Firestore クライアント ライブラリをご覧ください。

    FirestoreDb db = FirestoreDb.Create(project);
    Console.WriteLine("Created Cloud Firestore client with project ID: {0}", project);
    Ruby
    require "google/cloud/firestore"
    
    # The `project_id` parameter is optional and represents which project the
    # client will act on behalf of. If not supplied, the client falls back to the
    # default project inferred from the environment.
    firestore = Google::Cloud::Firestore.new project_id: project_id
    
    puts "Created Cloud Firestore client with given project ID."

    データを追加

    Cloud Firestore はデータをドキュメント内に保存します。ドキュメントはコレクション内に保存されます。データを初めてドキュメントに追加すると、Cloud Firestore によってコレクションとドキュメントが暗黙的に作成されます。コレクションやドキュメントを明示的に作成する必要はありません。

    次のサンプルコードを使用して、新しいコレクションとドキュメントを作成します。

    Java
    DocumentReference docRef = db.collection("users").document("alovelace");
    // Add document data  with id "alovelace" using a hashmap
    Map<String, Object> data = new HashMap<>();
    data.put("first", "Ada");
    data.put("last", "Lovelace");
    data.put("born", 1815);
    //asynchronously write data
    ApiFuture<WriteResult> result = docRef.set(data);
    // ...
    // result.get() blocks on response
    System.out.println("Update time : " + result.get().getUpdateTime());
    Python
    doc_ref = db.collection("users").document("alovelace")
    doc_ref.set({"first": "Ada", "last": "Lovelace", "born": 1815})

    Python

    doc_ref = db.collection("users").document("alovelace")
    await doc_ref.set({"first": "Ada", "last": "Lovelace", "born": 1815})
    Node.js
    const docRef = db.collection('users').doc('alovelace');
    
    await docRef.set({
      first: 'Ada',
      last: 'Lovelace',
      born: 1815
    });
    Go
    _, _, err := client.Collection("users").Add(ctx, map[string]interface{}{
    	"first": "Ada",
    	"last":  "Lovelace",
    	"born":  1815,
    })
    if err != nil {
    	log.Fatalf("Failed adding alovelace: %v", err)
    }
    PHP

    PHP

    Cloud Firestore クライアントのインストールと作成の詳細については、Cloud Firestore クライアント ライブラリをご覧ください。

    $docRef = $db->collection('samples/php/users')->document('alovelace');
    $docRef->set([
        'first' => 'Ada',
        'last' => 'Lovelace',
        'born' => 1815
    ]);
    printf('Added data to the lovelace document in the users collection.' . PHP_EOL);
    C#
    DocumentReference docRef = db.Collection("users").Document("alovelace");
    Dictionary<string, object> user = new Dictionary<string, object>
    {
        { "First", "Ada" },
        { "Last", "Lovelace" },
        { "Born", 1815 }
    };
    await docRef.SetAsync(user);
    Ruby
    doc_ref = firestore.doc "#{collection_path}/alovelace"
    
    doc_ref.set(
      {
        first: "Ada",
        last:  "Lovelace",
        born:  1815
      }
    )
    
    puts "Added data to the alovelace document in the users collection."

    次に、別のドキュメントを users コレクションに追加します。このドキュメントには、最初のドキュメントに表示されない Key-Value ペア(ミドルネーム)が含まれています。コレクション内のドキュメントには、それぞれ異なる情報のセットを含めることができます。

    Java
    DocumentReference docRef = db.collection("users").document("aturing");
    // Add document data with an additional field ("middle")
    Map<String, Object> data = new HashMap<>();
    data.put("first", "Alan");
    data.put("middle", "Mathison");
    data.put("last", "Turing");
    data.put("born", 1912);
    
    ApiFuture<WriteResult> result = docRef.set(data);
    System.out.println("Update time : " + result.get().getUpdateTime());
    Python
    doc_ref = db.collection("users").document("aturing")
    doc_ref.set({"first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912})

    Python

    doc_ref = db.collection("users").document("aturing")
    await doc_ref.set(
        {"first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912}
    )
    Node.js
    const aTuringRef = db.collection('users').doc('aturing');
    
    await aTuringRef.set({
      'first': 'Alan',
      'middle': 'Mathison',
      'last': 'Turing',
      'born': 1912
    });
    Go
    _, _, err = client.Collection("users").Add(ctx, map[string]interface{}{
    	"first":  "Alan",
    	"middle": "Mathison",
    	"last":   "Turing",
    	"born":   1912,
    })
    if err != nil {
    	log.Fatalf("Failed adding aturing: %v", err)
    }
    PHP

    PHP

    Cloud Firestore クライアントのインストールと作成の詳細については、Cloud Firestore クライアント ライブラリをご覧ください。

    $docRef = $db->collection('samples/php/users')->document('aturing');
    $docRef->set([
        'first' => 'Alan',
        'middle' => 'Mathison',
        'last' => 'Turing',
        'born' => 1912
    ]);
    printf('Added data to the aturing document in the users collection.' . PHP_EOL);
    C#
    DocumentReference docRef = db.Collection("users").Document("aturing");
    Dictionary<string, object> user = new Dictionary<string, object>
    {
        { "First", "Alan" },
        { "Middle", "Mathison" },
        { "Last", "Turing" },
        { "Born", 1912 }
    };
    await docRef.SetAsync(user);
    Ruby
    doc_ref = firestore.doc "#{collection_path}/aturing"
    
    doc_ref.set(
      {
        first:  "Alan",
        middle: "Mathison",
        last:   "Turing",
        born:   1912
      }
    )
    
    puts "Added data to the aturing document in the users collection."

    データを読み取る

    Firebase コンソールのデータビューアを使用して、Cloud Firestore にデータが追加されたことをすばやく確認します。

    また、"get" メソッドを使用してコレクション全体を取得することもできます。

    Java
    // asynchronously retrieve all users
    ApiFuture<QuerySnapshot> query = db.collection("users").get();
    // ...
    // query.get() blocks on response
    QuerySnapshot querySnapshot = query.get();
    List<QueryDocumentSnapshot> documents = querySnapshot.getDocuments();
    for (QueryDocumentSnapshot document : documents) {
      System.out.println("User: " + document.getId());
      System.out.println("First: " + document.getString("first"));
      if (document.contains("middle")) {
        System.out.println("Middle: " + document.getString("middle"));
      }
      System.out.println("Last: " + document.getString("last"));
      System.out.println("Born: " + document.getLong("born"));
    }
    Python
    users_ref = db.collection("users")
    docs = users_ref.stream()
    
    for doc in docs:
        print(f"{doc.id} => {doc.to_dict()}")

    Python

    users_ref = db.collection("users")
    docs = users_ref.stream()
    
    async for doc in docs:
        print(f"{doc.id} => {doc.to_dict()}")
    Node.js
    const snapshot = await db.collection('users').get();
    snapshot.forEach((doc) => {
      console.log(doc.id, '=>', doc.data());
    });
    Go
    iter := client.Collection("users").Documents(ctx)
    for {
    	doc, err := iter.Next()
    	if err == iterator.Done {
    		break
    	}
    	if err != nil {
    		log.Fatalf("Failed to iterate: %v", err)
    	}
    	fmt.Println(doc.Data())
    }
    PHP

    PHP

    Cloud Firestore クライアントのインストールと作成の詳細については、Cloud Firestore クライアント ライブラリをご覧ください。

    $usersRef = $db->collection('samples/php/users');
    $snapshot = $usersRef->documents();
    foreach ($snapshot as $user) {
        printf('User: %s' . PHP_EOL, $user->id());
        printf('First: %s' . PHP_EOL, $user['first']);
        if (!empty($user['middle'])) {
            printf('Middle: %s' . PHP_EOL, $user['middle']);
        }
        printf('Last: %s' . PHP_EOL, $user['last']);
        printf('Born: %d' . PHP_EOL, $user['born']);
        printf(PHP_EOL);
    }
    printf('Retrieved and printed out all documents from the users collection.' . PHP_EOL);
    C#
    CollectionReference usersRef = db.Collection("users");
    QuerySnapshot snapshot = await usersRef.GetSnapshotAsync();
    foreach (DocumentSnapshot document in snapshot.Documents)
    {
        Console.WriteLine("User: {0}", document.Id);
        Dictionary<string, object> documentDictionary = document.ToDictionary();
        Console.WriteLine("First: {0}", documentDictionary["First"]);
        if (documentDictionary.ContainsKey("Middle"))
        {
            Console.WriteLine("Middle: {0}", documentDictionary["Middle"]);
        }
        Console.WriteLine("Last: {0}", documentDictionary["Last"]);
        Console.WriteLine("Born: {0}", documentDictionary["Born"]);
        Console.WriteLine();
    }
    Ruby
    users_ref = firestore.col collection_path
    users_ref.get do |user|
      puts "#{user.document_id} data: #{user.data}."
    end

    次のステップ

    次のトピックで知識を深めてください。