開始使用 Cloud Firestore Enterprise 版

本快速入門導覽課程說明如何設定 Cloud Firestore Enterprise 版、新增資料,然後使用核心作業或管道作業,在 Firebase 控制台中查詢您剛新增的資料。

Cloud Firestore 支援行動或網頁 SDK 和伺服器用戶端程式庫:

  • Cloud Firestore 支援 Android、iOS 和網頁等平台的 SDK。搭配 Cloud Firestore Security RulesFirebase Authentication,行動和網頁 SDK 支援無伺服器應用程式架構,讓用戶端直接連線至 Cloud Firestore 資料庫。

  • Cloud Firestore 支援 Java、Node.js 和 Python 的伺服器用戶端程式庫。使用這些用戶端程式庫設定具備完整資料庫存取權的伺服器環境。如要進一步瞭解這些程式庫,請參閱伺服器用戶端程式庫快速入門導覽課程

建立 Cloud Firestore Enterprise 版資料庫

  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,請選取測試模式。

    正式版模式

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

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

  8. 點選「建立」

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

設定開發環境

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

Web

  1. 按照操作說明將 Firebase 新增至您的網頁應用程式
  2. Cloud Firestore SDK 以 npm 套件的形式提供。
    npm install firebase@12.9.0 --save
    您需要匯入 Firebase 和 Cloud Firestore
    import { initializeApp } from "firebase/app";
    import { getFirestore } from "firebase/firestore";
iOS+

按照操作說明將 Firebase 新增至 Apple 應用程式

使用 Swift Package Manager 安裝及管理 Firebase 依附元件。

  1. 在 Xcode 中保持開啟應用程式專案,然後依序點選「File」>「Swift Packages」>「Add Package Dependency」
  2. 系統提示時,請新增 Firebase Apple 平台 SDK 存放區:
  3.   https://github.com/firebase/firebase-ios-sdk
      
  4. 選擇 Firestore 程式庫。
  5. 完成後,Xcode 會自動開始在背景中解析並下載依附元件。
Android
  1. 按照操作說明將 Firebase 新增至 Android 應用程式
  2. 使用 Firebase Android BoM,在模組 (應用程式層級) Gradle 檔案 (通常為 app/build.gradle.ktsapp/build.gradle) 中,宣告 Android 適用的 Cloud Firestore 程式庫依附元件。
    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:34.8.0"))
    
        // Declare the dependency for the Cloud Firestore library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-firestore")
    }

    如果使用 Firebase Android BoM,應用程式就會一律使用相容的 Firebase Android 程式庫版本。

    (替代做法) 使用 BoM 宣告 Firebase 程式庫依附元件。 BoM

    如果選擇不使用 Firebase BoM,則必須在依附元件行中指定每個 Firebase 程式庫版本。

    請注意,如果應用程式使用多個 Firebase 程式庫,我們強烈建議使用 BoM 管理程式庫版本,確保所有版本都相容。

    dependencies {
        // Declare the dependency for the Cloud Firestore library
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-firestore:26.1.0")
    }

    想尋找 Kotlin 專用的程式庫模組嗎?2023 年 10 月發布版本起,Kotlin 和 Java 開發人員都可以依附於主要程式庫模組 (詳情請參閱這項計畫的常見問題)。

初始化 Cloud Firestore

初始化 Cloud Firestore 的例項:

Web

import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://support.google.com/firebase/answer/7015592
const firebaseConfig = {
    FIREBASE_CONFIGURATION
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);


// When initializing Firestore, remember to use the name of the database you created earlier:
const db = initializeFirestore(app, {}, 'your-new-enterprise-database');

FIREBASE_CONFIGURATION 替換成網頁應用程式的firebaseConfig

如要在裝置失去連線時保留資料,請參閱「啟用離線資料」說明文件。

Swift
import FirebaseCore
import FirebaseFirestore

FirebaseApp.configure()

// When initializing Firestore, remember to use the name of the database you created earlier:
let db = Firestore.firestore(database: "your-new-enterprise-database")

Kotlin

// Access a Cloud Firestore instance from your Activity
// When initializing Firestore, remember to use the name of the database you created earlier:
val firestore = FirebaseFirestore.getInstance("your-new-enterprise-database")

Java

// Access a Cloud Firestore instance from your Activity
// When initializing Firestore, remember to use the name of the database you created earlier:
FirebaseFirestore firestore = FirebaseFirestore.getInstance("your-new-enterprise-database");

使用 Core 作業新增資料

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

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

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

Web

import { collection, addDoc } from "firebase/firestore"; 

try {
  const docRef = await addDoc(collection(db, "users"), {
    first: "Ada",
    last: "Lovelace",
    born: 1815
  });
  console.log("Document written with ID: ", docRef.id);
} catch (e) {
  console.error("Error adding document: ", e);
}

Web

db.collection("users").add({
    first: "Ada",
    last: "Lovelace",
    born: 1815
})
.then((docRef) => {
    console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
    console.error("Error adding document: ", error);
});
Swift
注意:這項產品不適用於 watchOS 和 App Clip 目標。
// Add a new document with a generated ID
do {
  let ref = try await db.collection("users").addDocument(data: [
    "first": "Ada",
    "last": "Lovelace",
    "born": 1815
  ])
  print("Document added with ID: \(ref.documentID)")
} catch {
  print("Error adding document: \(error)")
}

Kotlin

// Create a new user with a first and last name
val user = hashMapOf(
    "first" to "Ada",
    "last" to "Lovelace",
    "born" to 1815,
)

// Add a new document with a generated ID
db.collection("users")
    .add(user)
    .addOnSuccessListener { documentReference ->
        Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}")
    }
    .addOnFailureListener { e ->
        Log.w(TAG, "Error adding document", e)
    }

Java

// Create a new user with a first and last name
Map<String, Object> user = new HashMap<>();
user.put("first", "Ada");
user.put("last", "Lovelace");
user.put("born", 1815);

// Add a new document with a generated ID
db.collection("users")
        .add(user)
        .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "Error adding document", e);
            }
        });

現在將另一份文件新增至 users 集合。請注意,這份文件包含第一個文件中沒有的鍵/值組合 (中間名)。集合中的文件可以包含不同的資訊集。

Web

// Add a second document with a generated ID.
import { addDoc, collection } from "firebase/firestore"; 

try {
  const docRef = await addDoc(collection(db, "users"), {
    first: "Alan",
    middle: "Mathison",
    last: "Turing",
    born: 1912
  });

  console.log("Document written with ID: ", docRef.id);
} catch (e) {
  console.error("Error adding document: ", e);
}

Web

// Add a second document with a generated ID.
db.collection("users").add({
    first: "Alan",
    middle: "Mathison",
    last: "Turing",
    born: 1912
})
.then((docRef) => {
    console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
    console.error("Error adding document: ", error);
});
Swift
注意:這項產品不適用於 watchOS 和 App Clip 目標。
// Add a second document with a generated ID.
do {
  let ref = try await db.collection("users").addDocument(data: [
    "first": "Alan",
    "middle": "Mathison",
    "last": "Turing",
    "born": 1912
  ])
  print("Document added with ID: \(ref.documentID)")
} catch {
  print("Error adding document: \(error)")
}

Kotlin

// Create a new user with a first, middle, and last name
val user = hashMapOf(
    "first" to "Alan",
    "middle" to "Mathison",
    "last" to "Turing",
    "born" to 1912,
)

// Add a new document with a generated ID
db.collection("users")
    .add(user)
    .addOnSuccessListener { documentReference ->
        Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}")
    }
    .addOnFailureListener { e ->
        Log.w(TAG, "Error adding document", e)
    }

Java

// Create a new user with a first, middle, and last name
Map<String, Object> user = new HashMap<>();
user.put("first", "Alan");
user.put("middle", "Mathison");
user.put("last", "Turing");
user.put("born", 1912);

// Add a new document with a generated ID
db.collection("users")
        .add(user)
        .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "Error adding document", e);
            }
        });

使用 Core 作業讀取資料

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

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

Web

import { collection, getDocs } from "firebase/firestore"; 

const querySnapshot = await getDocs(collection(db, "users"));
querySnapshot.forEach((doc) => {
  console.log(`${doc.id} => ${doc.data()}`);
});

Web

db.collection("users").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
    });
});
Swift
注意:這項產品不適用於 watchOS 和 App Clip 目標。
do {
  let snapshot = try await db.collection("users").getDocuments()
  for document in snapshot.documents {
    print("\(document.documentID) => \(document.data())")
  }
} catch {
  print("Error getting documents: \(error)")
}

Kotlin

db.collection("users")
    .get()
    .addOnSuccessListener { result ->
        for (document in result) {
            Log.d(TAG, "${document.id} => ${document.data}")
        }
    }
    .addOnFailureListener { exception ->
        Log.w(TAG, "Error getting documents.", exception)
    }

Java

db.collection("users")
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        Log.d(TAG, document.getId() + " => " + document.getData());
                    }
                } else {
                    Log.w(TAG, "Error getting documents.", task.getException());
                }
            }
        });

使用 Pipeline 作業讀取資料

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

Web

// The import/require of "firebase/firestore/pipelines" has a side-effect
// of extending the Firestore class with the `.pipeline()` method.
// Without this import/require, you will not be able to create a Pipeline.
// import { execute } from "firebase/firestore/pipelines";
const readDataPipeline = db.pipeline()
  .collection("users");

// Execute the pipeline and handle the result
try {
  const querySnapshot = await execute(readDataPipeline);
  querySnapshot.results.forEach((result) => {
    console.log(`${result.id} => ${result.data()}`);
  });
} catch (error) {
    console.error("Error getting documents: ", error);
}
Swift
do {
  // Initialize a Firestore Pipeline instance and specify the "users" collection as the
  // input stage.
  let snapshot = try await db.pipeline()
    .collection("users")
    .execute() // Execute the pipeline to retrieve documents.

  // Iterate through the documents in the pipeline results, similar to a regular query
  // snapshot.
  for result in snapshot.results {
    print("\(result.id ?? "no ID") => \(result.data)")
  }
} catch {
  print("Error getting documents with pipeline: \(error)")
}

Kotlin

val readDataPipeline = db.pipeline()
    .collection("users")

// Execute the pipeline and handle the result
readDataPipeline.execute()
    .addOnSuccessListener { result ->
        for (document in result) {
            println("${document.getId()} => ${document.getData()}")
        }
    }
    .addOnFailureListener { exception ->
        println("Error getting documents: $exception")
    }

Java

Pipeline readDataPipeline = db.pipeline()
.collection("users");

readDataPipeline.execute()
.addOnSuccessListener(new OnSuccessListener<Pipeline.Snapshot>() {
    @Override
    public void onSuccess(Pipeline.Snapshot snapshot) {
        for (PipelineResult result : snapshot.getResults()) {
            System.out.println(result.getId() + " => " + result.getData());
        }
    }
})
.addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        System.out.println("Error getting documents: " + e);
    }
});

保護行動和網頁 SDK 的資料

如果您使用網頁、Android 或 Apple 平台 SDK,請使用 Firebase AuthenticationCloud Firestore Security Rules,確保 Cloud Firestore 中的資料安全無虞。

以下是一些基本規則集,可供您做為入門參考。您可以在控制台的「規則」分頁中修改安全性規則。

需要驗證

// Allow read/write access to a document keyed by the user's UID
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{uid} {
      allow read, write: if request.auth != null && request.auth.uid == uid;
    }
  }
}

正式版模式

// Deny read/write access to all users under any conditions
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }
  }
}

將網頁版、Android 版或 iOS 版應用程式部署至正式環境前,請採取相關步驟,確保只有應用程式用戶端可以存取 Cloud Firestore 資料。請參閱 App Check 說明文件。

如果您使用其中一個伺服器 SDK,請使用身分與存取權管理 (IAM) 保護 Cloud Firestore 中的資料。

後續步驟

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