Hướng dẫn nhanh này sẽ hướng dẫn bạn cách thiết lập Firestore phiên bản Enterprise, thêm dữ liệu, sau đó sử dụng các thao tác với Core hoặc Quy trình để truy vấn dữ liệu mà bạn vừa thêm trong 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. Kết hợp với Cloud Firestore Security Rules và Firebase Authentication, SDK dành cho thiết bị di động và web hỗ trợ các 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 Cloud Firestore cơ sở dữ liệu 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ó đặc quyền với 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 Hướng dẫn nhanh về thư viện ứng dụng máy chủ.
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 tạo một dự án: 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 các 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 phần Cơ sở dữ liệu và bộ nhớ > Firestore.
Nhấp vào Tạo cơ sở dữ liệu.
Chọn Enterprise cho chế độ cơ sở dữ liệu.
Chọn Firestore ở Chế độ gốc cho chế độ hoạt động, hỗ trợ các thao tác với Core và Quy trình.
Chọn một vị trí cho cơ sở dữ liệu của bạn.
Chọn chế độ bắt đầu cho Cloud Firestore Security Rules:
- Chế độ thử nghiệm
Phù hợp để bắt đầu sử dụng các thư viện ứng dụng dành cho thiết bị di động và web, nhưng cho phép mọi người đọ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 của bạn.
Để bắt đầu sử dụng SDK dành cho web, nền tảng Apple hoặc SDK Android, hãy chọn chế độ thử nghiệm.
- Chế độ sản xuất
Từ chối mọi lượt đọc và ghi từ ứng dụng khách dành cho thiết bị di động và web. Các máy chủ ứng dụng đã xác thực của bạn (Python) vẫn có thể truy cập vào cơ sở dữ liệu của bạn.
Bộ quy tắc bảo mật ban đầu của Cloud Firestore Security Rules sẽ áp dụng cho cơ sở dữ liệu mặc định Cloud Firestore 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 Firestore phiên bản Enterprise, API này cũng sẽ bật trong Trình quản lý API của 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ó ở dạng gói npm.
Bạn cần nhập cả Firebase và Cloud Firestore.npm install firebase@12.15.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 của bạn.
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.
- Khi được nhắc, hãy thêm kho lưu trữ SDK nền tảng Apple của Firebase:
- 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 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 của bạn.
- Sử dụng
Firebase Android BoM (Bảng kê khai thành phần của Firebase cho Android),
hãy khai báo phần phụ thuộc cho thư viện Cloud Firestore dành cho Android trong
tệp Gradle của mô-đun (cấp ứng dụng)
(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:34.15.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") }
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.
(Giải pháp thay thế) 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.
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, đảm bảo rằng tất cả cá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:26.4.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 chạy 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 với Core
Để khám phá các thao tác với Core và Quy trình để 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 với 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 bộ sưu tập và tài liệu vào lần đầu tiên bạn thêm dữ liệu vào tài liệu. Bạn không cần tạo bộ sưu tập hoặc tài liệu một cách rõ ràng.
Tạo bộ sưu tập và tài liệu mới 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. Xin 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 bộ sưu tập có thể chứa nhiều tập hợp 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 với Core
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ộ bộ sưu tậ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 với Quy trình
Giờ đây, bạn có thể so sánh trải nghiệm truy vấn với Quy trình và trải nghiệm truy vấn với 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 dành cho thiết bị di động và web
Nếu bạn đang sử dụng SDK dành cho web, Android hoặc nền tảng 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.
Sau đâ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 trong bảng điều khiển của Firebase trên thẻ Cơ sở dữ liệu và bộ nhớ > Firestore > 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 iOS vào quá trình sản xuất, hãy 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. Hãy 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 sử dụng Identity and Access Management (IAM) để bảo mật dữ liệu của bạn trong Cloud Firestore.
Các bước tiếp theo
Nâng cao kiến thức của bạn về các thao tác với Core và Quy trình bằng các chủ đề sau:
- Tìm hiểu thêm về cách truy vấn bằng các thao tác với Core
- Tìm hiểu thêm về cách truy vấn bằng các thao tác với Quy trình.
- Tìm hiểu cách nâng cao các công cụ phát triển AI để thực thi các tác vụ hiệu quả hơn và sử dụng các phương pháp hay nhất (chẳng hạn như viết) bằng các kỹ năng của tác nhân Firebase.Cloud FirestoreCloud Firestore Security Rules