post-image

Cùng tìm hiểu về Firebase Cloud Firestore

Tổng quan

Cloud Firestore là một Database linh hoạt và dễ mở rộng cho mobile, web và server được phát triển từ Firebase and Google Cloud Platform.

Giới thiệu về Cloud Firestore

Cloud Firestore là một cloud-hosted, NoSQL database mà các ứng dụng phía client có thể trực tiếp truy cập thông qua native SDKs. Nó lưu dữ liệu theo mô hình dữ liệu NoSQL. Dữ liệu được lưu trữ trong các file tài liệu chứa các trường được ánh xạ vào các giá trị. Các file tài liệu này được lưu trữ trong các tập hợp chúng có thể sử dụng nó để tổ chức dữ liệu và truy vấn dữ liệu. Cloud Firestore hỗ trợ rất nhiều kiểu dữ liệu từ đơn giản như String, Integer hay những kiểu dữ liệu phức tạp như các nested object.

Thêm Cloud Firestore vào ứng dụng

Tạo một project

  1. Để sử dụng Cloud Firestore bạn cần tạo một project từ tài khoản firebase https://console.firebase.google.com/u/0/
  2. Trong menu trái bạn chọn Database và chọn Try Firestore Beta, cuối cùng là click Enable.

Cài đặt môi trường

  1. Để sử dụng dịch các thử viện firebase bạn cần thêm firebase vào project theo hướng dẫn sau: https://firebase.google.com/docs/android/setup
  2. Thêm Cloud Firestore vào app/build.gradle
compile 'com.google.firebase:firebase-firestore:11.8.0'

Tạo một instance

// Access a Cloud Firestore instance from your Activity

FirebaseFirestore db = FirebaseFirestore.getInstance();

Một số thao táo với dữ liệu

  1. Thêm dữ liệu Cloud lưu data trong Documents, Các Documents được lưu trữ trong các Collections. Khi bạn thêm dữ liệu vào trong một document lần đầu tiên thì Cloud sẽ tự động tạo các collections và documents bạn sẽ không cần tạo collections và documents một cách tường minh nữa.Dưới đây là một đoạn code mẫu cho việc tạo một document và một collection.
 // 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);
          }
      });
      

Đoạn code trên tạo một collection users và tạo một document user để lưu trữ đối tượng user.

Chúng ta có thể thêm một document user khác:

Map<String, Object> user = new HashMap<>();
user.put("first", "Alan");
user.put("middle", "Mathison");
user.put("last", "Turring");
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);
            }
        });

  1. Truy vấn dữ liệu Sau khi đã thêm thành công dữ liệu vào trong collection chúng ta có thể dùng hàm get() để lấy về toàn bộ documents trong collection users:
db.collection("users")
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (DocumentSnapshot document : task.getResult()) {
                        Log.d(TAG, document.getId() + " => " + document.getData());
                    }
                } else {
                    Log.w(TAG, "Error getting documents.", task.getException());
                }
            }
        });

Realtime database và Cloud firestore

Cloud Firestore có thể được coi là phiên bản cải tiến của Realtime database, nó được cải tiến nhiều tính năng mới và tăng tốc độ truy vấn dữ liệu. Nếu bạn đang sử dụng Realtime Database thì việc chuyển sang sử dụng Cloud firestore khá dễ dàng. Dưới đây mình sẽ nêu một số những ưu điểm của Cloud Firestore so với Realtime database:

  • Việc tổ chức lưu trữ dữ liệu phức tạp dễ dàng hơn so với Realtime database .
  • Có thể kết hợp việc filter, sort, … trong một query, điều này không thể làm được với Realtime database.
  • Có thể truy vấn một collection hoặc một document mà không cần phải thông qua việc truy vấn toàn bộ collections giống như realtime database.

Trong bài viết sau mình sẽ làm một ví dụ về việc chát realtime sử dụng cloud firestore để có thể hiểu rõ hơn về nó.

Nguồn: https://viblo.asia/p/cung-tim-hieu-ve-firebase-cloud-firestore-ByEZk32YZQ0

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *