Mulai Menggunakan Cloud Firestore

Panduan memulai ini menunjukkan cara menyiapkan Cloud Firestore, menambahkan data, lalu menggunakan operasi Core atau operasi Pipeline untuk mengkueri data yang baru saja ditambahkan di Firebase console.

Membuat database Cloud Firestore

  1. Jika belum melakukannya, buat project Firebase: Di Firebase console, klik Add project, lalu ikuti petunjuk di layar untuk membuat project Firebase atau untuk menambahkan layanan Firebase ke project Google Cloud yang ada.
  1. Buka project Anda di Firebase console. Di panel kiri, luaskan Build, lalu pilih Firestore database.

  2. Klik Create database.

  3. Pilih Enterprise untuk mode database.

  4. Pilih Firestore in Native Mode untuk mode operasi, yang mendukung operasi Core dan Pipeline.

  5. Pilih lokasi untuk database Anda.

  6. Pilih mode awal untuk Cloud Firestore Security Rules Anda:

    Mode pengujian

    Cocok untuk memulai dengan library klien seluler dan web, tetapi memungkinkan siapa pun untuk membaca dan menimpa data Anda. Setelah melakukan pengujian, pastikan untuk membaca bagian Melindungi data.

    Untuk memulai dengan web, platform Apple, atau Android SDK, pilih mode pengujian.

    Mode produksi

    Menolak semua pembacaan dan penulisan dari klien seluler dan web. Server aplikasi terautentikasi (Python) masih dapat mengakses database Anda.

    Kumpulan Cloud Firestore Security Rules awal Anda akan diterapkan ke database Cloud Firestore default. Jika Anda membuat beberapa database untuk project, Anda dapat men-deploy Cloud Firestore Security Rules untuk setiap database.

  7. Klik Create.

Saat Anda mengaktifkan Cloud Firestore, API di Pengelola Cloud API juga akan aktif.

Menyiapkan lingkungan pengembangan

Tambahkan dependensi dan library klien yang dibutuhkan ke aplikasi Anda.

Web

  1. Ikuti petunjuk untuk menambahkan Firebase ke aplikasi web Anda.
  2. Cloud Firestore SDK untuk Pratinjau Pribadi tersedia sebagai paket npm.

    Gunakan perintah berikut untuk menginstal Firestore SDK di project npm Anda.

    npm install --save firebase@eap-firestore-pipelines
iOS+
  1. Ikuti petunjuk untuk menambahkan Firebase ke aplikasi iOS Anda.
  2. Buat clone Firebase SDK dari GitHub dan periksa cabang pipeline-nya. Catat lokasi tempat Anda membuat clone-nya, karena Anda akan memerlukannya pada langkah berikutnya:
    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. Kemudian, tambahkan direktori (firebase-ios-sdk) sebagai dependensi lokal ke project Xcode Anda:
    1. Dari menu File, pilih Add Package Dependencies.
    2. Klik tombol Add Local…, lalu temukan direktori firebase-ios-sdk dengan cabang fitur yang telah Anda periksa.
Android
  1. Ikuti petunjuk untuk menambahkan Firebase ke aplikasi Android Anda.
  2. Buat clone Firebase SDK dari GitHub, periksa cabang pipeline, lalu publikasikan ke maven lokal:
    # 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. Tambahkan mavenLocal ke settings.gradle.kts tingkat project:
    dependencyResolutionManagement {
      repositories {
        mavenLocal() // Add this line
        ..
      }
    }
  4. Kemudian, tambahkan SDK versi lokal:
    ...
    // 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. Buat clone Firestore Python SDK dan periksa cabang pratinjau pipeline:
    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. Instal SDK server python-firestore lokal:
    python -m pip install -e .
  3. Instal Firebase Python Admin SDK seperti biasa:
    pip install --user firebase-admin

Lakukan inisialisasi Cloud Firestore

Lakukan inisialisasi instance 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');

Ganti FIREBASE_CONFIGURATION dengan firebaseConfig aplikasi web Anda.

Untuk mempertahankan data saat perangkat kehilangan koneksi, lihat dokumentasi Mengaktifkan Data 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

Laukan autentikasi dengan database Enterprise Anda menggunakan 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()

Menambahkan data menggunakan operasi Core

Guna mempelajari operasi Core dan operasi Pipeline untuk mengkueri data, tambahkan data ke database Anda menggunakan operasi Core.

Cloud Firestore menyimpan data dalam Documents yang disimpan di Collections. Cloud Firestore membuat koleksi dan dokumen secara implisit saat pertama kali Anda menambahkan data ke dokumen. Anda tidak perlu membuat koleksi atau dokumen secara eksplisit.

Buat koleksi baru dan dokumen menggunakan kode contoh berikut.

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
Catatan: Produk ini tidak tersedia di target watchOS dan App Clip.
// 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})

Sekarang tambahkan dokumen lain ke koleksi users. Perhatikan bahwa dokumen ini berisi key-value pair (nama tengah) yang tidak muncul di dokumen pertama. Dokumen dalam koleksi dapat berisi kumpulan informasi yang berbeda.

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
Catatan: Produk ini tidak tersedia di target watchOS dan App Clip.
// 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})

Membaca data menggunakan operasi Core

Gunakan penampil data di Firebase console untuk memverifikasi dengan cepat bahwa Anda telah menambahkan data ke Cloud Firestore.

Anda juga dapat menggunakan metode "get" untuk mengambil seluruh koleksi.

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
Catatan: Produk ini tidak tersedia di target watchOS dan App Clip.
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()}")

Membaca data menggunakan operasi Pipeline

Sekarang Anda dapat membandingkan pengalaman kueri Pipeline dengan pengalaman kueri Core.

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

Melindungi data

Jika Anda menggunakan SDK platform web, Android, atau Apple, gunakan Firebase Authentication dan Cloud Firestore Security Rules untuk melindungi data Anda di Cloud Firestore.

Berikut adalah beberapa kumpulan aturan dasar yang dapat Anda gunakan untuk memulai. Anda dapat mengubah aturan keamanan di tab Aturan konsol.

Auth diperlukan

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

Mode produksi

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

Sebelum men-deploy aplikasi web, Android, atau iOS ke produksi, lakukan juga langkah-langkah untuk memastikan bahwa hanya klien aplikasi yang dapat mengakses data Cloud Firestore Anda. Lihat dokumentasi App Check.

Jika Anda menggunakan salah satu SDK server, gunakan Identity and Access Management (IAM) untuk melindungi data di Cloud Firestore.

Langkah berikutnya

Perdalam pengetahuan Anda tentang operasi Core dan Pipeline dengan topik berikut: