使用伺服器用戶端程式庫開始使用 Cloud Firestore Standard 版

本快速入門導覽課程說明如何設定 Cloud Firestore Enterprise 版、新增資料,然後使用 C#、Go、Java、Node.js、PHP、Python 和 Ruby 的伺服器用戶端程式庫,在 Firebase 控制台中查看剛才新增的資料。

使用這些用戶端程式庫設定具備完整資料庫存取權的伺服器環境。

建立 Cloud Firestore 資料庫

  1. 如果尚未建立 Firebase 專案,請在 Firebase 控制台中按一下「新增專案」,然後按照畫面上的指示建立 Firebase 專案,或將 Firebase 服務新增至現有的 Google Cloud 專案。

  2. Firebase 控制台中開啟專案。在左側面板中展開「建構」,然後選取「Firestore 資料庫」

  3. 按一下 [Create database] (建立資料庫)。

  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 Security Rules 會套用至預設Cloud Firestore資料庫。如果為專案建立多個資料庫,可以為每個資料庫部署 Cloud Firestore Security Rules

  6. 點選「建立」

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

設定開發環境

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

Java
  1. 在應用程式中新增 Firebase Admin SDK:
    • 使用 Gradle:
      implementation 'com.google.firebase:firebase-admin:9.7.0'
    • 使用 Maven:
      <dependency>
        <groupId>com.google.firebase</groupId>
        <artifactId>firebase-admin</artifactId>
        <version>9.7.0</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 應用程式預設憑證進行驗證。
    • 如要從開發環境進行驗證,請設定 GOOGLE_APPLICATION_CREDENTIALS 環境變數,指向 JSON 服務帳戶金鑰檔案。您可以在 API 控制台的「憑證」頁面建立金鑰檔案。
      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 應用程式預設憑證進行驗證。
    • 如要從開發環境進行驗證,請設定 GOOGLE_APPLICATION_CREDENTIALS 環境變數,指向 JSON 服務帳戶金鑰檔案。您可以在 API 控制台的「憑證」頁面建立金鑰檔案。
      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 & admin」(IAM 與管理) >「Service accounts」(服務帳戶)。產生新的私密金鑰,並儲存 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 & admin」(IAM 與管理) >「Service accounts」(服務帳戶)。產生新的私密金鑰,並儲存 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 & admin」(IAM 與管理) >「Service accounts」(服務帳戶)。產生新的私密金鑰,並儲存 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 & admin」(IAM 與管理) >「Service accounts」(服務帳戶)。產生新的私密金鑰,並儲存 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 & admin」(IAM 與管理) >「Service accounts」(服務帳戶)。產生新的私密金鑰,並儲存 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 集合。請注意,這份文件包含第一個文件中沒有的鍵/值組合 (中間名)。集合中的文件可以包含不同的資訊集。

    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

    後續步驟

    深入瞭解下列主題: