คู่มือเริ่มใช้งานฉบับย่อนี้จะแสดงวิธีตั้งค่า Firestore รุ่น Enterprise, เพิ่มข้อมูล แล้วใช้การดำเนินการหลักหรือการดำเนินการไปป์ไลน์เพื่อค้นหาข้อมูลที่คุณเพิ่งเพิ่มในคอนโซล Firebase
Cloud Firestore รองรับ SDK บนอุปกรณ์เคลื่อนที่หรือเว็บ และไลบรารีของไคลเอ็นต์เซิร์ฟเวอร์ ดังนี้
Cloud Firestore รองรับ SDK สำหรับ Android, iOS, เว็บ และอื่นๆ เมื่อใช้ร่วมกับ Cloud Firestore Security Rules และ Firebase Authentication แล้ว SDK บนอุปกรณ์เคลื่อนที่และเว็บจะรองรับ สถาปัตยกรรมแอปแบบไม่ต้องใช้เซิร์ฟเวอร์ ซึ่งไคลเอ็นต์จะเชื่อมต่อกับฐานข้อมูล Cloud Firestore โดยตรง
Cloud Firestore รองรับไลบรารีของไคลเอ็นต์เซิร์ฟเวอร์ สำหรับ Java, Node.js และ Python ใช้ไลบรารีของไคลเอ็นต์เหล่านี้เพื่อตั้งค่าสภาพแวดล้อมเซิร์ฟเวอร์ที่มีสิทธิ์เข้าถึงฐานข้อมูลได้อย่างเต็มที่ ดูข้อมูลเพิ่มเติมเกี่ยวกับไลบรารีเหล่านี้ ได้ในการเริ่มต้นอย่างรวดเร็วสำหรับไลบรารีของไคลเอ็นต์เซิร์ฟเวอร์
สร้างฐานข้อมูล Firestore รุ่น Enterprise
หากยังไม่ได้สร้างโปรเจ็กต์ Firebase ให้สร้างใน Firebaseคอนโซล โดยคลิกเพิ่มโปรเจ็กต์ แล้วทำตามวิธีการบนหน้าจอเพื่อสร้างโปรเจ็กต์ Firebase หรือ เพิ่มบริการ Firebase ลงในโปรเจ็กต์Google Cloudที่มีอยู่
เปิดโปรเจ็กต์ในคอนโซล Firebase ในแผงด้านซ้าย ให้ขยาย Build แล้วเลือก ฐานข้อมูล Firestore
คลิกสร้างฐานข้อมูล
เลือกEnterprise สำหรับโหมดฐานข้อมูล
เลือกFirestore ในโหมดดั้งเดิม สำหรับโหมดการดำเนินการ ซึ่งรองรับการดำเนินการหลักและการดำเนินการ Pipeline
เลือกตำแหน่งสำหรับฐานข้อมูล
เลือกโหมดเริ่มต้นสำหรับ Cloud Firestore Security Rules
- โหมดทดสอบ
เหมาะสำหรับการเริ่มต้นใช้งานไลบรารีของไคลเอ็นต์บนอุปกรณ์เคลื่อนที่และเว็บ แต่จะอนุญาตให้ทุกคนอ่านและเขียนทับข้อมูลของคุณได้ หลังจากทดสอบแล้ว อย่าลืม ตรวจสอบส่วน รักษาความปลอดภัยให้ข้อมูล
หากต้องการเริ่มต้นใช้งาน SDK บนเว็บ, แพลตฟอร์ม Apple หรือ Android ให้เลือกโหมดทดสอบ
- โหมดโปรดักชัน
ปฏิเสธการอ่านและการเขียนทั้งหมดจากไคลเอ็นต์บนอุปกรณ์เคลื่อนที่และเว็บ เซิร์ฟเวอร์แอปพลิเคชันที่ตรวจสอบสิทธิ์แล้ว (Python) จะยังคงเข้าถึงฐานข้อมูลได้
ชุดกฎความปลอดภัยของ Cloud Firestore เริ่มต้นจะมีผลกับฐานข้อมูล Cloud Firestore เริ่มต้นCloud Firestore Security RulesCloud Firestore หากสร้างฐานข้อมูลหลายรายการสำหรับโปรเจ็กต์ คุณสามารถติดตั้งใช้งาน Cloud Firestore Security Rules สำหรับฐานข้อมูลแต่ละรายการได้
คลิกสร้าง
เมื่อเปิดใช้ Firestore รุ่น Enterprise ระบบจะเปิดใช้ API ใน Cloud API Manager ด้วย
ตั้งค่าสภาพแวดล้อมในการพัฒนาซอฟต์แวร์
เพิ่มทรัพยากร Dependency และไลบรารีของไคลเอ็นต์ที่จำเป็นลงในแอป
Web
iOS+
ทำตามวิธีการเพิ่ม Firebase ลงในแอป Apple
ใช้ Swift Package Manager เพื่อติดตั้งและจัดการทรัพยากร Dependency ของ Firebase
- เปิดโปรเจ็กต์แอปใน Xcode แล้วไปที่ File > Swift Packages > Add Package Dependency
- เมื่อได้รับข้อความแจ้ง ให้เพิ่มที่เก็บ Firebase Apple Platforms SDK ดังนี้
- เลือกไลบรารี Firestore
- เมื่อเสร็จแล้ว Xcode จะเริ่มจับคู่ข้อมูลและดาวน์โหลด ทรัพยากร Dependency ในเบื้องหลังโดยอัตโนมัติ
https://github.com/firebase/firebase-ios-sdk
Android
- ทำตามวิธีการเพิ่ม Firebase ลงในแอป Android
- เมื่อใช้
Firebase Android BoM,
ให้ประกาศทรัพยากร Dependency สำหรับไลบรารี Cloud Firestore สำหรับ Android ใน
ไฟล์ Gradle ของโมดูล (ระดับแอป)
(โดยมากจะเป็น
app/build.gradle.ktsหรือapp/build.gradle)dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.13.0")) // Declare the dependency for the Cloud Firestore library // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-firestore") }
การใช้ Firebase Android BoM, จะทำให้แอปใช้ไลบรารี Firebase Android เวอร์ชันที่เข้ากันได้อยู่เสมอ
(ทางเลือก) ประกาศทรัพยากร Dependency ของไลบรารี Firebase โดยไม่ ใช้ BoM
หากเลือกที่จะไม่ใช้ Firebase BoM คุณต้องระบุเวอร์ชันของไลบรารี Firebase แต่ละรายการในบรรทัดทรัพยากร Dependency
โปรดทราบว่าหากคุณใช้ไลบรารี Firebase หลายรายการ ในแอป เราขอแนะนำให้ใช้ BoM เพื่อจัดการเวอร์ชันของไลบรารี ซึ่งจะช่วยให้มั่นใจได้ว่าทุกเวอร์ชันเข้ากันได้
dependencies { // Declare the dependency for the Cloud Firestore library // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-firestore:26.3.0") }
กำลังมองหาโมดูลไลบรารีเฉพาะสำหรับ Kotlin ใช่ไหม ตั้งแต่เวอร์ชันที่เผยแพร่ในเดือน ตุลาคม 2023 เป็นต้นไป นักพัฒนาแอปทั้ง Kotlin และ Java สามารถใช้โมดูลไลบรารีหลักได้ (ดูรายละเอียดได้ที่ คำถามที่พบบ่อยเกี่ยวกับความคิดริเริ่มนี้)
เริ่มต้นใช้งาน 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");
เพิ่มข้อมูลโดยใช้การดำเนินการหลัก
หากต้องการสำรวจการดำเนินการหลักและการดำเนินการไปป์ไลน์สำหรับการค้นหาข้อมูล ให้เพิ่มข้อมูลลงในฐานข้อมูลโดยใช้การดำเนินการหลัก
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
// 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); } });
ตอนนี้ให้เพิ่มเอกสารอีกรายการลงในคอลเล็กชัน 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
// 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); } });
อ่านข้อมูลโดยใช้การดำเนินการหลัก
ใช้โปรแกรมดูข้อมูลใน คอนโซล 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
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()); } } });
อ่านข้อมูลโดยใช้การดำเนินการ Pipeline
ตอนนี้คุณสามารถเปรียบเทียบประสบการณ์การค้นหาไปป์ไลน์กับประสบการณ์การค้นหาหลักได้แล้ว
Web
// The import/require of "firebase/firestore/pipelines" has a side-effect // of extending the Firestore class with the `.pipeline()` method. // Without this import/require, you will not be able to create a Pipeline. // import { execute } from "firebase/firestore/pipelines"; 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); } });
รักษาความปลอดภัยให้ข้อมูลสำหรับ SDK บนอุปกรณ์เคลื่อนที่และเว็บ
หากใช้ 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 ของเซิร์ฟเวอร์รายการใดรายการหนึ่ง ให้ใช้ Identity and Access Management (IAM) เพื่อรักษาความปลอดภัยให้ข้อมูล ใน Cloud Firestore.
ขั้นตอนถัดไป
เพิ่มพูนความรู้เกี่ยวกับการดำเนินการหลักและการดำเนินการไปป์ไลน์ด้วยหัวข้อต่อไปนี้
- ดูข้อมูลเพิ่มเติมเกี่ยวกับการค้นหาด้วยการดำเนินการหลัก
- ดูข้อมูลเพิ่มเติมเกี่ยวกับการค้นหาด้วยการดำเนินการ Pipeline
- ดูวิธีปรับปรุงเครื่องมือพัฒนา AI เพื่อให้ทำงานได้อย่างมีประสิทธิภาพมากขึ้น และใช้แนวทางปฏิบัติแนะนำของ Cloud Firestore (เช่น การเขียน Cloud Firestore Security Rules) ด้วย ทักษะของเอเจนต์ Firebase