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

Hướng dẫn bắt đầu 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 thao tác Pipeline để truy vấn dữ liệu 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 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 bạn chưa tạo dự án Firebase, hãy nhấp vào Firebase bảng điều khiể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ó.

  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 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 cho chế độ cơ sở dữ liệu.

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

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

  7. Chọn một chế độ bắt đầu cho Cloud Firestore Security Rules:

    Chế độ thử nghiệm

    Phù hợp để bắt đầu sử dụng 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 của bạn.

    Để bắt đầu sử dụng SDK web, nền tảng Apple hoặc Android, hãy chọn chế độ thử nghiệm.

    Chế độ sản xuất

    Từ chối mọi hoạt động đọc và ghi từ ứng dụng web và thiết bị di động. 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.

    Bộ Quy tắc bảo mật Cloud Firestore ban đầu sẽ áp dụng cho cơ sở dữ liệu Cloud Firestore mặc định.Cloud Firestore Security RulesCloud Firestore 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ẽ bật trong Cloud API Manager.

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.

Node.js
  1. Thêm Firebase Admin SDK vào ứng dụng của bạn:
    npm install firebase-admin --save
  2. Làm theo hướng dẫn bên dưới để khởi chạy Cloud Firestore bằng thông tin xác thực 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. Làm theo hướng dẫn bên dưới để khởi chạy Cloud Firestore bằng thông tin xác thực 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.8.0'
    • Sử dụng Maven:
      <dependency>
        <groupId>com.google.firebase</groupId>
        <artifactId>firebase-admin</artifactId>
        <version>9.8.0</version>
      </dependency>
           
  2. Làm theo hướng dẫn bên dưới để khởi chạy Cloud Firestore bằng thông tin xác thực thích hợp trong môi trường của bạn.

Khởi chạy Cloud Firestore

Khởi chạy 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à các phương thức phổ biến nhất. Để tham khảo đầy đủ, hãy xem phần Khởi chạy Admin SDK.
  • Khởi chạy trên 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 trên 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 chạy 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 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 một khoá riêng tư mới và lưu tệp JSON. Sau đó, sử 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à các phương thức phổ biến nhất. Để tham khảo đầy đủ, hãy xem phần Khởi chạy Admin SDK.
  • Khởi chạy trên 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ể sử dụng thông tin xác thực mặc định của ứng dụng hiện có để 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 chạy 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 một khoá riêng tư mới và lưu tệp JSON. Sau đó, sử 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à các phương thức phổ biến nhất. Để tham khảo đầy đủ, hãy xem phần Khởi chạy Admin SDK.
  • Khởi chạy trên 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 chạy 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 một khoá riêng tư mới và lưu tệp JSON. Sau đó, sử 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ác thao tác Core

    Để 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á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 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 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 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.

    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 Pipeline

    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

    Tìm hiểu sâu hơn về các thao tác Core và thao tác Pipeline với các chủ đề sau: