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

本快速入門導覽課程說明如何設定 Cloud Firestore、新增資料,然後使用核心作業或管道作業,透過 Java、Node.js 和 Python 的伺服器用戶端程式庫,查詢您剛在 Firebase 控制台中新增的資料。

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

建立 Cloud Firestore 資料庫

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

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

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

  4. 選取「Enterprise」做為資料庫模式。

  5. 選取「原生模式的 Firestore」做為作業模式,支援核心和管道作業。

  6. 選取資料庫的位置

  7. 選取 Cloud Firestore Security Rules 的起始模式:

    測試模式

    適合用來開始使用行動和網路用戶端程式庫,但允許任何人讀取及覆寫您的資料。測試完成後,請務必查看「保護資料」一節。

    如要開始使用網頁、Apple 平台或 Android SDK,請選取測試模式。

    正式版模式

    拒絕行動和網路用戶端的所有讀寫要求。 通過驗證的應用程式伺服器 (Node.js、Python、Java) 仍可存取資料庫。

    初始設定的 Cloud Firestore Security Rules 會套用至預設Cloud Firestore資料庫。如果為專案建立多個資料庫,可以為每個資料庫部署 Cloud Firestore Security Rules

  8. 點選「建立」

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

設定開發環境

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

Node.js
  1. 在應用程式中新增 Firebase Admin SDK:
    npm install firebase-admin --save
  2. 請按照下列操作說明,在環境中以適當的憑證初始化 Cloud Firestore
Python
  1. 將 Firebase Admin SDK 新增至 Python 應用程式:
    pip install --upgrade firebase-admin
  2. 請按照下列操作說明,在環境中以適當的憑證初始化 Cloud Firestore
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

初始化 Cloud Firestore

初始化 Cloud Firestore 的例項:

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();
    
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()
  • 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();
  • 使用 Core 作業新增資料

    如要探索用於查詢資料的核心作業和管道作業,請使用核心作業將資料新增至資料庫。

    Cloud Firestore 會將資料儲存在文件中,並將文件儲存在集合中。第一次將資料新增至文件時,Cloud Firestore 會隱含建立集合和文件。您不需要明確建立集合或文件。

    使用下列範例程式碼建立新集合和文件。

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

    使用 Core 作業讀取資料

    使用 Firebase 控制台中的資料檢視器,快速確認您已將資料新增至 Cloud Firestore

    您也可以使用「get」方法擷取整個集合。

    Node.js
    const snapshot = await db.collection('users').get();
    snapshot.forEach((doc) => {
      console.log(doc.id, '=>', doc.data());
    });
    Python
    users_ref = db.collection("users")
    docs = users_ref.stream()
    
    for doc in docs:
        print(f"{doc.id} => {doc.to_dict()}")
    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"));
    }

    使用 Pipeline 作業讀取資料

    現在您可以比較 Pipeline 查詢體驗與 Core 查詢體驗。

    Node.js
    const readDataPipeline = db.pipeline()
      .collection("users");
    
    // Execute the pipeline and handle the result
    try {
      const querySnapshot = await readDataPipeline.execute();
      querySnapshot.results.forEach((result) => {
        console.log(`${result.id} => ${result.data()}`);
      });
    } catch (error) {
        console.error("Error getting documents: ", error);
    }
    Python
    pipeline = client.pipeline().collection("users")
    for result in pipeline.execute():
        print(f"{result.id} => {result.data()}")
    Java
    Pipeline pipeline = firestore.pipeline().collection("users");
    ApiFuture<Pipeline.Snapshot> future = pipeline.execute();
    for (com.google.cloud.firestore.PipelineResult result : future.get().getResults()) {
      System.out.println(result.getId() + " => " + result.getData());
    }
    // or, asynchronously
    pipeline.execute(
        new ApiStreamObserver<com.google.cloud.firestore.PipelineResult>() {
          @Override
          public void onNext(com.google.cloud.firestore.PipelineResult result) {
            System.out.println(result.getId() + " => " + result.getData());
          }
    
          @Override
          public void onError(Throwable t) {
            System.err.println(t);
          }
    
          @Override
          public void onCompleted() {
            System.out.println("done");
          }
        });

    後續步驟

    透過下列主題深入瞭解 Core 和管道作業: