เริ่มต้นใช้งาน Cloud Firestore

การเริ่มต้นอย่างรวดเร็วนี้จะแสดงวิธีตั้งค่า Cloud Firestore เพิ่มข้อมูล แล้วใช้ การดำเนินการหลักหรือการดำเนินการไปป์ไลน์เพื่อค้นหาข้อมูลที่คุณเพิ่งเพิ่มในคอนโซล Firebase

สร้างฐานข้อมูล Cloud Firestore

  1. หากยังไม่ได้สร้างโปรเจ็กต์ Firebase ให้สร้างในFirebaseคอนโซลโดยคลิกเพิ่มโปรเจ็กต์ แล้วทำตามวิธีการบนหน้าจอเพื่อสร้างโปรเจ็กต์ Firebase หรือเพิ่มบริการ Firebase ลงในGoogle Cloudโปรเจ็กต์ที่มีอยู่
  1. เปิดโปรเจ็กต์ในFirebaseคอนโซล ในแผงด้านซ้าย ให้ขยาย สร้าง แล้วเลือก ฐานข้อมูล Firestore

  2. คลิกสร้างฐานข้อมูล

  3. เลือกEnterprise สำหรับโหมดฐานข้อมูล

  4. เลือก Firestore ในโหมดดั้งเดิมสำหรับโหมดการทำงานที่รองรับ การดำเนินการหลักและการดำเนินการของไปป์ไลน์

  5. เลือกตำแหน่งสำหรับฐานข้อมูล

  6. เลือกโหมดเริ่มต้นสำหรับ Cloud Firestore Security Rules

    โหมดทดสอบ

    เหมาะสำหรับการเริ่มต้นใช้งานไลบรารีของไคลเอ็นต์อุปกรณ์เคลื่อนที่และเว็บ แต่จะอนุญาตให้ทุกคนอ่านและเขียนทับข้อมูลของคุณได้ หลังจากทดสอบแล้ว อย่าลืมตรวจสอบส่วนรักษาความปลอดภัยให้ข้อมูล

    หากต้องการเริ่มต้นใช้งาน SDK ของเว็บ, แพลตฟอร์ม Apple หรือ Android ให้เลือกโหมดทดสอบ

    โหมดโปรดักชัน

    ปฏิเสธการอ่านและการเขียนทั้งหมดจากไคลเอ็นต์อุปกรณ์เคลื่อนที่และเว็บ เซิร์ฟเวอร์แอปพลิเคชันที่ได้รับการตรวจสอบสิทธิ์ (Python) จะยังเข้าถึง ฐานข้อมูลได้

    ชุด Cloud Firestore Security Rules เริ่มต้นจะมีผลกับฐานข้อมูล Cloud Firestore เริ่มต้น หากสร้างฐานข้อมูลหลายรายการสำหรับโปรเจ็กต์ คุณสามารถทำให้ Cloud Firestore Security Rules ใช้งานได้สำหรับฐานข้อมูลแต่ละรายการ

  7. คลิกสร้าง

เมื่อเปิดใช้ Cloud Firestore ระบบจะเปิดใช้ API ใน Cloud API Manager ด้วย

ตั้งค่าสภาพแวดล้อมในการพัฒนา

เพิ่มทรัพยากร Dependency และไลบรารีของไคลเอ็นต์ที่จำเป็นลงในแอป

Web

  1. ทําตามวิธีการเพื่อ เพิ่ม Firebase ลงในเว็บแอป
  2. Cloud Firestore SDK สำหรับเวอร์ชันตัวอย่างส่วนตัวพร้อมใช้งานเป็นแพ็กเกจ npm

    ใช้คำสั่งต่อไปนี้เพื่อติดตั้ง Firestore SDK ในโปรเจ็กต์ npm

    npm install --save firebase@eap-firestore-pipelines
iOS+
  1. ทําตามวิธีการเพื่อ เพิ่ม Firebase ลงในแอป iOS
  2. โคลน Firebase SDK จาก GitHub และตรวจสอบสาขาไปป์ไลน์ จดตำแหน่งที่คุณโคลนไว้ เนื่องจากคุณจะต้องใช้ในขั้นตอนถัดไป
    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. จากนั้นเพิ่มไดเรกทอรี (firebase-ios-sdk) เป็นทรัพยากร Dependency ในเครื่องไปยังโปรเจ็กต์ Xcode โดยทำดังนี้
    1. จากเมนูไฟล์ ให้เลือกเพิ่มการอ้างอิงแพ็กเกจ
    2. คลิกปุ่มเพิ่มในเครื่อง… จากนั้นค้นหาไดเรกทอรี firebase-ios-sdk ที่มีสาขาฟีเจอร์ที่คุณเช็คเอาต์
Android
  1. ทําตามวิธีการเพื่อ เพิ่ม Firebase ลงในแอป Android
  2. โคลน Firebase SDK จาก GitHub ตรวจสอบสาขาไปป์ไลน์ แล้ว เผยแพร่ไปยัง Maven ในเครื่อง
    # 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. เพิ่ม mavenLocal ลงในระดับโปรเจ็กต์ settings.gradle.kts ดังนี้
    dependencyResolutionManagement {
      repositories {
        mavenLocal() // Add this line
        ..
      }
    }
  4. จากนั้นเพิ่ม 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. โคลน Firestore Python SDK และตรวจสอบสาขาตัวอย่างไปป์ไลน์
    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. ติดตั้ง SDK ของเซิร์ฟเวอร์ python-firestore ในเครื่อง
    python -m pip install -e .
  3. ติดตั้ง Firebase Python Admin SDK ตามปกติโดยทำดังนี้
    pip install --user firebase-admin

เริ่มต้น Cloud Firestore

เริ่มต้นอินสแตนซ์ของ 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');

แทนที่ FIREBASE_CONFIGURATION ด้วย firebaseConfig ของเว็บแอป

หากต้องการคงข้อมูลไว้เมื่ออุปกรณ์ขาดการเชื่อมต่อ โปรดดูเอกสารประกอบเปิดใช้ข้อมูลแบบออฟไลน์

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

ตรวจสอบสิทธิ์กับฐานข้อมูลขององค์กรโดยใช้ 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()

เพิ่มข้อมูลโดยใช้การดำเนินการหลัก

หากต้องการสำรวจการดำเนินการหลักและการดำเนินการไปป์ไลน์สำหรับการค้นหาข้อมูล ให้เพิ่มข้อมูลลงในฐานข้อมูลโดยใช้การดำเนินการหลัก

Cloud Firestore จัดเก็บข้อมูลในเอกสาร ซึ่งจัดเก็บไว้ในคอลเล็กชัน Cloud Firestore จะสร้างคอลเล็กชันและเอกสารโดยนัย เมื่อคุณเพิ่มข้อมูลลงในเอกสารเป็นครั้งแรก คุณไม่จำเป็นต้อง สร้างคอลเล็กชันหรือเอกสารอย่างชัดเจน

สร้างคอลเล็กชันและเอกสารใหม่โดยใช้โค้ดตัวอย่างต่อไปนี้

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
หมายเหตุ: ผลิตภัณฑ์นี้ไม่พร้อมใช้งานในเป้าหมาย watchOS และ 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})

ตอนนี้ให้เพิ่มเอกสารอีกฉบับลงในusersคอลเล็กชัน โปรดสังเกตว่าเอกสารนี้ มีคู่คีย์-ค่า (ชื่อกลาง) ที่ไม่ได้ปรากฏในเอกสารแรก เอกสารในคอลเล็กชันอาจมีชุดข้อมูลที่แตกต่างกัน

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
หมายเหตุ: ผลิตภัณฑ์นี้ไม่พร้อมใช้งานในเป้าหมาย watchOS และ 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})

อ่านข้อมูลโดยใช้การดำเนินการหลัก

ใช้เครื่องมือแสดงข้อมูลในคอนโซล Firebase เพื่อยืนยันอย่างรวดเร็วว่าคุณได้เพิ่มข้อมูลลงใน Cloud Firestore แล้ว

นอกจากนี้ คุณยังใช้วิธี "get" เพื่อดึงข้อมูลทั้งคอลเล็กชันได้ด้วย

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
หมายเหตุ: ผลิตภัณฑ์นี้ไม่พร้อมใช้งานในเป้าหมาย watchOS และ 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()}")

อ่านข้อมูลโดยใช้การดำเนินการของไปป์ไลน์

ตอนนี้คุณสามารถเปรียบเทียบประสบการณ์การใช้งานการค้นหาแบบไปป์ไลน์กับการค้นหาหลักได้แล้ว

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

รักษาข้อมูลของคุณให้ปลอดภัย

หากใช้ SDK ของแพลตฟอร์มเว็บ, Android หรือ Apple ให้ใช้การตรวจสอบสิทธิ์ Firebase และ Cloud Firestore Security Rules เพื่อรักษาความปลอดภัยของข้อมูลใน Cloud Firestore

ต่อไปนี้คือชุดกฎพื้นฐานบางส่วนที่คุณใช้เพื่อเริ่มต้นได้ คุณสามารถแก้ไข กฎความปลอดภัยได้ในแท็บกฎของ คอนโซล

ต้องมีการตรวจสอบสิทธิ์

// 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;
    }
  }
}

โหมดโปรดักชัน

// Deny read/write access to all users under any conditions
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }
  }
}

ก่อนที่จะนําแอปเว็บ, Android หรือ iOS ไปใช้งานจริง ให้ทําตามขั้นตอน เพื่อให้มั่นใจว่าเฉพาะไคลเอ็นต์แอปของคุณเท่านั้นที่จะเข้าถึงCloud Firestoreข้อมูลได้ ดูเอกสารประกอบของ App Check

หากคุณใช้ SDK ของเซิร์ฟเวอร์อย่างใดอย่างหนึ่ง ให้ใช้ Identity and Access Management (IAM) เพื่อรักษาความปลอดภัยของข้อมูล ใน Cloud Firestore

ขั้นตอนถัดไป

เพิ่มพูนความรู้เกี่ยวกับการดำเนินการหลักและการดำเนินการไปป์ไลน์ด้วยหัวข้อต่อไปนี้