Bu hızlı başlangıç kılavuzunda, Cloud Firestore'yı nasıl ayarlayacağınız, veri ekleyeceğiniz ve ardından Firebase konsolunda yeni eklediğiniz verileri sorgulamak için temel işlemleri veya boru hattı işlemlerini nasıl kullanacağınız gösterilmektedir.
Cloud Firestore veritabanı oluşturma
- Henüz yapmadıysanız bir Firebase projesi oluşturun: Firebase konsolunda Proje ekle'yi tıklayın, ardından ekrandaki talimatları uygulayarak bir Firebase projesi oluşturun veya Firebase hizmetlerini mevcut bir Google Cloud projesine ekleyin.
Projenizi Firebase konsolunda açın. Sol panelde Oluştur'u genişletin ve Firestore veritabanı'nı seçin.
Create database'i (Veritabanı oluştur) tıklayın.
Veritabanı modu için Enterprise'ı seçin.
İşlem modu için Yerel Modda Firestore'u seçin. Bu mod, temel ve işlem hattı işlemlerini destekler.
Veritabanınız için bir konum seçin.
Cloud Firestore Security Rules için bir başlangıç modu seçin:
- Test modu
Mobil ve web istemci kitaplıklarını kullanmaya başlamak için uygundur ancak herkesin verilerinizi okumasına ve üzerine yazmasına izin verir. Testten sonra Verilerinizin güvenliğini sağlama bölümünü incelemeyi unutmayın.
Web, Apple platformları veya Android SDK'sını kullanmaya başlamak için test modunu seçin.
- Üretim modu
Mobil ve web istemcilerinden gelen tüm okuma ve yazma işlemlerini reddeder. Kimliği doğrulanmış uygulama sunucularınız (Python), veritabanınıza erişmeye devam edebilir.
İlk Cloud Firestore Security Rules kümeniz, varsayılan Cloud Firestore veritabanınız için geçerli olur. Projeniz için birden fazla veritabanı oluşturursanız her veritabanı için Cloud Firestore Security Rules dağıtabilirsiniz.
Oluştur'u tıklayın.
Cloud Firestore'yı etkinleştirdiğinizde Cloud API Yöneticisi'nde de API etkinleştirilir.
Geliştirme ortamınızı kurma
Gerekli bağımlılıkları ve istemci kitaplıklarını uygulamanıza ekleyin.
Web
- Firebase'i web uygulamanıza ekleme talimatlarını uygulayın.
-
Özel önizleme için Cloud Firestore SDK'sı, npm paketi olarak sunulur.
Firestore SDK'yı npm projenize yüklemek için aşağıdaki komutu kullanın.
npm install --save firebase@eap-firestore-pipelines
iOS+
- Firebase'i iOS uygulamanıza ekleme talimatlarını uygulayın.
- Firebase SDK'yı GitHub'dan kopyalayın ve pipelines dalına göz atın. Bir sonraki adımda ihtiyacınız olacağından, klonladığınız konumu not edin:
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
- Ardından dizini (firebase-ios-sdk) Xcode projenize yerel bağımlılık olarak ekleyin:
- Dosya menüsünden Paket Bağımlılıkları Ekle'yi seçin.
- Add Local… (Yerel Ekle…) düğmesini tıklayın, ardından kontrol ettiğiniz özellik dalını içeren firebase-ios-sdk dizinini bulun.
Android
- Firebase'i Android uygulamanıza ekleme talimatlarını uygulayın.
- Firebase SDK'yı GitHub'dan kopyalayın, pipelines dalına göz atın ve yerel Maven'e yayınlayın:
# 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
- Proje düzeyindeki settings.gradle.kts dosyasına
mavenLocalekleyin:dependencyResolutionManagement { repositories { mavenLocal() // Add this line .. } }
- Ardından, SDK'nın yerel sürümünü ekleyin:
... // 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
- Firestore Python SDK'sını klonlayın ve ardışık düzen önizleme dalını kontrol edin:
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
- Yerel python-firestore sunucu SDK'sını yükleyin:
python -m pip install -e .
- Firebase Python Admin SDK'yı normal şekilde yükleyin:
pip install --user firebase-admin
Cloud Firestore başlatılıyor
Cloud Firestore örneğini başlatın:
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 kısmını web uygulamanızın firebaseConfig ile değiştirin.
Cihaz bağlantısını kaybettiğinde verilerin kalıcı olması için Çevrimdışı Verileri Etkinleştirme dokümanına bakın.
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
Yönetici SDK'sını kullanarak kurumsal veritabanınızla kimlik doğrulama:
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()
Temel işlemleri kullanarak veri ekleme
Verileri sorgulamak için temel işlemleri ve ardışık düzen işlemlerini keşfetmek üzere temel işlemleri kullanarak veritabanınıza veri ekleyin.
Cloud Firestore, verileri Koleksiyonlarda depolanan Belgeler'de saklar. Cloud Firestore, belgeye ilk kez veri eklediğinizde koleksiyonları ve dokümanları örtülü olarak oluşturur. Koleksiyon veya doküman oluşturmanız gerekmez.
Aşağıdaki örnek kodu kullanarak yeni bir koleksiyon ve doküman oluşturun.
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
// 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
Şimdi users koleksiyonuna başka bir belge ekleyin. Bu belgede, ilk belgede görünmeyen bir anahtar/değer çifti (ikinci ad) olduğunu unutmayın. Bir koleksiyondaki dokümanlar farklı bilgi kümeleri içerebilir.
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
// 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
Temel işlemleri kullanarak veri okuma
Cloud Firestore'a veri eklediğinizi hızlıca doğrulamak için Firebase konsolundaki veri görüntüleyiciyi kullanın.
Koleksiyonun tamamını almak için "get" yöntemini de kullanabilirsiniz.
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
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()}")
Ardışık düzen işlemlerini kullanarak veri okuma
Artık Pipeline sorgu deneyimini Core sorgu deneyimiyle karşılaştırabilirsiniz.
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()}")
Verilerinizi güvence altına alma
Web, Android veya Apple platformları SDK'sını kullanıyorsanız Firebase Authentication ve Cloud Firestore Security Rules kullanarak verilerinizi Cloud Firestore içinde güvenceye alın.
Başlamak için kullanabileceğiniz bazı temel kural kümelerini aşağıda bulabilirsiniz. Güvenlik kurallarınızı konsolun Kurallar sekmesinde değiştirebilirsiniz.
Kimlik doğrulama gerekli
// 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;
}
}
}
Üretim modu
// Deny read/write access to all users under any conditions
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
}
}
Web, Android veya iOS uygulamanızı üretime dağıtmadan önce, yalnızca uygulama istemcilerinizin Cloud Firestore verilerinize erişebildiğinden emin olmak için de adımlar atın. App Check belgelerine bakın.
Sunucu SDK'larından birini kullanıyorsanız Cloud Firestore'deki verilerinizi güvenceye almak için Kimlik ve Erişim Yönetimi (IAM)'yi kullanın.
Sonraki adımlar
Aşağıdaki konuları inceleyerek Core ve Pipeline işlemleri hakkındaki bilginizi derinleştirin:
- Temel ve İşlem Hattı işlemleri arasındaki farkları bildiğinizden emin olun.
- Temel işlemlerle sorgulama hakkında daha fazla bilgi edinin.
- Pipeline işlemleri ile sorgulama hakkında daha fazla bilgi edinin.