Bản bắt đầu nhanh này hướng dẫn bạn cách thiết lập phiên bản Firestore Enterprise, thêm dữ liệu, sau đó sử dụng Thao tác cốt lõi hoặc Thao tác quy trình để truy vấn dữ liệu mà bạn vừa thêm vào bảng điều khiển của Firebase.
Cloud Firestore hỗ trợ SDK dành cho thiết bị di động hoặc web và thư viện ứng dụng máy chủ:
Cloud Firestore hỗ trợ SDK cho Android, iOS, web và nhiều nền tảng khác. Khi kết hợp với Cloud Firestore Security Rules và Firebase Authentication, SDK web và di động sẽ hỗ trợ kiến trúc ứng dụng không máy chủ, trong đó ứng dụng khách kết nối trực tiếp với cơ sở dữ liệu Cloud Firestore của bạn.
Cloud Firestore hỗ trợ thư viện ứng dụng máy chủ cho Java, Node.js và Python. Sử dụng các thư viện ứng dụng này để thiết lập môi trường máy chủ đặc quyền có quyền truy cập đầy đủ vào cơ sở dữ liệu của bạn. Tìm hiểu thêm về các thư viện này trong phần Bắt đầu nhanh về thư viện ứng dụng máy chủ.
Câu lệnh AI cho tính năng trợ giúp AI
Để được trợ giúp AI, hãy sao chép câu lệnh bên dưới vào tác nhân lập trình AI (như Gemini trong Android Studio, Antigravity, Claude Code, Codex và Cursor). Bạn có thể tuỳ chỉnh câu lệnh và lặp lại với tác nhân. Truy cập vào bài viết Kỹ năng của tác nhân Firebase để biết thông tin chi tiết về cách cài đặt.
Help me use Firebase in my app.
1. Make sure that **Firebase agent skills** are installed and updated. For Claude Code, Codex, or Cursor agents, help me install the Firebase plugin. For other agents, run `npx skills add firebase/agent-skills`. Always try to use **Firebase agent skills** for Firebase-related tasks.
2. Help me set up and use Firebase for the backend of my app. Set up Firestore database in **Enterprise edition**. Help me to choose the best location for my database instance.
Tạo cơ sở dữ liệu Firestore phiên bản Enterprise
Nếu bạn chưa tạo dự án Firebase, hãy làm như sau: Trong bảng điều khiển của Firebase, hãy nhấp vào Thêm dự án, sau đó làm theo hướng dẫn trên màn hình để tạo dự án Firebase hoặc thêm dịch vụ Firebase vào một dự án Google Cloud hiện có.
Trong bảng điều khiển bên trái, hãy chuyển đến Databases & Storage (Cơ sở dữ liệu và bộ nhớ) > Firestore.
Nhấp vào Tạo cơ sở dữ liệu.
Chọn Enterprise (Doanh nghiệp) cho chế độ cơ sở dữ liệu.
Chọn Firestore ở Chế độ gốc cho chế độ hoạt động, chế độ này hỗ trợ các hoạt động Core và Pipeline.
Chọn một vị trí cho cơ sở dữ liệu của bạn.
Chọn chế độ khởi động cho Cloud Firestore Security Rules:
- Chế độ thử nghiệm
Phù hợp để bắt đầu với thư viện ứng dụng web và thiết bị di động, nhưng cho phép bất kỳ ai đọc và ghi đè dữ liệu của bạn. Sau khi kiểm thử, hãy nhớ xem lại phần Bảo mật dữ liệu.
Để bắt đầu sử dụng SDK web, nền tảng của Apple hoặc SDK Android, hãy chọn chế độ thử nghiệm.
- Chế độ sản xuất
Từ chối tất cả các yêu cầu đọc và ghi từ ứng dụng di động và ứng dụng web. Máy chủ ứng dụng đã xác thực (Python) của bạn vẫn có thể truy cập vào cơ sở dữ liệu.
Tập hợp Cloud Firestore Security Rules ban đầu sẽ áp dụng cho cơ sở dữ liệu Cloud Firestore mặc định của bạn. Nếu tạo nhiều cơ sở dữ liệu cho dự án, bạn có thể triển khai Cloud Firestore Security Rules cho từng cơ sở dữ liệu.
Nhấp vào Tạo.
Khi bạn bật phiên bản Firestore Enterprise, API này cũng sẽ được bật trong Trình quản lý API Cloud.
Thiết lập môi trường phát triển
Thêm các phần phụ thuộc và thư viện ứng dụng bắt buộc vào ứng dụng của bạn.
Web
- Làm theo hướng dẫn để thêm Firebase vào ứng dụng web của bạn.
-
SDK Cloud Firestore được cung cấp dưới dạng một gói npm.
Bạn cần nhập cả Firebase và Cloud Firestore.npm install firebase@13.0.0 --save
import { initializeApp } from "firebase/app"; import { getFirestore } from "firebase/firestore";
iOS+
Làm theo hướng dẫn để thêm Firebase vào ứng dụng Apple.
Sử dụng Trình quản lý gói Swift để cài đặt và quản lý các phần phụ thuộc của Firebase.
- Trong Xcode, khi dự án ứng dụng của bạn đang mở, hãy chuyển đến File > Swift Packages > Add Package Dependency (Tệp > Gói Swift > Thêm phần phụ thuộc gói).
- Khi được nhắc, hãy thêm kho lưu trữ SDK Firebase cho nền tảng của Apple:
- Chọn thư viện Firestore.
- Khi hoàn tất, Xcode sẽ tự động bắt đầu phân giải và tải các phần phụ thuộc của bạn xuống ở chế độ nền.
https://github.com/firebase/firebase-ios-sdk
Android
- Làm theo hướng dẫn để thêm Firebase vào ứng dụng Android.
- Sử dụng
Firebase Android BoM (Bảng kê khai thành phần của Firebase cho Android),
khai báo phần phụ thuộc cho thư viện Cloud Firestore cho Android trong
tệp Gradle (ở cấp ứng dụng) trong mô-đun
(thường là
app/build.gradle.ktshoặcapp/build.gradle).dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:35.0.1")) // 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") }
Bằng cách sử dụng Firebase Android BoM (Bảng kê khai thành phần của Firebase cho Android), ứng dụng của bạn sẽ luôn sử dụng những phiên bản tương thích của thư viện Android trên Firebase.
(Cách khác) Khai báo các phần phụ thuộc của thư viện Firebase mà không sử dụng BoM
Nếu chọn không sử dụng Firebase BoM, bạn phải chỉ định từng phiên bản thư viện Firebase trong dòng phần phụ thuộc của thư viện đó.
Xin lưu ý rằng nếu bạn sử dụng nhiều thư viện Firebase trong ứng dụng, bạn nên sử dụng BoM để quản lý các phiên bản thư viện, nhằm đảm bảo tất cả phiên bản đều tương thích.
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:27.0.0") }
Bạn đang tìm mô-đun thư viện dành riêng cho Kotlin? Kể từ bản phát hành tháng 10 năm 2023, cả nhà phát triển Kotlin và Java đều có thể phụ thuộc vào mô-đun thư viện chính (để biết thông tin chi tiết, hãy xem Câu hỏi thường gặp về sáng kiến này).
Khởi chạy Cloud Firestore
Khởi động một thực thể của 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');
Thay thế FIREBASE_CONFIGURATION bằng firebaseConfig của ứng dụng web.
Để duy trì dữ liệu khi thiết bị mất kết nối, hãy xem tài liệu Bật dữ liệu ngoại tuyế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");
Thêm dữ liệu bằng các thao tác cốt lõi
Để khám phá các thao tác Core và thao tác Pipeline nhằm truy vấn dữ liệu, hãy thêm dữ liệu vào cơ sở dữ liệu của bạn bằng các thao tác Core.
Cloud Firestore lưu trữ dữ liệu trong Tài liệu, được lưu trữ trong Bộ sưu tập. Cloud Firestore ngầm tạo các tập hợp và tài liệu trong lần đầu tiên bạn thêm dữ liệu vào tài liệu. Bạn không cần phải tạo bộ sưu tập hoặc tài liệu một cách rõ ràng.
Tạo một tập hợp mới và một tài liệu bằng mã ví dụ sau.
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); } });
Bây giờ, hãy thêm một tài liệu khác vào bộ sưu tập users. Lưu ý rằng tài liệu này bao gồm một cặp khoá-giá trị (tên đệm) không xuất hiện trong tài liệu đầu tiên. Các tài liệu trong một tập hợp có thể chứa nhiều nhóm thông tin.
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); } });
Đọc dữ liệu bằng các thao tác cốt lõi
Sử dụng trình xem dữ liệu trong bảng điều khiển của Firebase để nhanh chóng xác minh rằng bạn đã thêm dữ liệu vào Cloud Firestore.
Bạn cũng có thể sử dụng phương thức "get" để truy xuất toàn bộ tập hợp.
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()); } } });
Đọc dữ liệu bằng các thao tác trong quy trình
Giờ đây, bạn có thể so sánh trải nghiệm truy vấn Pipeline với trải nghiệm truy vấn Core.
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); } });
Bảo mật dữ liệu cho SDK web và thiết bị di động
Nếu bạn đang sử dụng SDK nền tảng web, Android hoặc Apple, hãy sử dụng Firebase Authentication và Cloud Firestore Security Rules để bảo mật dữ liệu của bạn trong Cloud Firestore.
Dưới đây là một số bộ quy tắc cơ bản mà bạn có thể sử dụng để bắt đầu. Bạn có thể sửa đổi các quy tắc bảo mật của mình trong bảng điều khiển của Firebase, tại thẻ Databases & Storage (Cơ sở dữ liệu và bộ nhớ) > Firestore > Rules (Quy tắc).
Yêu cầu xác thực
// 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;
}
}
}
Chế độ sản xuất
// Deny read/write access to all users under any conditions
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
}
}
Trước khi triển khai ứng dụng web, Android hoặc ứng dụng iOS cho môi trường thực tế, bạn cũng cần thực hiện các bước để đảm bảo rằng chỉ ứng dụng khách của bạn mới có thể truy cập vào dữ liệu Cloud Firestore. Xem tài liệu về Kiểm tra ứng dụng.
Nếu bạn đang sử dụng một trong các SDK máy chủ, hãy dùng Quản lý danh tính và quyền truy cập (IAM) để bảo mật dữ liệu của bạn trong Cloud Firestore.
Các bước tiếp theo
Tìm hiểu sâu hơn về các hoạt động của Core và Pipeline qua các chủ đề sau:
- Tìm hiểu thêm về cách truy vấn bằng Thao tác cốt lõi
- Tìm hiểu thêm về cách truy vấn bằng Thao tác trong quy trình.
- Tìm hiểu cách cải thiện các công cụ phát triển AI để thực thi nhiệm vụ hiệu quả hơn và áp dụng các phương pháp hay nhất của Cloud Firestore (chẳng hạn như viết Cloud Firestore Security Rules) bằng kỹ năng của tác nhân Firebase.