תחילת העבודה עם Cloud Firestore

במדריך הזה לומדים איך להגדיר את Cloud Firestore, להוסיף נתונים ואז להשתמש בפעולות ליבה או בפעולות של צינורות כדי לשלוח שאילתה לנתונים שהוספתם במסוף Firebase.

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

  1. אם עדיין לא עשיתם זאת, אתם צריכים ליצור פרויקט ב-Firebase: במסוף Firebase, לוחצים על הוספת פרויקט ופועלים לפי ההוראות שמופיעות במסך כדי ליצור פרויקט ב-Firebase או כדי להוסיף שירותי Firebase לפרויקט Google Cloud קיים.
  1. פותחים את הפרויקט במסוף Firebase. בחלונית הימנית, מרחיבים את Build ובוחרים באפשרות Firestore database.

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

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

  4. בוחרים באפשרות Firestore במצב מקורי למצב הפעולה, שתומך בפעולות של Core ו-Pipeline.

  5. בוחרים מיקום למסד הנתונים.

  6. בוחרים מצב התחלה ל-Cloud Firestore Security Rules:

    מצב בדיקה

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

    כדי להתחיל להשתמש ב-SDK לאתרים, לפלטפורמות של אפל או ל-Android, בוחרים במצב בדיקה.

    מצב ייצור

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

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

  7. לוחצים על יצירה.

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

הגדרת סביבת הפיתוח

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

Web

  1. פועלים לפי ההוראות להוספת Firebase לאפליקציית האינטרנט.
  2. ה-SDK של Cloud Firestore לגרסת טרום-השקה פרטית זמין כחבילת npm.

    כדי להתקין את Firestore SDK בפרויקט npm, מריצים את הפקודה הבאה.

    npm install --save firebase@eap-firestore-pipelines
‫iOS+
  1. פועלים לפי ההוראות להוספת Firebase לאפליקציית iOS.
  2. משכפלים את Firebase SDK מ-GitHub ומעיינים בהסתעפות של צינורות הנתונים. חשוב לשים לב למיקום שאליו משכפלים את המאגר, כי תצטרכו אותו בשלב הבא:
    git clone https://github.com/firebase/firebase-ios-sdk.git
    # or git clone git@github.com:firebase/firebase-ios-sdk.git
    cd firebase-ios-sdk
    
    # check out pipeline feature branch
    git fetch origin feat/pipeline/private-preview
    git checkout feat/pipeline/private-preview
  3. לאחר מכן מוסיפים את הספרייה (firebase-ios-sdk) כתלות מקומית לפרויקט Xcode:
    1. בתפריט File (קובץ), בוחרים באפשרות Add Package Dependencies (הוספת תלות בחבילה).
    2. לוחצים על הלחצן Add Local… (הוספה מקומית) ומאתרים את הספרייה firebase-ios-sdk עם הענף של התכונה שהוצאתם.
Android
  1. פועלים לפי ההוראות להוספת Firebase לאפליקציית Android.
  2. משכפלים את Firebase SDK מ-GitHub, בודקים את הסתעפות הצינורות ומפרסמים אותה ב-Maven המקומי:
    # Prerequisites before you start:
    # Install Java 17
    # Setup Android Development environments (having proper ANDROID_HOME, etc)
    
    git clone https://github.com/firebase/firebase-android-sdk.git
    # or git clone git@github.com:firebase/firebase-android-sdk.git
    cd firebase-android-sdk
    
    # check out pipeline feature branch
    git fetch origin feat/pipeline/private-preview
    git checkout feat/pipeline/private-preview
    
    # publish firebase SDK (without crashlytics) to maven local
    ./gradlew publishToMavenLocal -x :firebase-crashlytics:publishToMavenLocal -x :firebase-crashlytics-ndk:publishToMavenLocal
    
    # Optionally, if you want crashlytics built and published to mavel local
    # Make sure you have Android NDK 21 installed
    git submodule update --init --recursive
    ./gradlew publishToMavenLocal
  3. מוסיפים את mavenLocal לקובץ settings.gradle.kts ברמת הפרויקט:
    dependencyResolutionManagement {
      repositories {
        mavenLocal() // Add this line
        ..
      }
    }
  4. לאחר מכן, מוסיפים את הגרסה המקומית של ה-SDK:
    ...
    // Firestore 99.0.0-pipeline.preview.1 has pipelines
    implementation("com.google.firebase:firebase-firestore:99.0.0-pipeline.preview.1")
    
    // Firebase Authentication
    implementation("com.google.firebase:firebase-auth")
    ...
Python
  1. משכפלים את Firestore Python SDK ומעיינים בענף של תצוגה מקדימה של צינור:
    git clone https://github.com/googleapis/python-firestore.git
    # or git clone git@github.com:googleapis/python-firestore.git
    cd python-firestore
    
    # check out pipeline preview branch
    git fetch origin pipeline-preview
    git checkout pipeline-preview
  2. מתקינים את ה-SDK של שרת python-firestore המקומי:
    python -m pip install -e .
  3. מתקינים את Firebase Python Admin SDK כרגיל:
    pip install --user firebase-admin

אתחול 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");
Python

אימות באמצעות Admin SDK במסד הנתונים של הארגון:

import firebase_admin
from firebase_admin import firestore

def main():
  default_app = firebase_admin.initialize_app()
  client = firestore.client(default_app, "your-new-enterprise-database")
  query = client.pipeline().database().limit(5)
  for result in query.execute():
    print(result.data())

if __name__ == "__main__":
    main()

הוספת נתונים באמצעות פעולות ליבה

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

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
הערה: המוצר הזה לא זמין ב-watchOS ובמטרות של קליפים של אפליקציות.
// 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);
            }
        });
Python
doc_ref = db.collection("users").document("alovelace")
doc_ref.set({"first": "Ada", "last": "Lovelace", "born": 1815})

עכשיו מוסיפים עוד מסמך לאוסף 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
הערה: המוצר הזה לא זמין ב-watchOS ובמטרות של קליפים של אפליקציות.
// 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);
            }
        });
Python
doc_ref = db.collection("users").document("aturing")
doc_ref.set({"first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912})

קריאת נתונים באמצעות פעולות מרכזיות

אפשר להשתמש בכלי להצגת נתונים במסוף 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
הערה: המוצר הזה לא זמין ב-watchOS ובמטרות של קליפים של אפליקציות.
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());
                }
            }
        });
Python
users_ref = db.collection("users")
docs = users_ref.stream()

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

קריאת נתונים באמצעות פעולות של צינורות

עכשיו אפשר להשוות בין חוויית השימוש בשאילתת הצינור לבין חוויית השימוש בשאילתת הליבה.

Web

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);
    }
});
Python
pipeline = client.pipeline().collection("users")
for result in pipeline.execute():
    print(f"{result.id} => {result.data()}")

אבטחת הנתונים

אם אתם משתמשים ב-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.

השלבים הבאים

כדי להרחיב את הידע שלכם בנושא פעולות ליבה וצינורות, תוכלו לעיין בנושאים הבאים: