Bắt đầu sử dụng Cloud Firestore Enterprise Edition bằng thư viện ứng dụng máy chủ

Hướng dẫn nhanh này cho bạn biết 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 vào bảng điều khiển Firebase bằng cách sử dụng thư viện ứng dụng phía 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ạ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ó.

  2. 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 mục Build (Tạo) rồi chọn Cơ sở dữ liệu Firestore.

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

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

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

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

  7. 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 xét phần Bảo mật dữ liệu của bạn.

    Để bắt đầu với web, nền tảng Apple hoặc SDK Android, hãy chọn chế độ kiểm thử.

    Chế độ sản xuất

    Từ chối mọi lượt đọc và ghi từ ứng dụng di động và ứng dụng web. Các máy chủ ứng dụng đã xác thực (Node.js, Python, Java) 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.

  8. 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.

Node.js
  1. Thêm Firebase Admin SDK vào ứng dụng của bạn:
    npm install firebase-admin --save
  2. Hãy làm theo hướng dẫn bên dưới để khởi tạo Cloud Firestore bằng thông tin đăng nhập thích hợp trong môi trường của bạn.
Python
  1. Thêm Firebase Admin SDK vào ứng dụng Python của bạn:
    pip install --upgrade firebase-admin
  2. Hãy làm theo hướng dẫn bên dưới để khởi tạo Cloud Firestore bằng thông tin đăng nhập thích hợp trong môi trường của bạn.
Java
  1. Thêm Firebase Admin SDK vào ứng dụng của bạn:
    • Sử dụng Gradle:
      implementation 'com.google.firebase:firebase-admin:9.7.1'
    • Sử dụng Maven:
      <dependency>
        <groupId>com.google.firebase</groupId>
        <artifactId>firebase-admin</artifactId>
        <version>9.7.1</version>
      </dependency>
           
  2. Hãy làm theo hướng dẫn bên dưới để khởi tạo Cloud Firestore bằng thông tin đăng nhập thích hợp trong môi trường của bạn.

Khởi chạy Cloud Firestore

Khởi động một phiên bản của Cloud Firestore:

Node.js
SDK Cloud Firestore được khởi chạy theo nhiều cách tuỳ thuộc vào môi trường của bạn. Dưới đây là những phương pháp phổ biến nhất. Để biết thông tin tham khảo đầy đủ, hãy xem phần Khởi chạy Admin SDK.
  • Khởi chạy vào ngày Cloud Functions
    const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
    const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
    initializeApp();
    
    const db = getFirestore();
    
  • Khởi chạy vào ngày Google Cloud
    const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
    const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
    initializeApp({
      credential: applicationDefault()
    });
    
    const db = getFirestore();
  • Khởi động trên máy chủ của riêng bạn

    Để sử dụng Firebase Admin SDK trên máy chủ của riêng bạn (hoặc bất kỳ môi trường Node.js nào khác), hãy sử dụng một tài khoản dịch vụ. Chuyển đến phần IAM và quản trị &gt; Tài khoản dịch vụ trong bảng điều khiển Google Cloud. Tạo khoá riêng tư mới và lưu tệp JSON. Sau đó, hãy dùng tệp này để khởi chạy SDK:

    const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
    const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
    const serviceAccount = require('./path/to/serviceAccountKey.json');
    
    initializeApp({
      credential: cert(serviceAccount)
    });
    
    const db = getFirestore();
    
Python
SDK Cloud Firestore được khởi chạy theo nhiều cách tuỳ thuộc vào môi trường của bạn. Dưới đây là những phương pháp phổ biến nhất. Để biết thông tin tham khảo đầy đủ, hãy xem phần Khởi chạy Admin SDK.
  • Khởi chạy vào ngày Google Cloud
    import firebase_admin
    from firebase_admin import firestore
    
    # Application Default credentials are automatically created.
    app = firebase_admin.initialize_app()
    db = firestore.client()

    Bạn cũng có thể dùng thông tin đăng nhập mặc định hiện có của ứng dụng để khởi chạy SDK.

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore
    
    # Use the application default credentials.
    cred = credentials.ApplicationDefault()
    
    firebase_admin.initialize_app(cred)
    db = firestore.client()
  • Khởi động trên máy chủ của riêng bạn

    Để sử dụng Firebase Admin SDK trên máy chủ của riêng bạn, hãy sử dụng một tài khoản dịch vụ.

    Chuyển đến IAM và quản trị > Tài khoản dịch vụ trong bảng điều khiển Google Cloud. Tạo khoá riêng tư mới và lưu tệp JSON. Sau đó, hãy dùng tệp này để khởi chạy SDK:

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore
    
    # Use a service account.
    cred = credentials.Certificate('path/to/serviceAccount.json')
    
    app = firebase_admin.initialize_app(cred)
    
    db = firestore.client()
  • Java
    SDK Cloud Firestore được khởi chạy theo nhiều cách tuỳ thuộc vào môi trường của bạn. Dưới đây là những phương pháp phổ biến nhất. Để biết thông tin tham khảo đầy đủ, hãy xem phần Khởi chạy Admin SDK.
  • Khởi chạy vào ngày Google Cloud
    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.cloud.firestore.Firestore;
    
    import com.google.firebase.FirebaseApp;
    import com.google.firebase.FirebaseOptions;
    
    // Use the application default credentials
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
    FirebaseOptions options = new FirebaseOptions.Builder()
        .setCredentials(credentials)
        .setProjectId(projectId)
        .build();
    FirebaseApp.initializeApp(options);
    
    Firestore db = FirestoreClient.getFirestore();
  • Khởi động trên máy chủ của riêng bạn

    Để sử dụng Firebase Admin SDK trên máy chủ của riêng bạn, hãy sử dụng một tài khoản dịch vụ.

    Chuyển đến IAM và quản trị > Tài khoản dịch vụ trong bảng điều khiển Google Cloud. Tạo khoá riêng tư mới và lưu tệp JSON. Sau đó, hãy dùng tệp này để khởi chạy SDK:

    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.cloud.firestore.Firestore;
    
    import com.google.firebase.FirebaseApp;
    import com.google.firebase.FirebaseOptions;
    
    // Use a service account
    InputStream serviceAccount = new FileInputStream("path/to/serviceAccount.json");
    GoogleCredentials credentials = GoogleCredentials.fromStream(serviceAccount);
    FirebaseOptions options = new FirebaseOptions.Builder()
        .setCredentials(credentials)
        .build();
    FirebaseApp.initializeApp(options);
    
    Firestore db = FirestoreClient.getFirestore();
  • 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.

    Node.js
    const docRef = db.collection('users').doc('alovelace');
    
    await docRef.set({
      first: 'Ada',
      last: 'Lovelace',
      born: 1815
    });
    Java
    DocumentReference docRef = db.collection("users").document("alovelace");
    // Add document data  with id "alovelace" using a hashmap
    Map<String, Object> data = new HashMap<>();
    data.put("first", "Ada");
    data.put("last", "Lovelace");
    data.put("born", 1815);
    //asynchronously write data
    ApiFuture<WriteResult> result = docRef.set(data);
    // ...
    // result.get() blocks on response
    System.out.println("Update time : " + result.get().getUpdateTime());
    Python
    doc_ref = db.collection("users").document("alovelace")
    doc_ref.set({"first": "Ada", "last": "Lovelace", "born": 1815})

    Đọ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ể dùng phương thức "get" để truy xuất toàn bộ tập hợp.

    Node.js
    const snapshot = await db.collection('users').get();
    snapshot.forEach((doc) => {
      console.log(doc.id, '=>', doc.data());
    });
    Python
    users_ref = db.collection("users")
    docs = users_ref.stream()
    
    for doc in docs:
        print(f"{doc.id} => {doc.to_dict()}")
    Java
    // asynchronously retrieve all users
    ApiFuture<QuerySnapshot> query = db.collection("users").get();
    // ...
    // query.get() blocks on response
    QuerySnapshot querySnapshot = query.get();
    List<QueryDocumentSnapshot> documents = querySnapshot.getDocuments();
    for (QueryDocumentSnapshot document : documents) {
      System.out.println("User: " + document.getId());
      System.out.println("First: " + document.getString("first"));
      if (document.contains("middle")) {
        System.out.println("Middle: " + document.getString("middle"));
      }
      System.out.println("Last: " + document.getString("last"));
      System.out.println("Born: " + document.getLong("born"));
    }

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

    Node.js
    const readDataPipeline = db.pipeline()
      .collection("users");
    
    // Execute the pipeline and handle the result
    try {
      const querySnapshot = await readDataPipeline.execute();
      querySnapshot.results.forEach((result) => {
        console.log(`${result.id} => ${result.data()}`);
      });
    } catch (error) {
        console.error("Error getting documents: ", error);
    }
    Python
    pipeline = client.pipeline().collection("users")
    for result in pipeline.execute():
        print(f"{result.id} => {result.data()}")
    Java
    Pipeline pipeline = firestore.pipeline().collection("users");
    ApiFuture<Pipeline.Snapshot> future = pipeline.execute();
    for (com.google.cloud.firestore.PipelineResult result : future.get().getResults()) {
      System.out.println(result.getId() + " => " + result.getData());
    }
    // or, asynchronously
    pipeline.execute(
        new ApiStreamObserver<com.google.cloud.firestore.PipelineResult>() {
          @Override
          public void onNext(com.google.cloud.firestore.PipelineResult result) {
            System.out.println(result.getId() + " => " + result.getData());
          }
    
          @Override
          public void onError(Throwable t) {
            System.err.println(t);
          }
    
          @Override
          public void onCompleted() {
            System.out.println("done");
          }
        });

    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: