Cloud Firestore 使用入门

本快速入门将向您展示如何设置 Cloud Firestore、添加数据,然后使用核心操作或流水线操作在 Firebase 控制台中查询您刚刚添加的数据。

创建 Cloud Firestore 数据库

  1. 如果您还没有 Firebase 项目,请创建一个,具体步骤是:在 Firebase 控制台中,点击添加项目,然后按照屏幕上的说明创建 Firebase 项目或将 Firebase 服务添加到现有 Google Cloud 项目。
  1. Firebase 控制台中打开您的项目。在左侧面板中,展开构建,然后选择 Firestore 数据库

  2. 点击创建数据库

  3. 选择企业版作为数据库模式。

  4. 选择原生模式下的 Firestore 作为操作模式,该模式支持核心操作和流水线操作。

  5. 选择数据库的位置

  6. 为您的 Cloud Firestore Security Rules选择一个初始模式:

    测试模式

    此模式适合刚开始使用移动和 Web 客户端库的用户,但会允许任何人读取和覆盖您的数据。测试完成后,请务必查看保护您的数据部分。

    如需开始使用 Web、Apple 平台或 Android SDK,请选择测试模式。

    生产模式

    拒绝来自移动和 Web 客户端的所有读写操作。经过身份验证的应用服务器 (Python) 仍然可以访问您的数据库。

    最初的一组 Cloud Firestore Security Rules将应用于您的默认 Cloud Firestore 数据库。如果您为项目创建多个数据库,则可以为每个数据库部署 Cloud Firestore Security Rules

  7. 点击创建

启用 Cloud Firestore 时,也会在 Cloud API 管理器中启用相应 API。

设置开发环境

将所需的依赖项和客户端库添加到您的应用。

Web

  1. 按照相关说明将 Firebase 添加到您的 Web 应用
  2. Cloud Firestore SDK(非公开预览版)以 npm 软件包的形式提供。

    使用以下命令在您的 npm 项目中安装 Firestore SDK。

    npm install --save firebase@eap-firestore-pipelines
iOS+
  1. 按照相关说明将 Firebase 添加到您的 iOS 应用
  2. 从 GitHub 克隆 Firebase SDK 并检出流水线分支。记下克隆到的位置,因为您需要在下一步中使用它:
    git clone https://github.com/firebase/firebase-ios-sdk.git
    # or git clone git@github.com:firebase/firebase-ios-sdk.git
    cd firebase-ios-sdk
    
    # check out pipeline feature branch
    git fetch origin feat/pipeline/private-preview
    git checkout feat/pipeline/private-preview
  3. 然后,将该目录 (firebase-ios-sdk) 作为本地依赖项添加到您的 Xcode 项目中:
    1. File(文件)菜单中选择 Add Package Dependencies(添加软件包依赖项)。
    2. 点击 Add Local…(添加本地…)按钮,然后找到您已检出的功能分支所在的 firebase-ios-sdk 目录。
Android
  1. 按照相关说明将 Firebase 添加到您的 Android 应用
  2. 从 GitHub 克隆 Firebase SDK,检出流水线分支,并将其发布到本地 Maven:
    # Prerequisites before you start:
    # Install Java 17
    # Setup Android Development environments (having proper ANDROID_HOME, etc)
    
    git clone https://github.com/firebase/firebase-android-sdk.git
    # or git clone git@github.com:firebase/firebase-android-sdk.git
    cd firebase-android-sdk
    
    # check out pipeline feature branch
    git fetch origin feat/pipeline/private-preview
    git checkout feat/pipeline/private-preview
    
    # publish firebase SDK (without crashlytics) to maven local
    ./gradlew publishToMavenLocal -x :firebase-crashlytics:publishToMavenLocal -x :firebase-crashlytics-ndk:publishToMavenLocal
    
    # Optionally, if you want crashlytics built and published to mavel local
    # Make sure you have Android NDK 21 installed
    git submodule update --init --recursive
    ./gradlew publishToMavenLocal
  3. mavenLocal 添加到项目级 settings.gradle.kts 中:
    dependencyResolutionManagement {
      repositories {
        mavenLocal() // Add this line
        ..
      }
    }
  4. 然后,添加 SDK 的本地版本:
    ...
    // Firestore 99.0.0-pipeline.preview.1 has pipelines
    implementation("com.google.firebase:firebase-firestore:99.0.0-pipeline.preview.1")
    
    // Firebase Authentication
    implementation("com.google.firebase:firebase-auth")
    ...
Python
  1. 克隆 Firestore Python SDK 并签出流水线预览分支:
    git clone https://github.com/googleapis/python-firestore.git
    # or git clone git@github.com:googleapis/python-firestore.git
    cd python-firestore
    
    # check out pipeline preview branch
    git fetch origin pipeline-preview
    git checkout pipeline-preview
  2. 安装本地 python-firestore 服务器 SDK:
    python -m pip install -e .
  3. 像往常一样安装 Firebase Python Admin SDK:
    pip install --user firebase-admin

初始化 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 替换为 Web 应用的 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");
Python

使用 Admin SDK 向企业数据库进行身份验证:

import firebase_admin
from firebase_admin import firestore

def main():
  default_app = firebase_admin.initialize_app()
  client = firestore.client(default_app, "your-new-enterprise-database")
  query = client.pipeline().database().limit(5)
  for result in query.execute():
    print(result.data())

if __name__ == "__main__":
    main()

使用核心操作添加数据

为了探索用于查询数据的核心操作和流水线操作,请使用核心操作向数据库添加数据。

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);
            }
        });
Python
doc_ref = db.collection("users").document("alovelace")
doc_ref.set({"first": "Ada", "last": "Lovelace", "born": 1815})

现在,将另一个文档添加到 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);
            }
        });
Python
doc_ref = db.collection("users").document("aturing")
doc_ref.set({"first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912})

使用核心操作读取数据

使用 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());
                }
            }
        });
Python
users_ref = db.collection("users")
docs = users_ref.stream()

for doc in docs:
    print(f"{doc.id} => {doc.to_dict()}")

使用流水线操作读取数据

现在,您可以比较流水线查询体验与核心操作查询体验。

Web

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);
    }
});
Python
pipeline = client.pipeline().collection("users")
for result in pipeline.execute():
    print(f"{result.id} => {result.data()}")

保护您的数据

如果您使用的是 Web、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;
    }
  }
}

在将 Web、Android 或 iOS 应用部署到生产环境之前,请采取措施确保只有应用客户端才能访问您的 Cloud Firestore 数据。请参阅 App Check 文档。

如果您使用的是服务器 SDK 之一,请通过 Identity and Access Management (IAM) 来保护 Cloud Firestore 中的数据。

后续步骤

通过以下主题深入了解核心操作和流水线操作: