使用伺服器用戶端程式庫建立 Firestore 資料庫

本快速入門導覽課程說明如何使用 C#、Go、Java、Node.js、PHP、Python 或 Ruby 伺服器用戶端程式庫,設定 Firestore、新增資料及讀取資料。

事前準備

  • Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  • In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  • In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

以原生模式建立 Firestore 資料庫

如果是新專案,您需要建立 Firestore 資料庫執行個體。

  1. 前往 Firestore 檢視器

  2. 在「選取資料庫服務」畫面中,選擇「原生模式的 Firestore」

  3. 選取 Firestore 的位置

    如果無法選取位置,表示專案的「預設資源位置」 Google Cloud 已設定完畢。專案的部分資源 (例如預設 Firestore 執行個體) 共用常見的位置依附元件,您可以在建立專案時或設定共用此位置依附元件的其他服務時,設定這些資源的位置。

  4. 按一下 [Create Database] (建立資料庫)。

建立 Firestore 專案時,系統也會在 Cloud API 管理工具中啟用 API。

設定驗證方法

如要執行用戶端程式庫,您必須先建立服務帳戶並設定環境變數以設定驗證

Provide authentication credentials to your application code by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS. This variable applies only to your current shell session. If you want the variable to apply to future shell sessions, set the variable in your shell startup file, for example in the ~/.bashrc or ~/.profile file.

Linux 或 macOS

export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Replace KEY_PATH with the path of the JSON file that contains your credentials.

For example:

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

Windows

For PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Replace KEY_PATH with the path of the JSON file that contains your credentials.

For example:

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

For command prompt:

set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH

Replace KEY_PATH with the path of the JSON file that contains your credentials.

在應用程式中加入伺服器用戶端程式庫

將必要的依附元件和用戶端程式庫新增至應用程式。

Java

將 Firestore Java 程式庫新增至應用程式:

  • 使用 Maven:
    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>com.google.cloud</groupId>
          <artifactId>libraries-bom</artifactId>
          <version>26.63.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
(Async)
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 集合。請注意,這份文件包含第一個文件中沒有的鍵/值組合 (中間名)。集合中的文件可以包含不同的資訊集。

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

後續步驟

深入瞭解下列主題: