Cloud Firestore Enterprise エディションを使ってみる

このクイックスタートでは、Cloud Firestore Enterprise エディションを設定してデータを追加し、Core オペレーションまたは Pipeline オペレーションを使用して、Firebase コンソールで追加したデータをクエリする方法について説明します。

Cloud Firestore は、モバイル SDK またはウェブ SDK とサーバー クライアント ライブラリをサポートしています。

  • Cloud Firestore は、Android、iOS、ウェブなどの SDK をサポートしています。Cloud Firestore Security RulesFirebase Authentication を組み合わせると、モバイル SDK とウェブ SDK でサーバーレス アプリ アーキテクチャがサポートされ、これによりクライアントは Cloud Firestore データベースに直接接続できます。

  • Cloud Firestore は、Java、Node.js、Python 用のサーバー クライアント ライブラリをサポートしています。これらのクライアント ライブラリを使用して、データベースへの完全アクセス権を備えた特権的サーバー環境を設定します。これらのライブラリの詳細については、サーバー クライアント ライブラリのクイックスタートをご覧ください。

Cloud Firestore Enterprise エディションのデータベースを作成する

  1. まだ Firebase プロジェクトを作成していない場合は作成します。Firebase コンソールで[プロジェクトを追加] をクリックし、画面上の指示に沿って、Firebase プロジェクトを作成するか、Google Cloud プロジェクトに Firebase サービスを追加します。

  2. Firebase コンソールでプロジェクトを開きます。左側のパネルで [ビルド] を展開し、[Firestore データベース] を選択します。

  3. [データベースを作成] をクリックします。

  4. データベース モードとして [Enterprise] を選択します。

  5. オペレーション モードとして [ネイティブ モードの Firestore] を選択します。このモードでは、Core オペレーションと Pipeline オペレーションがサポートされます。

  6. データベースのロケーションを選択します。

  7. Cloud Firestore Security Rules の開始モードを選択します。

    テストモード

    モバイルおよびウェブ クライアント ライブラリを使用する場合に適していますが、すべてのユーザーがデータを読み書きできます。テストが終わったら、必ずデータのセキュリティ保護セクションを確認してください。

    ウェブ、Apple プラットフォーム、Android SDK を使用する場合は、テストモードを選択します。

    本番環境モード

    モバイルおよびウェブ クライアントからのすべての読み書きを拒否します。認証されたアプリケーション サーバー(Python)は引き続きデータベースにアクセスできます。

    デフォルトの Cloud Firestore データベースには、Cloud Firestore Security Rules の初期セットが適用されます。プロジェクトに複数のデータベースを作成する場合は、データベースごとに Cloud Firestore Security Rules をデプロイできます。

  8. [作成] をクリックします。

Cloud Firestore Enterprise エディションを有効にすると、Cloud API Manager で API も有効になります。

開発環境を設定する

必要な依存関係とクライアント ライブラリをアプリに追加します。

Web

  1. Firebase をウェブアプリに追加するの手順に沿って操作します。
  2. Cloud Firestore SDK は、npm パッケージとしても提供されています。
    npm install firebase@12.8.0 --save
    Firebase と Cloud Firestore の両方をインポートする必要があります。
    import { initializeApp } from "firebase/app";
    import { getFirestore } from "firebase/firestore";
iOS+

Firebase を Apple アプリに追加するの手順に沿って操作します。

Swift Package Manager を使用して Firebase の依存関係のインストールと管理を行います。

  1. Xcode でアプリ プロジェクトを開いたまま、[File(ファイル)] > [Swift Packages(Swift パッケージ)] > [Add Package Dependency(パッケージの依存関係を追加)] の順に移動します。
  2. プロンプトが表示されたら、Firebase Apple プラットフォーム SDK リポジトリを追加します。
  3.   https://github.com/firebase/firebase-ios-sdk
      
  4. Firestore ライブラリを選択します。
  5. 上記の作業が完了すると、Xcode は依存関係の解決とバックグラウンドでのダウンロードを自動的に開始します。
Android
  1. Android アプリに Firebase を追加するの手順に沿って操作します。
  2. Firebase Android 部品構成表を使用して、モジュール(アプリレベル)の Gradle ファイル(通常は app/build.gradle.kts または app/build.gradle)で Android 向け Cloud Firestore ライブラリの依存関係を宣言します。
    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:34.7.0"))
    
        // Declare the dependency for the Cloud Firestore library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-firestore")
    }

    Firebase Android BoM を使用すると、アプリは常に互換性のあるバージョンの Firebase Android ライブラリを使用します。

    (別の方法) BoM を使用せずに Firebase ライブラリの依存関係を宣言する

    Firebase BoM を使用しない場合は、依存関係の行でそれぞれの Firebase ライブラリのバージョンを指定する必要があります。

    アプリで複数の Firebase ライブラリを使用する場合は、すべてのバージョンの互換性を確保するため、BoM を使用してライブラリのバージョンを管理することを強くおすすめします。

    dependencies {
        // Declare the dependency for the Cloud Firestore library
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-firestore:26.0.2")
    }

    Kotlin 固有のライブラリ モジュールをお探しの場合、2023 年 10 月のリリース以降は、Kotlin と Java のどちらのデベロッパーもメイン ライブラリ モジュールを利用できるようになります(詳しくは、このイニシアチブに関するよくある質問をご覧ください)。

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");

Core オペレーションを使用してデータを追加する

データのクエリに使用する Core オペレーションと Pipeline オペレーションを試すには、Core オペレーションを使用してデータベースにデータを追加します。

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

次に、別のドキュメントを users コレクションに追加します。このドキュメントには、最初のドキュメントに表示されない Key-Value ペア(ミドルネーム)が含まれています。コレクション内のドキュメントには、それぞれ異なる情報のセットを含めることができます。

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

Core オペレーションを使用してデータを読み取る

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

Pipeline オペレーションを使用してデータを読み取る

これで、Pipeline クエリ エクスペリエンスと 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);
    }
});

モバイル SDK とウェブ SDK のデータを保護する

ウェブ、Android、または Apple プラットフォームの SDK を使用している場合は、Firebase AuthenticationCloud 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 のデータを保護します。

次のステップ

次のトピックで Core オペレーションと Pipeline オペレーションの知識を深めてください。