Erste Schritte mit Cloud Firestore

In dieser Kurzanleitung erfahren Sie, wie Sie Cloud Firestore einrichten, Daten hinzufügen und dann entweder Core-Vorgänge oder Pipelinevorgänge verwenden, um die Daten abzufragen, die Sie gerade in der Firebase-Konsole hinzugefügt haben.

Cloud Firestore-Datenbank erstellen

  1. Falls noch nicht geschehen, erstellen Sie ein Firebase-Projekt: Klicken Sie in der Firebase Console auf Projekt hinzufügen und folgen Sie der Anleitung auf dem Bildschirm, um ein Firebase-Projekt zu erstellen oder Firebase-Dienste für ein vorhandenes Google Cloud-Projekt hinzuzufügen.
  1. Öffnen Sie Ihr Projekt in der Firebase-Konsole. Maximieren Sie im linken Bereich Build und wählen Sie dann Firestore-Datenbank aus.

  2. Klicken Sie auf Datenbank erstellen.

  3. Wählen Sie als Datenbankmodus Enterprise aus.

  4. Wählen Sie Firestore im nativen Modus als Betriebsmodus aus, der Core- und Pipeline-Vorgänge unterstützt.

  5. Wählen Sie einen Speicherort für Ihre Datenbank aus.

  6. Wählen Sie einen Startmodus für Ihr Cloud Firestore Security Rules aus:

    Testmodus

    Gut für die ersten Schritte mit den Mobil- und Web-Clientbibliotheken, allerdings können Ihre Daten von beliebigen Personen gelesen und überschrieben werden. Prüfen Sie nach dem Test den Abschnitt Daten schützen.

    Wenn Sie das Web-, Apple-Plattform- oder Android SDK verwenden möchten, wählen Sie den Testmodus aus.

    Produktionsmodus

    Verweigert alle Lese- und Schreibvorgänge von Mobil- und Webclients. Ihre authentifizierten Anwendungsserver (Python) können weiterhin auf Ihre Datenbank zugreifen.

    Ihre erste Gruppe von Cloud Firestore Security Rules wird auf Ihre Standarddatenbank Cloud Firestore angewendet. Wenn Sie mehrere Datenbanken für Ihr Projekt erstellen, können Sie Cloud Firestore Security Rules für jede Datenbank bereitstellen.

  7. Klicken Sie auf Erstellen.

Wenn Sie Cloud Firestore aktivieren, wird auch die API im Cloud API Manager aktiviert.

Entwicklungsumgebung einrichten

Fügen Sie Ihrer Anwendung die erforderlichen Abhängigkeiten und Clientbibliotheken hinzu.

Web

  1. Folgen Sie der Anleitung unter Firebase zu meiner Web-App hinzufügen.
  2. Das Cloud Firestore SDK für die private Vorschau ist als NPM-Paket verfügbar.

    Verwenden Sie den folgenden Befehl, um das Firestore SDK in Ihrem npm-Projekt zu installieren.

    npm install --save firebase@eap-firestore-pipelines
iOS+
  1. Folgen Sie der Anleitung unter Firebase zu meiner iOS-Anwendung hinzufügen.
  2. Klonen Sie das Firebase SDK von GitHub und checken Sie den Pipelines-Zweig aus. Notieren Sie sich den Speicherort, an den Sie das Repository klonen, da Sie ihn im nächsten Schritt benötigen:
    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. Fügen Sie dann das Verzeichnis (firebase-ios-sdk) als lokale Abhängigkeit zu Ihrem Xcode-Projekt hinzu:
    1. Wählen Sie im Menü Datei die Option Paketabhängigkeiten hinzufügen aus.
    2. Klicken Sie auf die Schaltfläche Add Local… (Lokal hinzufügen…) und suchen Sie dann das Verzeichnis „firebase-ios-sdk“ mit dem Feature-Branch, den Sie ausgecheckt haben.
Android
  1. Folgen Sie der Anleitung unter Firebase zu meiner Android-Anwendung hinzufügen.
  2. Klonen Sie das Firebase SDK von GitHub, checken Sie den Pipelines-Zweig aus und veröffentlichen Sie ihn im lokalen Maven-Repository:
    # 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. Fügen Sie mavenLocal der settings.gradle.kts auf Projektebene hinzu:
    dependencyResolutionManagement {
      repositories {
        mavenLocal() // Add this line
        ..
      }
    }
  4. Fügen Sie dann die lokale Version des SDK hinzu:
    ...
    // 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. Klonen Sie das Firestore Python SDK und prüfen Sie den Pipeline-Vorschauzweig:
    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. Installieren Sie das lokale Python-Firestore-Server-SDK:
    python -m pip install -e .
  3. Installieren Sie das Firebase Python Admin SDK wie gewohnt:
    pip install --user firebase-admin

Cloud Firestore initialisieren

Initialisieren Sie eine Instanz von 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');

Ersetzen Sie FIREBASE_CONFIGURATION durch die firebaseConfig Ihrer Webanwendung.

Informationen zum dauerhaften Sichern von Daten für den Fall, dass die Verbindung des Geräts unterbrochen wird, finden Sie in der Dokumentation Offlinedaten aktivieren.

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

Authentifizieren Sie sich mit dem Admin SDK bei Ihrer Unternehmensdatenbank:

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()

Daten mit Core-Vorgängen hinzufügen

Wenn Sie Core-Vorgänge und Pipeline-Vorgänge zum Abfragen von Daten untersuchen möchten, fügen Sie Ihrer Datenbank mit Core-Vorgängen Daten hinzu.

In Cloud Firestore werden Daten in Dokumenten gespeichert, die wiederum in Sammlungen gespeichert sind. Cloud Firestore erstellt Sammlungen und Dokumente implizit, wenn Sie dem Dokument zum ersten Mal Daten hinzufügen. Sie müssen Sammlungen oder Dokumente also nicht explizit anlegen.

Mit dem folgenden Beispielcode können Sie eine neue Sammlung und ein Dokument erstellen.

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
Hinweis: Dieses Produkt nicht ist auf WatchOS- und App Clip-Zielen verfügbar.
// 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})

Fügen Sie jetzt der Sammlung users ein weiteres Dokument hinzu. Beachten Sie, dass dieses Dokument ein Schlüssel/Wert-Paar (zweiter Vorname) enthält, das im ersten Dokument nicht auftaucht. Dokumente in einer Sammlung können unterschiedliche Informationen enthalten.

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
Hinweis: Dieses Produkt nicht ist auf WatchOS- und App Clip-Zielen verfügbar.
// 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})

Daten mit Core-Vorgängen lesen

Verwenden Sie die Datenansicht in der Firebase Console, um schnell zu prüfen, ob Sie Daten zu Cloud Firestore hinzugefügt haben.

Sie können auch die Methode „get“ verwenden, um die gesamte Sammlung abzurufen.

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
Hinweis: Dieses Produkt nicht ist auf WatchOS- und App Clip-Zielen verfügbar.
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()}")

Daten mit Pipeline-Vorgängen lesen

Sie können jetzt die Pipeline-Abfrage mit der Core-Abfrage vergleichen.

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()}")

Daten schützen

Wenn Sie das SDK für Web-, Android- oder Apple-Plattformen verwenden, schützen Sie Ihre Daten in Cloud Firestore mit Firebase Authentication und Cloud Firestore Security Rules.

Hier sind einige grundlegende Regelsätze, die Sie für den Einstieg verwenden können. Sie können Ihre Sicherheitsregeln auf dem Tab „Regeln“ der Konsole ändern.

Auth erforderlich

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

Produktionsmodus

// Deny read/write access to all users under any conditions
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }
  }
}

Bevor Sie Ihre Web-, Android- oder iOS-App in der Produktion bereitstellen, sollten Sie auch dafür sorgen, dass nur Ihre App-Clients auf Ihre Cloud Firestore-Daten zugreifen können. Weitere Informationen finden Sie in der App Check-Dokumentation.

Wenn Sie eines der Server-SDKs verwenden, nutzen Sie die Identitäts- und Zugriffsverwaltung (Identity and Access Management, IAM), um Ihre Daten in Cloud Firestore zu schützen.

Nächste Schritte

Vertiefen Sie Ihr Wissen über Core- und Pipeline-Vorgänge mit den folgenden Themen: