יצירת מסד נתונים של Firestore באמצעות ספריית לקוח של שרת

במדריך המקוצר הזה מוסבר איך להגדיר את Firestore, להוסיף נתונים ולקרוא נתונים באמצעות ספריית לקוח של שרת ב-C#, ב-Go, ב-Java, ב-Node.js, ב-PHP, ב-Python או ב-Ruby.

לפני שמתחילים

  • נכנסים לחשבון Google Cloud . אם אתם משתמשים חדשים ב- Google Cloud, צרו חשבון כדי שתוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
  • In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

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

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

יצירת מסד נתונים של Firestore במצב Native

אם זה פרויקט חדש, צריך ליצור מופע של מסד נתונים של Firestore.

  1. כניסה לכלי לצפייה ב-Firestore

  2. במסך Select a database service (בחירת שירות מסד נתונים), בוחרים באפשרות Firestore in Native mode (‏Firestore במצב Native).

  3. בוחרים מיקום ל-Firestore.

    אם אי אפשר לבחור מיקום, סימן שהמיקום של משאבי ברירת המחדל Google Cloud בפרויקט כבר הוגדר. חלק מהמשאבים בפרויקט (כמו מופע ברירת המחדל של Firestore) חולקים תלות משותפת במיקום, ואפשר להגדיר את המיקום שלהם במהלך יצירת הפרויקט או כשמגדירים שירות אחר שחולק את התלות הזו במיקום.

  4. לוחצים על יצירת מסד נתונים.

כשיוצרים פרויקט Firestore, ה-API מופעל גם ב-Cloud API Manager.

מגדירים אימות

כדי להריץ את ספריית הלקוח, צריך קודם להגדיר אימות על ידי יצירת חשבון שירות והגדרת משתנה סביבה.

הוספה של ספריית הלקוח של השרת לאפליקציה

מוסיפים לאפליקציה את התלויות הנדרשות ואת ספריות הלקוח.

Java

מוסיפים את ספריית Java של Firestore לאפליקציה:

  • שימוש ב-Maven:
    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>com.google.cloud</groupId>
          <artifactId>libraries-bom</artifactId>
          <version>26.65.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, תוכלו לעיין בקובץ ה-README של לקוח Firestore ל-Java.
  • שימוש בסביבת פיתוח משולבת (IDE):

    אם משתמשים ב-VS Code, ב-IntelliJ או ב-Eclipse, אפשר להוסיף את ספריות הלקוח לפרויקט באמצעות יישומי הפלאגין הבאים של IDE:

    באמצעות יישומי הפלאגין תוכלו להשתמש בפונקציות נוספות, כמו ניהול מפתחות לחשבונות שירות. לפרטים נוספים, קראו את מאמרי העזרה של כל אחד מיישומי הפלאגין.

Python

מוסיפים את ספריית Python של Firestore לאפליקציה:

pip install --upgrade google-cloud-firestore

Node.js

להוסיף את ספריית Firestore Node.js לאפליקציה:

npm install --save @google-cloud/firestore
המשך

מתקינים את ספריית Go של Firestore:

go get cloud.google.com/go/firestore

להוסיף את ספריית Firestore Go לאפליקציה:

import "cloud.google.com/go/firestore"
PHP
  1. מתקינים ומפעילים את התוסף gRPC ל-PHP, שנדרש לשימוש בספריית הלקוח.
  2. מוסיפים את ספריית Firestore PHP לאפליקציה:
    composer require google/cloud-firestore
C#‎
  1. מוסיפים את ספריית Firestore C# לאפליקציה בקובץ .csproj:
    <ItemGroup>
      <PackageReference Include="Google.Cloud.Firestore" Version="1.1.0-beta01" />
    </ItemGroup>
  2. מוסיפים לקובץ Program.cs את הנתונים הבאים:
    using Google.Cloud.Firestore;
Ruby
  1. מוסיפים את ספריית Firestore Ruby לאפליקציה בקובץ Gemfile:
    gem "google-cloud-firestore"
  2. מתקינים את יחסי התלות מ-Gemfile באמצעות הפקודה:
    bundle install

הפעלה של Firestore במצב Native

מאתחלים מופע של 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
(Async)
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',
});
המשך
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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

Go

כדי לבצע אימות ב-Firestore, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

_, _, 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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

$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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

Go

כדי לבצע אימות ב-Firestore, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

_, _, 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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

$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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// 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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

Go

כדי לבצע אימות ב-Firestore, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

$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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

השלבים הבאים

כדי להעמיק את הידע שלכם, כדאי לעיין בנושאים הבאים: