使用服务器客户端库开始使用 Cloud Firestore 标准版

本快速入门将向您展示如何设置 Cloud Firestore 企业版、添加数据,然后使用 C#、Go、Java、Node.js、PHP、Python 和 Ruby 的服务器客户端库在 Firebase 控制台中查看您刚刚添加的数据。

您可以使用这些客户端库设置特权服务器环境,以便全面访问您的数据库。

创建 Cloud Firestore 数据库

  1. 如果您还没有 Firebase 项目,请创建一个,具体步骤是:在 Firebase 控制台中,点击添加项目,然后按照屏幕上的说明创建 Firebase 项目或将 Firebase 服务添加到现有 Google Cloud 项目。

  2. Firebase 控制台中打开您的项目。在左侧面板中,展开构建,然后选择 Firestore 数据库

  3. 点击创建数据库

  4. 选择数据库的位置

    如果您无法选择位置,则表明项目的“默认 Google Cloud 资源位置”已经设置。您的项目的部分资源(例如默认 Cloud Firestore 实例)共享一个通用位置依赖项,并且可以在项目创建期间或设置共享此位置依赖项的其他服务时设置其位置。

  5. 为您的 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

  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. 将 Firebase Admin SDK 添加到您的 Go 应用中:
    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 和管理 > 服务账号。生成一个新的私钥并保存该 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 和管理 > 服务账号。生成一个新的私钥并保存该 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 和管理 > 服务账号。生成一个新的私钥并保存该 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
  • 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 和管理 > 服务账号。生成一个新的私钥并保存该 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

    后续步骤

    通过以下各主题深入了解相关知识: