במדריך הזה מוסבר איך להגדיר את מהדורת Enterprise של Cloud Firestore, להוסיף נתונים ואז להשתמש בפעולות ליבה או בפעולות של צינור עיבוד נתונים כדי לשלוף את הנתונים שהוספתם זה עתה במסוף Firebase.
Cloud Firestore תומך בערכות SDK לנייד או לאינטרנט ובספריות לקוח לשרת:
Cloud Firestore תומך בערכות SDK ל-Android, ל-iOS ולאינטרנט ועוד. בשילוב עם Cloud Firestore Security Rules ועם Firebase Authentication, ערכות ה-SDK לנייד ולאינטרנט תומכות בארכיטקטורות של אפליקציות ללא שרתים, שבהן לקוחות מתחברים ישירות למסד הנתונים Cloud Firestore.
Cloud Firestore תומך בספריות לקוח של שרת עבור Java, Node.js ו-Python. אפשר להשתמש בספריות הלקוח האלה כדי להגדיר סביבות שרת עם הרשאות מלאות וגישה מלאה למסד הנתונים. מידע נוסף על הספריות האלה זמין במאמר תחילת העבודה עם ספריות לקוח לשרת.
יצירת מסד נתונים במהדורת Cloud Firestore Enterprise
אם עדיין לא עשיתם זאת, אתם צריכים ליצור פרויקט ב-Firebase: במסוף Firebase, לוחצים על הוספת פרויקט ופועלים לפי ההוראות שמופיעות במסך כדי ליצור פרויקט ב-Firebase או כדי להוסיף שירותי Firebase לפרויקט Google Cloud קיים.
פותחים את הפרויקט במסוף Firebase. בחלונית הימנית, מרחיבים את Build ובוחרים באפשרות Firestore database.
לוחצים על יצירת מסד נתונים.
בוחרים באפשרות Enterprise למצב מסד הנתונים.
בוחרים באפשרות Firestore in Native Mode (Firestore במצב מקורי) למצב הפעולה, שתומך בפעולות Core ו-Pipeline.
בוחרים מיקום למסד הנתונים.
בוחרים מצב התחלה ל-Cloud Firestore Security Rules:
- מצב בדיקה
מתאים להתחלת העבודה עם ספריות לקוח לנייד ולאינטרנט, אבל מאפשר לכל אחד לקרוא ולשכתב את הנתונים. אחרי הבדיקה, חשוב לעיין בסעיף הגנה על הנתונים.
כדי להתחיל להשתמש ב-SDK לאתרים, לפלטפורמות של אפל או ל-Android, בוחרים במצב בדיקה.
- מצב ייצור
דוחה את כל פעולות הקריאה והכתיבה מלקוחות ניידים ומלקוחות אינטרנט. שרתי האפליקציות המאומתים (Python) עדיין יכולים לגשת למסד הנתונים.
הסט הראשוני של Cloud Firestore Security Rules יחול על מסד הנתונים שמוגדר כברירת מחדל Cloud Firestore. אם יוצרים כמה מסדי נתונים לפרויקט, אפשר לפרוס Cloud Firestore Security Rules לכל מסד נתונים.
לוחצים על יצירה.
כשמפעילים את מהדורת Cloud Firestore Enterprise, המערכת מפעילה גם את ה-API בCloud API Manager.
הגדרת סביבת הפיתוח
מוסיפים לאפליקציה את התלויות הנדרשות ואת ספריות הלקוח.
Web
- פועלים לפי ההוראות להוספת Firebase לאפליקציית האינטרנט.
-
SDK Cloud Firestore זמין כחבילת npm.
צריך לייבא גם את Firebase וגם את Cloud Firestore.npm install firebase@12.9.0 --save
import { initializeApp } from "firebase/app"; import { getFirestore } from "firebase/firestore";
iOS+
פועלים לפי ההוראות להוספת Firebase לאפליקציית Apple.
משתמשים ב-Swift Package Manager כדי להתקין ולנהל יחסי תלות ב-Firebase.
- ב-Xcode, כשפרויקט האפליקציה פתוח, עוברים אל File > Swift Packages > Add Package Dependency (קובץ > חבילות Swift > הוספת תלות בחבילה).
- כשמוצגת בקשה, מוסיפים את מאגר Firebase Apple platforms SDK:
- בוחרים את ספריית Firestore.
- אחרי שתסיימו, פלטפורמת Xcode תתחיל באופן אוטומטי לטפל ביחסי התלות ולהוריד אותם ברקע.
https://github.com/firebase/firebase-ios-sdk
Android
- פועלים לפי ההוראות להוספת Firebase לאפליקציית Android.
- באמצעות Firebase Android BoM, מצהירים על התלות בספרייה Cloud Firestore ל-Android בקובץ Gradle של המודול (ברמת האפליקציה) (בדרך כלל
app/build.gradle.ktsאוapp/build.gradle).dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.8.0")) // Declare the dependency for the Cloud Firestore library // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-firestore") }
אם משתמשים בFirebase Android BoM, האפליקציה תמיד תשתמש בגרסאות תואמות של ספריות Firebase Android.
(חלופה) מצהירים על תלות של הפרויקט בספריות Firebase בלי להשתמש ב- BoM
אם לא משתמשים ב-Firebase BoM, צריך לציין את הגרסה של כל ספריית Firebase בשורת התלות שלה.
הערה: אם אתם משתמשים בכמה ספריות Firebase באפליקציה, מומלץ מאוד להשתמש ב-BoM כדי לנהל את גרסאות הספריות, וכך לוודא שכל הגרסאות תואמות.
dependencies { // Declare the dependency for the Cloud Firestore library // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-firestore:26.1.0") }
מחפשים מודול ספריות ספציפי ל-Kotlin? החל מגרסת אוקטובר 2023, מפתחי Kotlin ומפתחי Java יכולים להסתמך על מודול הספרייה הראשי (פרטים נוספים זמינים בשאלות הנפוצות בנושא).
אתחול 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 ב-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");
הוספת נתונים באמצעות פעולות ליבה
כדי לבחון פעולות ליבה ופעולות של צינורות להעברת נתונים לצורך שליפת נתונים, צריך להוסיף נתונים למסד הנתונים באמצעות פעולות ליבה.
Cloud Firestore מאחסן נתונים ב-Documents, שמאוחסנים ב-Collections. 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
// 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); } });
עכשיו מוסיפים עוד מסמך לאוסף 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
// 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); } });
קריאת נתונים באמצעות פעולות מרכזיות
אפשר להשתמש בכלי להצגת נתונים במסוף 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
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()); } } });
קריאת נתונים באמצעות פעולות של צינורות
עכשיו אפשר להשוות בין חוויית השימוש בשאילתת הצינור לבין חוויית השימוש בשאילתת הליבה.
Web
// The import/require of "firebase/firestore/pipelines" has a side-effect // of extending the Firestore class with the `.pipeline()` method. // Without this import/require, you will not be able to create a Pipeline. // import { execute } from "firebase/firestore/pipelines"; 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); } });
אבטחת הנתונים בערכות SDK לנייד ולאינטרנט
אם אתם משתמשים ב-SDK של פלטפורמות האינטרנט, Android או Apple, אתם יכולים להשתמש באימות ב-Firebase וב-Cloud Firestore Security Rules כדי לאבטח את הנתונים ב-Cloud Firestore.
ריכזנו כאן כמה קבוצות כללים בסיסיות שתוכלו להשתמש בהן כדי להתחיל. אפשר לשנות את כללי האבטחה בכרטיסייה Rules במסוף.
נדרש אימות
// 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;
}
}
}
לפני שפורסים את אפליקציית האינטרנט, Android או iOS בסביבת הייצור, צריך גם לבצע פעולות כדי לוודא שרק לקוחות האפליקציה יכולים לגשת לנתוני Cloud Firestore. מידע נוסף זמין במאמרי העזרה בנושא App Check.
אם אתם משתמשים באחת מערכות ה-SDK של השרת, אתם יכולים להשתמש בניהול זהויות והרשאות גישה (IAM) כדי לאבטח את הנתונים ב-Cloud Firestore.
השלבים הבאים
כדי להרחיב את הידע שלכם בנושא פעולות מרכזיות ופעולות של צינורות, תוכלו לעיין בנושאים הבאים: