本快速入门将向您展示如何设置 Cloud Firestore 企业版、添加数据,然后使用 C#、Go、Java、Node.js、PHP、Python 和 Ruby 的服务器客户端库在 Firebase 控制台中查看您刚刚添加的数据。
您可以使用这些客户端库设置特权服务器环境,以便全面访问您的数据库。
创建 Cloud Firestore 数据库
如果您还没有 Firebase 项目,请创建一个,具体步骤是:在 Firebase 控制台中,点击添加项目,然后按照屏幕上的说明创建 Firebase 项目或将 Firebase 服务添加到现有 Google Cloud 项目。
在 Firebase 控制台中打开您的项目。在左侧面板中,展开构建,然后选择 Firestore 数据库。
点击创建数据库。
选择数据库的位置。
如果您无法选择位置,则表明项目的“默认 Google Cloud 资源位置”已经设置。您的项目的部分资源(例如默认 Cloud Firestore 实例)共享一个通用位置依赖项,并且可以在项目创建期间或设置共享此位置依赖项的其他服务时设置其位置。
为您的 Cloud Firestore Security Rules选择一个初始模式:
- 测试模式
此模式适合刚开始使用移动和 Web 客户端库的用户,但会允许任何人读取和覆盖您的数据。测试完成后,请务必查看保护您的数据部分。
如需开始使用 Web、Apple 平台或 Android SDK,请选择测试模式。
- 生产模式
拒绝来自移动和 Web 客户端的所有读写操作。经过身份验证的应用服务器(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。
点击创建。
启用 Cloud Firestore 时,也会在 Cloud API 管理器中启用相应 API。
设置开发环境
将所需的依赖项和客户端库添加到您的应用。
Java
- 将 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>
- 使用 Gradle:
- 按照以下说明在您的环境中使用适当的凭据初始化 Cloud Firestore。
Python
- 将 Firebase Admin SDK 添加到您的 Python 应用中:
pip install --upgrade firebase-admin
- 按照以下说明在您的环境中使用适当的凭据初始化 Cloud Firestore。
Node.js
-
将 Firebase Admin SDK 添加到您的应用中:
npm install firebase-admin --save
- 按照以下说明在您的环境中使用适当的凭据初始化 Cloud Firestore。
Go
- 将 Firebase Admin SDK 添加到您的 Go 应用中:
go get firebase.google.com/go
- 按照以下说明在您的环境中使用适当的凭据初始化 Cloud Firestore。
PHP
- 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 上运行应用,则无需进行身份验证。否则,请设置服务账号。
-
如需从开发环境中进行身份验证,请将
- 安装并启用 PHP 版 gRPC 扩展程序(您在使用客户端库时需用到它)。
- 将 Cloud Firestore PHP 库添加到您的应用中:
composer require google/cloud-firestore
Ruby
- 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 上运行应用,则无需进行身份验证。否则,请设置服务账号。
-
如需从开发环境中进行身份验证,请将
- 在您的
Gemfile中,将 Cloud Firestore Ruby 库添加到您的应用中:gem "google-cloud-firestore"
-
使用以下命令从
Gemfile安装依赖项:bundle install
(可选)使用 Firebase Local Emulator Suite 进行原型设计和测试
对于移动开发者,在介绍应用如何对 Cloud Firestore 执行读写操作之前,我们先介绍一套可用于对 Cloud Firestore 功能进行原型设计和测试的工具:Firebase Local Emulator Suite。如果您在尝试使用不同的数据模型、优化安全规则,或设法寻找最经济有效的方式与后端进行交互,那么无需实际部署即可在本地进行上述工作是非常理想的。
Cloud Firestore 模拟器是 Local Emulator Suite 的一部分,通过该模拟器,您的应用可以与模拟的数据库内容和配置进行交互,并可视需要与您的模拟项目资源(函数、其他数据库和安全规则)进行交互。
如需使用 Cloud Firestore 模拟器,只需完成几个步骤:
- 向应用的测试配置添加一行代码以连接到模拟器。
- 从本地项目的根目录运行
firebase emulators:start。 - 照常使用 Cloud Firestore 平台 SDK 从应用的原型设计代码进行调用。
我们提供详细的 Cloud Firestore 和 Cloud Functions 演示。您还应该参阅 Local Emulator Suite 简介。
初始化 Cloud Firestore
初始化 Cloud Firestore 的实例:
Java
Cloud Firestore SDK 可通过不同的方式初始化,具体取决于您的环境。以下是最常用的一些方法。如需查看完整的参考文档,请参阅初始化 Admin SDK。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 和管理 > 服务账号。生成一个新的私钥并保存该 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。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 和管理 > 服务账号。生成一个新的私钥并保存该 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。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 和管理 > 服务账号。生成一个新的私钥并保存该 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 和管理 > 服务账号。生成一个新的私钥并保存该 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。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 和管理 > 服务账号。生成一个新的私钥并保存该 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 客户端库。
C#
C#
如需详细了解如何安装和创建 Cloud Firestore 客户端,请参阅 Cloud Firestore 客户端库。
Ruby
添加数据
Cloud Firestore 将数据存储在文档中,而文档存储在集合中。在您首次向文档添加数据时,Cloud Firestore 就会隐式创建集合和文档。您不需要显式创建集合或文档。
使用以下示例代码创建一个新集合和一个新文档。
Java
Python
Python
Node.js
Go
PHP
PHP
如需详细了解如何安装和创建 Cloud Firestore 客户端,请参阅 Cloud Firestore 客户端库。
C#
Ruby
现在,将另一个文档添加到 users 集合中。请注意,此文档包含第一个文档中没有的一个键值对(中间名)。集合中的文档可以包含不同的信息集。
Java
Python
Python
Node.js
Go
PHP
PHP
如需详细了解如何安装和创建 Cloud Firestore 客户端,请参阅 Cloud Firestore 客户端库。
C#
Ruby
读取数据
使用 Firebase 控制台中的数据查看器可以快速验证您是否已将数据添加到 Cloud Firestore。
您也可以使用“get”方法来检索整个集合。
Java
Python
users_ref = db.collection("users") docs = users_ref.stream() for doc in docs: print(f"{doc.id} => {doc.to_dict()}")
Python
Node.js
Go
PHP
PHP
如需详细了解如何安装和创建 Cloud Firestore 客户端,请参阅 Cloud Firestore 客户端库。
C#
Ruby
后续步骤
通过以下各主题深入了解相关知识:
- 数据模型 - 详细了解 Cloud Firestore 中数据的结构组织形式,包括分层数据和子集合。
- 添加数据 - 详细了解如何在 Cloud Firestore 中创建和更新数据。
- 获取数据 - 详细了解如何检索数据。
- 执行简单查询和复合查询 - 了解如何运行简单查询和复合查询。
- 对查询结果进行排序和限制其数量 - 了解如何对查询返回的数据进行排序和限制其数量。