クイックスタート: サーバー クライアント ライブラリを使用して Firestore データベースを作成する

このクイックスタートでは、C#、Go、Java、Node.js、PHP、Python、または Ruby サーバー クライアント ライブラリを使用して、Firestore の設定、データの追加、データの読み取りを行う方法を説明します。

始める前に

  • Google Cloud アカウントにログインします。Google Cloud を初めて使用する場合は、アカウントを作成して、実際のシナリオでの Google プロダクトのパフォーマンスを評価してください。新規のお客様には、ワークロードの実行、テスト、デプロイができる無料クレジット $300 分を差し上げます。
  • Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  • Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

ネイティブ モードの Firestore データベースを作成する

新しいプロジェクトの場合は、Firestore データベース インスタンスを作成する必要があります。

  1. Cloud Firestore ビューアに移動します

  2. [データベース サービスの選択] 画面で、ネイティブ モードの Firestore を選択します。

  3. Firestore のロケーションを選択します。

    このロケーション設定が、プロジェクトのデフォルトの Google Cloud Platform(GCP)リソース ロケーションになります。なお、このロケーションは、プロジェクト内のロケーション設定が必要な GCP サービスで使用されます。具体例としては、デフォルトの Cloud Storage バケットや App Engine アプリ(Cloud Scheduler を使用する場合に必要)などがあります。

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

Firestore プロジェクトを作成すると、Cloud API Manager で API も有効になります。

認証を設定する

クライアント ライブラリを使用するには、サービス アカウントを作成して環境変数を設定し、認証を設定する必要があります。

環境変数 GOOGLE_APPLICATION_CREDENTIALS を設定して、アプリケーション コードに認証情報を指定します。この変数は、現在のシェル セッションにのみ適用されます。この変数を新しいシェル セッションに適用する場合は、シェル起動ファイル(~/.bashrc ファイルや ~/.profile ファイルなど)で変数を設定します。

Linux または macOS

export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

KEY_PATH は、認証情報が含まれる JSON ファイルのパスに置き換えます。

例:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

Windows

PowerShell の場合:

$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

KEY_PATH は、認証情報が含まれる JSON ファイルのパスに置き換えます。

例:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"

コマンド プロンプトの場合:

set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH

KEY_PATH は、認証情報が含まれる JSON ファイルのパスに置き換えます。

アプリにサーバー クライアント ライブラリを追加する

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

Java

アプリに Firestore Java ライブラリを追加します。

  • Maven を使用する:
    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>com.google.cloud</groupId>
          <artifactId>libraries-bom</artifactId>
          <version>26.34.0</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>
    
    <dependencies>
      <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-firestore</artifactId>
      </dependency>
  • Gradle を使用している場合や、BOM なしで設定した場合は、Firestore Client for Java の README をご覧ください。
  • IDE を使用する:

    VS Code、IntelliJ または Eclipse を使用している場合は、次の IDE プラグインでプロジェクトにクライアント ライブラリを追加できます。

    プラグインでは、サービス アカウントのキー管理などの追加機能も提供されます。詳細は各プラグインのドキュメントをご覧ください。

Python

アプリに Firestore Python ライブラリを追加します。

pip install --upgrade google-cloud-firestore

Node.js

アプリに Firestore Node.js ライブラリを追加します。

npm install --save @google-cloud/firestore
Go

Firestore Go ライブラリをインストールします。

go get cloud.google.com/go/firestore

アプリに Firestore Go ライブラリを追加します。

import "cloud.google.com/go/firestore"
PHP
  1. PHP 用の gRPC 拡張機能をインストールして有効にします。この機能は、クライアント ライブラリを使用する場合に必要です。
  2. アプリに Firestore PHP ライブラリを追加します。
    composer require google/cloud-firestore
C#
  1. .csproj ファイル内でアプリに Firestore C# ライブラリを追加します。
    <ItemGroup>
      <PackageReference Include="Google.Cloud.Firestore" Version="1.1.0-beta01" />
    </ItemGroup>
  2. 次のコードを Program.cs ファイルに追加します。
    using Google.Cloud.Firestore;
Ruby
  1. Gemfile 内でアプリに Firestore Ruby ライブラリを追加します。
    gem "google-cloud-firestore"
  2. 以下のようにして、Gemfile から依存関係をインストールします。
    bundle install

Firestore を初期化する

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

Java
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.FirestoreOptions;
FirestoreOptions firestoreOptions =
    FirestoreOptions.getDefaultInstance().toBuilder()
        .setProjectId(projectId)
        .setCredentials(GoogleCredentials.getApplicationDefault())
        .build();
Firestore db = firestoreOptions.getService();
Python
from google.cloud import firestore

# The `project` 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 = firestore.Client(project="my-project-id")
Python
(非同期)
from google.cloud import firestore

# The `project` 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 = firestore.AsyncClient(project="my-project-id")
Node.js
const Firestore = require('@google-cloud/firestore');

const db = new Firestore({
  projectId: 'YOUR_PROJECT_ID',
  keyFilename: '/path/to/keyfile.json',
});
Go
import (
	"context"
	"flag"
	"fmt"
	"log"

	"google.golang.org/api/iterator"

	"cloud.google.com/go/firestore"
)

func createClient(ctx context.Context) *firestore.Client {
	// Sets your Google Cloud Platform project ID.
	projectID := "YOUR_PROJECT_ID"

	client, err := firestore.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}
	// Close client when done with
	// defer client.Close()
	return client
}
PHP
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#
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."

データを追加する

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

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

Java

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

Python
(Async)

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

Node.js

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

const docRef = db.collection('users').doc('alovelace');

await docRef.set({
  first: 'Ada',
  last: 'Lovelace',
  born: 1815
});

Go

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

_, _, 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

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#

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

Python
(Async)

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

Node.js

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

const aTuringRef = db.collection('users').doc('aturing');

await aTuringRef.set({
  'first': 'Alan',
  'middle': 'Mathison',
  'last': 'Turing',
  'born': 1912
});

Go

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

_, _, 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

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#

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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."

データを読み取る

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

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

Java

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

// 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

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

users_ref = db.collection("users")
docs = users_ref.stream()

for doc in docs:
    print(f"{doc.id} => {doc.to_dict()}")

Python
(Async)

users_ref = db.collection("users")
docs = users_ref.stream()

async for doc in docs:
    print(f"{doc.id} => {doc.to_dict()}")

Node.js

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

const snapshot = await db.collection('users').get();
snapshot.forEach((doc) => {
  console.log(doc.id, '=>', doc.data());
});

Go

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

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#

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

users_ref = firestore.col collection_path
users_ref.get do |user|
  puts "#{user.document_id} data: #{user.data}."
end

次のステップ

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