Quickstart using a server client library

This quickstart shows you how to set up Cloud Firestore, add data, and read data by using the C#, Go, Java, Node.js, PHP, Python, or Ruby server client library.

Before you begin

  • Google アカウントにログインします。

    Google アカウントをまだお持ちでない場合は、新しいアカウントを登録します。

  • GCP プロジェクトを選択または作成します。

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

Create a Cloud Firestore in Native mode database

If this is a new project, you need to create a Cloud Firestore database instance.

  1. Go to the Cloud Firestore viewer.

  2. From the Select a database service screen, choose Cloud Firestore in Native mode.

  3. Select a location for your Cloud Firestore.

    This location setting is your project's default Google Cloud Platform (GCP) resource location. Note that this location will be used for GCP services in your project that require a location setting, specifically, your default Cloud Storage bucket and your App Engine app (which is required if you use Cloud Scheduler).

  4. Click Create Database.

When you create a Cloud Firestore project, it also enables the API in the Cloud API Manager.

Set up authentication

To run the client library, you must first set up authentication by creating a service account and setting an environment variable.

GCP Console

  1. GCP Console で [サービス アカウントキーの作成] ページに移動します。

    [サービス アカウントキーの作成] ページに移動
  2. [サービス アカウント] リストから [新しいサービス アカウント] を選択します。
  3. [サービス アカウント名] フィールドに名前を入力します。
  4. [役割] リストで、[プロジェクト] > [オーナー] を選択します。

    : [役割] フィールドの設定により、リソースにアクセスするサービス アカウントが承認されます。このフィールドは、後から GCP Console で表示または変更できます。本番環境アプリケーションを開発している場合は、[プロジェクト] > [オーナー] よりも詳細な権限を指定します。詳しくはサービス アカウントへの役割の付与をご覧ください。
  5. [作成] をクリックします。キーが含まれている JSON ファイルがパソコンにダウンロードされます。

コマンドライン

ローカルマシン上の Cloud SDK を使用するか、または Cloud Shell 内で以下のコマンドを実行できます。

  1. サービス アカウントを作成します。[NAME] をサービス アカウントの名前に置き換えます。

    gcloud iam service-accounts create [NAME]
  2. サービス アカウントに権限を付与します。[PROJECT_ID] は実際のプロジェクト ID に置き換えます。

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role "roles/owner"
    : [役割] フィールドの設定により、リソースにアクセスするサービス アカウントが承認されます。後で GCP Console を使用して、このフィールドを表示したり変更したりできます。本番環境アプリケーションを開発している場合は、[プロジェクト] > [オーナー] よりも詳細な権限を指定します。詳しくはサービス アカウントへの役割の付与をご覧ください。
  3. キーファイルを生成します。[FILE_NAME] はキーファイルの名前に置き換えます。

    gcloud iam service-accounts keys create [FILE_NAME].json --iam-account [NAME]@[PROJECT_ID].iam.gserviceaccount.com

環境変数 GOOGLE_APPLICATION_CREDENTIALS を設定して、アプリケーション コードに認証情報を指定します。[PATH] は、サービス アカウント キーが含まれる JSON ファイルのファイルパスに置き換え、[FILE_NAME] はファイル名に置き換えます。この変数は現在のシェル セッションにのみ適用されるため、新しいセッションを開く場合は、変数を再度設定してください。

Linux または macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

例:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"

Windows

PowerShell を使用する場合:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

例:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"

コマンド プロンプトを使用する場合:

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

Add the server client library to your app

Add the required dependencies and client libraries to your app.

Java

Add the Cloud Firestore Java library to your app:

  • Using Gradle:
    compile 'com.google.cloud:google-cloud-firestore:1.29.0'
    
  • Using Maven:
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-firestore</artifactId>
      <version>1.30.0</version>
    </dependency>
  • Using an IDE:

    If you're using IntelliJ or Eclipse, you can add client libraries to your project using these IDE plugins:

    The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.

Python

Add the Cloud Firestore Python library to your app:

pip install --upgrade google-cloud-firestore

Node.js

Add the Cloud Firestore Node.js library to your app:

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

Install the Cloud Firestore Go library:

go get cloud.google.com/go/firestore

Add the Cloud Firestore Go library to your app:

import "cloud.google.com/go/firestore"
PHP
  1. Install and enable the gRPC extension for PHP, which you will need to use the client library.
  2. Add the Cloud Firestore PHP library to your app:
    composer require google/cloud-firestore
C#
  1. Add the Cloud Firestore C# library to your app in your .csproj file:
    <ItemGroup>
      <PackageReference Include="Google.Cloud.Firestore" Version="1.1.0-beta01" />
    </ItemGroup>
  2. Add the following to your Program.cs file:
    using Google.Cloud.Firestore;
Ruby
  1. Add the Cloud Firestore Ruby library to your app in your Gemfile:
    gem "google-cloud-firestore"
  2. Install dependencies from your Gemfile using:
    bundle install

Initialize Cloud Firestore

Initialize an instance of Cloud Firestore:

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

# Project ID is determined by the GCLOUD_PROJECT environment variable
db = firestore.Client()
Node.js
const Firestore = require('@google-cloud/firestore');

const db = new Firestore({
  projectId: 'YOUR_PROJECT_ID',
  keyFilename: '/path/to/keyfile.json',
});
Go
// Sets your Google Cloud Platform project ID.
projectID := "YOUR_PROJECT_ID"

// Get a Firestore client.
ctx := context.Background()
client, err := firestore.NewClient(ctx, projectID)
if err != nil {
	log.Fatalf("Failed to create client: %v", err)
}

// Close client when done.
defer client.Close()
PHP
use Google\Cloud\Firestore\FirestoreClient;

/**
 * Initialize Cloud Firestore with default project ID.
 * ```
 * initialize();
 * ```
 */
function initialize()
{
    // Create the Cloud Firestore client
    $db = new FirestoreClient();
    printf('Created Cloud Firestore client with default project ID.' . PHP_EOL);
}
C#
FirestoreDb db = FirestoreDb.Create(project);
Console.WriteLine("Created Cloud Firestore client with project ID: {0}", project);
Ruby
require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new project_id: project_id

puts "Created Cloud Firestore client with given project ID."

Add data

Cloud Firestore stores data in Documents, which are stored in Collections. Cloud Firestore creates collections and documents implicitly the first time you add data to the document. You do not need to explicitly create collections or documents.

Create a new collection and a document using the following example code.

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(u'users').document(u'alovelace')
doc_ref.set({
    u'first': u'Ada',
    u'last': u'Lovelace',
    u'born': 1815
})
  
Node.js
let docRef = db.collection('users').doc('alovelace');

let setAda = 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
$docRef = $db->collection('users')->document('lovelace');
$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 "users/alovelace"

doc_ref.set(
  first: "Ada",
  last:  "Lovelace",
  born:  1815
)

puts "Added data to the alovelace document in the users collection."
  

Now add another document to the users collection. Notice that this document includes a key-value pair (middle name) that does not appear in the first document. Documents in a collection can contain different sets of information.

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(u'users').document(u'aturing')
doc_ref.set({
    u'first': u'Alan',
    u'middle': u'Mathison',
    u'last': u'Turing',
    u'born': 1912
})
  
Node.js
let aTuringRef = db.collection('users').doc('aturing');

let setAlan = 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
$docRef = $db->collection('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 "users/aturing"

doc_ref.set(
  first:  "Alan",
  middle: "Mathison",
  last:   "Turing",
  born:   1912
)

puts "Added data to the aturing document in the users collection."
  

Read data

To quickly verify that you've added data to Cloud Firestore, use the data viewer in the Firebase console.

You can also use the get method to retrieve the entire collection.

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(u'users')
docs = users_ref.stream()

for doc in docs:
    print(u'{} => {}'.format(doc.id, doc.to_dict()))
  
Node.js
db.collection('users').get()
  .then((snapshot) => {
    snapshot.forEach((doc) => {
      console.log(doc.id, '=>', doc.data());
    });
  })
  .catch((err) => {
    console.log('Error getting documents', err);
  });
  
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
$usersRef = $db->collection('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 "users"
users_ref.get do |user|
  puts "#{user.document_id} data: #{user.data}."
end
  

Next steps

Deepen your knowledge with the following topics:

  • Data model — Learn more about how data is structured in Cloud Firestore, including hierarchical data and subcollections.
  • Add data — Learn more about creating and updating data in Cloud Firestore.
  • Get data — Learn more about how to retrieve data.
  • Perform simple and compound queries — Learn how to run simple and compound queries.
  • Order and limit queries — Learn how to order and limit the data returned by your queries.
このページは役立ちましたか?評価をお願いいたします。

フィードバックを送信...