使用服务器客户端库创建 Firestore 数据库

本快速入门介绍如何使用 C#、Go、Java、Node.js、PHP、Python 或 Ruby 服务器客户端库设置 Firestore、添加数据和读取数据。

准备工作

  • Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  • In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  • In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

在原生模式数据库下创建 Firestore

如果是全新项目,您需要创建一个 Firestore 数据库实例。

  1. 转到 Firestore 查看器

  2. 选择数据库服务屏幕中,选择“原生模式下的 Firestore”。

  3. 选择 Firestore 的位置

    此位置设置是您项目的默认 Google Cloud Platform (GCP) 资源位置。请注意:此位置将用于项目中需要位置设置的 GCP 服务,具体地说,包括您的默认 Cloud Storage 存储分区和 App Engine 应用(如果您使用 Cloud Scheduler,就需要该应用)。

  4. 点击创建数据库

您在创建 Firestore 项目时,也会在 Cloud API Manager 中启用 API。

设置身份验证

要运行客户端库,您必须先创建服务账号并设置环境变量,以设置身份验证

Provide authentication credentials to your application code by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS. This variable applies only to your current shell session. If you want the variable to apply to future shell sessions, set the variable in your shell startup file, for example in the ~/.bashrc or ~/.profile file.

Linux 或 macOS

export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Replace KEY_PATH with the path of the JSON file that contains your credentials.

For example:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

Windows

For PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Replace KEY_PATH with the path of the JSON file that contains your credentials.

For example:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"

For command prompt:

set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH

Replace KEY_PATH with the path of the JSON file that contains your credentials.

将服务器客户端库添加到您的应用中

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

Java

将 Firestore Java 库添加到您的应用中:

  • 使用 Maven:
    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>com.google.cloud</groupId>
          <artifactId>libraries-bom</artifactId>
          <version>26.48.0</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>
    
    <dependencies>
      <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-firestore</artifactId>
      </dependency>
  • 如果您使用的是 Gradle 或在不使用 BOM 的情况下进行设置,请参阅 Firestore Java 版客户端的 README
  • 使用 IDE

    如果您使用的是 VS Code、IntelliJ 或 Eclipse,则可使用以下 IDE 插件将客户端库添加到您的项目中:

    上述插件还提供其他功能,例如服务账号密钥管理。如需了解详情,请参阅各个插件相应的文档。

Python

将 Firestore Python 库添加到您的应用中:

pip install --upgrade google-cloud-firestore

Node.js

将 Firestore Node.js 库添加到您的应用中:

npm install --save @google-cloud/firestore
Go

安装 Firestore Go 库:

go get cloud.google.com/go/firestore

将 Firestore Go 库添加到您的应用中:

import "cloud.google.com/go/firestore"
PHP
  1. 安装并启用 PHP 版 gRPC 扩展程序(您在使用客户端库时需要用到它)。
  2. 将 Firestore PHP 库添加到您的应用中:
    composer require google/cloud-firestore
C#
  1. 在您的 .csproj 文件中,将 Firestore C# 库添加到您的应用中:
    <ItemGroup>
      <PackageReference Include="Google.Cloud.Firestore" Version="1.1.0-beta01" />
    </ItemGroup>
  2. 将以下内容添加到 Program.cs 文件:
    using Google.Cloud.Firestore;
Ruby
  1. 在您的 Gemfile 中,将 Firestore Ruby 库添加到您的应用中:
    gem "google-cloud-firestore"
  2. 使用以下命令从 Gemfile 安装依赖项:
    bundle install

初始化 Firestore

初始化 Firestore 的实例:

Java
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.FirestoreOptions;
FirestoreOptions firestoreOptions =
    FirestoreOptions.getDefaultInstance().toBuilder()
        .setProjectId(projectId)
        .setCredentials(GoogleCredentials.getApplicationDefault())
        .build();
Firestore db = firestoreOptions.getService();
Python
from google.cloud import firestore

# The `project` 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 = firestore.Client(project="my-project-id")
Python
(异步)
from google.cloud import firestore

# The `project` 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 = firestore.AsyncClient(project="my-project-id")
Node.js
const Firestore = require('@google-cloud/firestore');

const db = new Firestore({
  projectId: 'YOUR_PROJECT_ID',
  keyFilename: '/path/to/keyfile.json',
});
Go
import (
	"context"
	"flag"
	"fmt"
	"log"

	"google.golang.org/api/iterator"

	"cloud.google.com/go/firestore"
)

func createClient(ctx context.Context) *firestore.Client {
	// Sets your Google Cloud Platform project ID.
	projectID := "YOUR_PROJECT_ID"

	client, err := firestore.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}
	// Close client when done with
	// defer client.Close()
	return client
}
PHP
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#
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."

添加数据

Firestore 将数据存储在文档中,而文档存储在集合中。在您首次向文档添加数据时,Firestore 就会隐式创建集合和文档。您不需要显式创建集合或文档。

使用以下示例代码创建一个新集合和一个新文档。

Java

如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

doc_ref = db.collection("users").document("alovelace")
doc_ref.set({"first": "Ada", "last": "Lovelace", "born": 1815})

Python
(Async)

doc_ref = db.collection("users").document("alovelace")
await doc_ref.set({"first": "Ada", "last": "Lovelace", "born": 1815})

Node.js

如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

const docRef = db.collection('users').doc('alovelace');

await docRef.set({
  first: 'Ada',
  last: 'Lovelace',
  born: 1815
});

Go

如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

_, _, 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

如需向 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#

如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

doc_ref = db.collection("users").document("aturing")
doc_ref.set({"first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912})

Python
(Async)

doc_ref = db.collection("users").document("aturing")
await doc_ref.set(
    {"first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912}
)

Node.js

如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

const aTuringRef = db.collection('users').doc('aturing');

await aTuringRef.set({
  'first': 'Alan',
  'middle': 'Mathison',
  'last': 'Turing',
  'born': 1912
});

Go

如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

_, _, 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

如需向 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#

如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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."

读取数据

如需快速验证您已将数据添加到 Firestore,请使用 Firebase 控制台中的数据查看器。

您还可以使用 get 方法来检索整个集合。

Java

如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

// 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

如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

users_ref = db.collection("users")
docs = users_ref.stream()

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

Python
(Async)

users_ref = db.collection("users")
docs = users_ref.stream()

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

Node.js

如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

const snapshot = await db.collection('users').get();
snapshot.forEach((doc) => {
  console.log(doc.id, '=>', doc.data());
});

Go

如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

如需向 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#

如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

users_ref = firestore.col collection_path
users_ref.get do |user|
  puts "#{user.document_id} data: #{user.data}."
end

后续步骤

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