Pierwsze kroki z Cloud Firestore

Z tego przewodnika dowiesz się, jak skonfigurować Cloud Firestore, dodać dane, a następnie użyć operacji podstawowych lub operacji potoku, aby wysłać zapytanie o dane, które właśnie zostały dodane w konsoli Firebase.

Tworzenie bazy danych Cloud Firestore

  1. Jeśli nie masz jeszcze projektu Firebase, utwórz go: w Firebasekonsoli kliknij Dodaj projekt, a potem postępuj zgodnie z instrukcjami wyświetlanymi na ekranie, aby utworzyć projekt Firebase lub dodać usługi Firebase do istniejącego projektu Google Cloud.
  1. Otwórz projekt w Firebasekonsoli. W panelu po lewej stronie rozwiń Kompilacja, a następnie kliknij Baza danych Firestore.

  2. Kliknij Utwórz bazę danych.

  3. Wybierz tryb bazy danych Enterprise.

  4. Wybierz Firestore w trybie natywnym jako tryb działania, który obsługuje operacje podstawowe i operacje potoku.

  5. Wybierz lokalizację bazy danych.

  6. Wybierz tryb początkowy Cloud Firestore Security Rules:

    Tryb testowy

    Dobre rozwiązanie na początek korzystania z bibliotek klienta mobilnego i internetowego, ale umożliwia odczytywanie i nadpisywanie danych przez dowolną osobę. Po przetestowaniu koniecznie zapoznaj się z sekcją Zabezpieczanie danych.

    Aby rozpocząć korzystanie z pakietu SDK na potrzeby internetu, platform Apple lub Androida, wybierz tryb testowy.

    Tryb produkcji

    Odrzuca wszystkie odczyty i zapisy klientów mobilnych oraz internetowych. Uwierzytelnione serwery aplikacji (Python) nadal mogą uzyskiwać dostęp do bazy danych.

    Początkowy zestaw Cloud Firestore Security Rules zostanie zastosowany do domyślnej bazy danychCloud Firestore. Jeśli utworzysz wiele baz danych w projekcie, możesz wdrożyć Cloud Firestore Security Rules dla każdej z nich.

  7. Kliknij Utwórz.

Gdy włączysz Cloud Firestore, włączy się też interfejs API w Cloud API Manager.

Konfigurowanie środowiska programistycznego

Dodaj do aplikacji wymagane zależności i biblioteki klienta.

Web

  1. Wykonaj instrukcje, aby dodać Firebase do aplikacji internetowej.
  2. Pakiet SDK Cloud Firestore w wersji testowej jest dostępny jako pakiet npm.

    Aby zainstalować pakiet SDK Firestore w projekcie npm, użyj tego polecenia:

    npm install --save firebase@eap-firestore-pipelines
iOS+
  1. Wykonaj instrukcje, aby dodać Firebase do aplikacji na iOS.
  2. Sklonuj pakiet SDK Firebase z GitHuba i sprawdź gałąź potoków. Zanotuj lokalizację, do której klonujesz repozytorium, ponieważ będzie Ci ona potrzebna w następnym kroku:
    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. Następnie dodaj katalog (firebase-ios-sdk) jako lokalną zależność do projektu Xcode:
    1. W menu Plik wybierz Dodaj zależności pakietu.
    2. Kliknij przycisk Add Local… (Dodaj lokalnie…), a następnie znajdź katalog firebase-ios-sdk z gałęzią funkcji, którą masz wyewidencjonowaną.
Android
  1. Wykonaj instrukcje, aby dodać Firebase do aplikacji na Androida.
  2. Sklonuj pakiet SDK Firebase z GitHuba, sprawdź gałąź potoków i opublikuj ją w lokalnym Mavenie:
    # 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. Dodaj mavenLocal do pliku settings.gradle.kts na poziomie projektu:
    dependencyResolutionManagement {
      repositories {
        mavenLocal() // Add this line
        ..
      }
    }
  4. Następnie dodaj lokalną wersję pakietu 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. Sklonuj pakiet SDK Firestore w Pythonie i sprawdź gałąź podglądu potoku:
    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. Zainstaluj lokalny pakiet SDK serwera python-firestore:
    python -m pip install -e .
  3. Zainstaluj pakiet Firebase Python Admin SDK w zwykły sposób:
    pip install --user firebase-admin

Zainicjuj Cloud Firestore

Zainicjuj instancję 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');

Zastąp FIREBASE_CONFIGURATION adresem firebaseConfig aplikacji internetowej.

Aby zachować dane, gdy urządzenie utraci połączenie, zapoznaj się z dokumentacją Włączanie danych offline.

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

Przeprowadź uwierzytelnianie w firmowej bazie danych za pomocą pakietu 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()

Dodawanie danych za pomocą operacji podstawowych

Aby poznać podstawowe operacje i operacje potoku do wykonywania zapytań dotyczących danych, dodaj dane do bazy danych za pomocą podstawowych operacji.

Cloud Firestore przechowuje dane w dokumentach, które są przechowywane w kolekcjach. Cloud Firestore tworzy kolekcje i dokumenty niejawnie przy pierwszym dodaniu danych do dokumentu. Nie musisz jawnie tworzyć kolekcji ani dokumentów.

Utwórz nową kolekcję i dokument, korzystając z tego przykładowego kodu.

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
Uwaga: ten produkt nie jest dostępny na platformach watchOS ani w przypadku klipów aplikacji.
// 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})

Teraz dodaj kolejny dokument do kolekcji users. Zwróć uwagę, że ten dokument zawiera parę klucz-wartość (drugie imię), która nie występuje w pierwszym dokumencie. Dokumenty w kolekcji mogą zawierać różne zestawy informacji.

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
Uwaga: ten produkt nie jest dostępny na platformach watchOS ani w przypadku klipów aplikacji.
// 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})

Odczytywanie danych za pomocą operacji podstawowych

Za pomocą przeglądarki danych w konsoli Firebase możesz szybko sprawdzić, czy dane zostały dodane do Cloud Firestore.

Możesz też użyć metody „get”, aby pobrać całą kolekcję.

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
Uwaga: ten produkt nie jest dostępny na platformach watchOS ani w przypadku klipów aplikacji.
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()}")

Odczytywanie danych za pomocą operacji potoku

Teraz możesz porównać zapytania w potoku z zapytaniami podstawowymi.

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

Zabezpieczanie danych

Jeśli używasz pakietu SDK na platformy internetowe, Android lub Apple, użyj uwierzytelniania FirebaseCloud Firestore Security Rules, aby zabezpieczyć dane w Cloud Firestore.

Oto kilka podstawowych zestawów reguł, które pomogą Ci zacząć. Reguły zabezpieczeń możesz modyfikować na karcie Reguły w konsoli.

Wymagane uwierzytelnianie

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

Tryb produkcji

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

Zanim wdrożysz aplikację internetową lub aplikację na Androida lub iOS w wersji produkcyjnej, podejmij też działania, które zapewnią, że tylko Twoi klienci aplikacji będą mieć dostęp do Cloud Firestoredanych. Zapoznaj się z dokumentacją App Check.

Jeśli używasz jednego z pakietów SDK serwera, użyj Identity and Access Management (IAM), aby zabezpieczyć dane w Cloud Firestore.

Dalsze kroki

Poszerz swoją wiedzę o działaniach związanych z usługami podstawowymi i potokami, korzystając z tych tematów: