Bắt đầu sử dụng Cloud Firestore

Hướng dẫn nhanh này sẽ hướng dẫn bạn cách thiết lập Cloud Firestore, thêm dữ liệu, sau đó sử dụng các thao tác Core hoặc Pipeline để truy vấn dữ liệu mà bạn vừa thêm trong bảng điều khiển Firebase.

Tạo cơ sở dữ liệu Cloud Firestore

  1. Nếu chưa có, bạn cần tạo một dự án Firebase: Trong bảng điều khiển 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 một dự án Firebase hoặc thêm các dịch vụ Firebase vào một dự án Google Cloud hiện có.
  1. Mở dự án của bạn trong bảng điều khiển Firebase. Trong bảng điều khiển bên trái, hãy mở rộng Build (Tạo) rồi chọn Cơ sở dữ liệu Firestore.

  2. Nhấp vào Tạo cơ sở dữ liệu.

  3. Chọn Doanh nghiệp cho chế độ cơ sở dữ liệu.

  4. Chọn Firestore ở chế độ gốc cho chế độ hoạt động, hỗ trợ các hoạt động Core và Pipeline.

  5. Chọn một vị trí cho cơ sở dữ liệu của bạn.

  6. Chọn chế độ khởi động cho Cloud Firestore Security Rules:

    Chế độ kiểm thử

    Phù hợp để bắt đầu sử dụng các thư viện ứng dụng 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 với SDK cho web, nền tảng Apple hoặc Android, hãy chọn chế độ kiểm thử.

    Chế độ sản xuất

    Từ chối mọi hoạt động đọc và ghi từ ứng dụng di động và ứng dụng web. Các máy chủ ứng dụng được xác thực (Python) vẫn có thể truy cập vào cơ sở dữ liệu của bạn.

    Nhóm 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.

  7. Nhấp vào Tạo.

Khi bạn bật Cloud Firestore, API này cũng sẽ được bật trong Trình quản lý API trên đám mây.

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 cần thiết vào ứng dụng của bạn.

Web

  1. Làm theo hướng dẫn để thêm Firebase vào ứng dụng web của bạn.
  2. SDK Cloud Firestore cho Bản xem trước riêng tư có sẵn dưới dạng một gói npm.

    Sử dụng lệnh sau để cài đặt Firestore SDK trong dự án npm của bạn.

    npm install --save firebase@eap-firestore-pipelines
iOS+
  1. Làm theo hướng dẫn để thêm Firebase vào ứng dụng iOS.
  2. Sao chép Firebase SDK trên GitHub và kiểm tra nhánh quy trình. Ghi lại vị trí mà bạn sao chép, vì bạn sẽ cần vị trí đó trong bước tiếp theo:
    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. Sau đó, hãy thêm thư mục (firebase-ios-sdk) làm phần phụ thuộc cục bộ vào dự án Xcode của bạn:
    1. Trong trình đơn File (Tệp), hãy chọn Add Package Dependencies (Thêm các phần phụ thuộc của gói).
    2. Nhấp vào nút Add Local… (Thêm cục bộ), sau đó tìm thư mục firebase-ios-sdk có nhánh tính năng mà bạn đã kiểm tra.
Android
  1. Làm theo hướng dẫn để thêm Firebase vào ứng dụng Android.
  2. Sao chép Firebase SDK từ GitHub, kiểm tra nhánh pipelines và xuất bản nhánh đó lên maven cục bộ:
    # 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. Thêm mavenLocal vào settings.gradle.kts ở cấp dự án:
    dependencyResolutionManagement {
      repositories {
        mavenLocal() // Add this line
        ..
      }
    }
  4. Sau đó, hãy thêm phiên bản cục bộ của SDK:
    ...
    // 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. Sao chép Firestore Python SDK và kiểm tra nhánh xem trước của quy trình:
    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. Cài đặt SDK máy chủ python-firestore cục bộ:
    python -m pip install -e .
  3. Cài đặt Firebase Python Admin SDK như bình thường:
    pip install --user firebase-admin

Khởi chạy Cloud Firestore

Khởi động một phiên bản 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");
Python

Xác thực bằng cơ sở dữ liệu doanh nghiệp của bạn bằng 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()

Thêm dữ liệu bằng cách sử dụng các thao tác chính

Để khám phá các thao tác Core và thao tác Pipeline để truy vấn dữ liệu, hãy thêm dữ liệu vào cơ sở dữ liệu bằng cách sử dụ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 sẽ tạo các bộ sưu tập và tài liệu một cách ngầm ẩn 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 phải tạo rõ ràng các bộ sưu tập hoặc tài liệu.

Tạo một 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
Lưu ý: Sản phẩm này không có trên watchOS và các mục tiêu 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})

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 có 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 bộ 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
Lưu ý: Sản phẩm này không có trên watchOS và các mục tiêu 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})

Đọc dữ liệu bằng các thao tác 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ộ 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
Lưu ý: Sản phẩm này không có trên watchOS và các mục tiêu 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()}")

Đọ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

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

Bảo mật dữ liệu của bạn

Nếu bạn đang sử dụng SDK của nền tảng web, Android hoặc Apple, hãy sử dụng Xác thực FirebaseCloud 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 thẻ Quy tắc của bảng điều khiển.

Cần có quyền 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 quy trình sản xuất, hãy thực hiện các bước để đảm bảo rằng chỉ các ứ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ề App Check.

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

Nâng cao kiến thức về các hoạt động của Core và Pipeline qua các chủ đề sau: