بدء استخدام Cloud Firestore

يوضّح لك هذا الدليل السريع كيفية إعداد Cloud Firestore وإضافة البيانات، ثم استخدام إما "العمليات الأساسية" أو "عمليات خط الأنابيب" للاستعلام عن البيانات التي أضفتها للتو في وحدة تحكّم Firebase.

إنشاء قاعدة بيانات Cloud Firestore

  1. إذا لم يسبق لك إنشاء مشروع على Firebase، أنشئ مشروعًا باتّباع الخطوات التالية: في Firebaseوحدة التحكّم، انقر على إضافة مشروع، ثم اتّبِع التعليمات الظاهرة على الشاشة لإنشاء مشروع على Firebase أو لإضافة خدمات Firebase إلى مشروع Google Cloud حالي.
  1. افتح مشروعك في وحدة تحكّم Firebase. في اللوحة اليمنى، وسِّع إنشاء، ثم اختَر قاعدة بيانات Firestore.

  2. انقر على إنشاء قاعدة بيانات.

  3. اختَر المؤسسة لوضع قاعدة البيانات.

  4. اختَر Firestore في الوضع الأصلي لوضع التشغيل الذي يتيح عمليات Core وPipeline.

  5. اختَر موقعًا جغرافيًا لقاعدة البيانات.

  6. اختَر وضعًا لبدء Cloud Firestore Security Rules:

    وضع الاختبار

    هذه الطريقة مناسبة للبدء باستخدام مكتبات البرامج للعملاء على الأجهزة الجوّالة والويب، ولكنّها تتيح لأي شخص قراءة بياناتك واستبدالها. بعد إجراء الاختبار، احرص على مراجعة قسم تأمين بياناتك.

    لبدء استخدام حزمة تطوير البرامج (SDK) على الويب أو منصات Apple أو Android، اختَر وضع الاختبار.

    وضع الإنتاج

    يتم رفض جميع عمليات القراءة والكتابة من تطبيقات الأجهزة الجوّالة وعملاء الويب. ستظل خوادم التطبيقات التي تمّت المصادقة عليها (Python) قادرة على الوصول إلى قاعدة البيانات.

    سيتم تطبيق مجموعة Cloud Firestore Security Rules الأولية على قاعدة بيانات Cloud Firestore التلقائية. إذا أنشأت قواعد بيانات متعددة لمشروعك، يمكنك نشر Cloud Firestore Security Rules لكل قاعدة بيانات.

  7. انقر على إنشاء.

عند تفعيل Cloud Firestore، يتم أيضًا تفعيل واجهة برمجة التطبيقات في Cloud API Manager.

إعداد بيئة التطوير

أضِف التبعيات ومكتبات البرامج المطلوبة إلى تطبيقك.

Web

  1. اتّبِع التعليمات لإضافة Firebase إلى تطبيق الويب.
  2. تتوفّر حزمة تطوير البرامج (SDK) الخاصة بـ Cloud Firestore في "البرنامج التجريبي الخاص" كحزمة npm.

    استخدِم الأمر التالي لتثبيت حزمة تطوير البرامج (SDK) الخاصة بخدمة Firestore في مشروع npm.

    npm install --save firebase@eap-firestore-pipelines
iOS+‎
  1. اتّبِع التعليمات لإضافة Firebase إلى تطبيق iOS.
  2. استنسِخ حزمة تطوير البرامج (SDK) لمنصّة Firebase من 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. انقر على الزر إضافة ملف محلي…، ثم ابحث عن دليل firebase-ios-sdk الذي يتضمّن فرع الميزة الذي تم استخراجه.
Android
  1. اتّبِع التعليمات لإضافة Firebase إلى تطبيق Android.
  2. استنسِخ حزمة تطوير البرامج (SDK) لمنصة Firebase من 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. أنشئ نسخة طبق الأصل من حزمة تطوير البرامج (SDK) الخاصة بلغة Python في Firestore، واطّلِع على فرع معاينة خط أنابيب الإنتاج:
    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. ثبِّت حزمة تطوير البرامج (SDK) الخاصة بمدير Firebase في Python كالمعتاد:
    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

المصادقة باستخدام قاعدة بيانات مؤسستك من خلال حزمة 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()

إضافة البيانات باستخدام العمليات الأساسية

لاستكشاف عمليات Core وعمليات Pipeline للاستعلام عن البيانات، أضِف بيانات إلى قاعدة البيانات باستخدام عمليات Core.

تخزّن Cloud Firestore البيانات في مستندات، ويتم تخزين هذه المستندات في مجموعات. تنشئ 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()}")

قراءة البيانات باستخدام عمليات Pipeline

يمكنك الآن مقارنة تجربة طلب البحث في &quot;مسار الإحالة الناجحة&quot; بتجربة طلب البحث في &quot;التقارير الأساسية&quot;.

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 Authentication وCloud Firestore Security Rules لتأمين بياناتك في Cloud Firestore.

في ما يلي بعض مجموعات القواعد الأساسية التي يمكنك استخدامها للبدء. يمكنك تعديل قواعد الأمان في علامة التبويب القواعد في وحدة التحكّم.

يجب إكمال عملية المصادقة

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

الخطوات التالية

يمكنك تعميق معرفتك بعمليات Core وPipeline من خلال المواضيع التالية: