Cloud Firestore の Datastore モードでの使用

Firestore は、自動スケーリングと高性能を実現し、アプリケーション開発を簡素化するように構築された NoSQL ドキュメント データベースです。これは Datastore の最新バージョンで、Datastore のいくつかの点が改善されています。

Datastore モードの Firestore は、サーバーのユースケースと App Engine 用に最適化されているため、主に App Engine アプリで使用されるデータベースには Datastore モードの Firestore を使用することをおすすめします。ネイティブ モードの Firestore は、モバイルとリアルタイムの通知のユースケースに最適です。Firestore モードの詳細については、ネイティブ モードと Datastore モードからの選択をご覧ください。

このドキュメントでは、Google Cloud Client Library を使用して Datastore モードのデータベースにデータを格納する方法、または Datastore モードのデータベースからデータを取得する方法について説明します。

前提条件と設定

App Engine の Node.js 用「Hello, World!」の説明に従って環境とプロジェクトを設定し、App Engine での Node.js アプリの構造を理解してください。このドキュメントで説明しているサンプルアプリを実行する際に必要となるため、プロジェクト ID を書き留めておきます。

リポジトリのクローン作成

サンプルをダウンロード(クローンを作成)します。

git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples
cd nodejs-docs-samples/appengine/datastore

プロジェクト構成の編集と依存関係の設定

package.json では、@google-cloud/datastore を依存関係として設定します。これにより Datastore モードを使用するための関数が提供されます。

{
  "name": "appengine-datastore",
  "description": "Sample for Google Cloud Datastore on Google App Engine.",
  "version": "0.0.1",
  "private": true,
  "license": "Apache-2.0",
  "author": "Google Inc.",
  "repository": {
    "type": "git",
    "url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git"
  },
  "engines": {
    "node": "16.x.x"
  },
  "scripts": {
    "start": "node app.js",
    "system-test": "mocha --exit test/*.test.js",
    "test": "npm run system-test"
  },
  "dependencies": {
    "@google-cloud/datastore": "^7.0.0",
    "express": "^4.16.4"
  },
  "devDependencies": {
    "mocha": "^9.0.0",
    "supertest": "^6.0.0"
  }
}

アプリケーション コード

このサンプル アプリケーションは訪問者の IP のログ記録、取得、表示を行います。ログエントリがタイプ visit の単純な 2 フィールド クラスであり、データセットの save コマンドを使用して Cloud Datastore に保存されることを確認できます。データセットの runQuery コマンドを使用すると、最新の 10 件の訪問を降順に取得できます。

'use strict';

const express = require('express');
const crypto = require('crypto');

const app = express();
app.enable('trust proxy');

// By default, the client will authenticate using the service account file
// specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use
// the project specified by the GOOGLE_CLOUD_PROJECT environment variable. See
// https://github.com/GoogleCloudPlatform/google-cloud-node/blob/master/docs/authentication.md
// These environment variables are set automatically on Google App Engine
const {Datastore} = require('@google-cloud/datastore');

// Instantiate a datastore client
const datastore = new Datastore({
  projectId: 'long-door-651',
});

/**
 * Insert a visit record into the database.
 *
 * @param {object} visit The visit record to insert.
 */
const insertVisit = visit => {
  return datastore.save({
    key: datastore.key('visit'),
    data: visit,
  });
};

/**
 * Retrieve the latest 10 visit records from the database.
 */
const getVisits = () => {
  const query = datastore
    .createQuery('visit')
    .order('timestamp', {descending: true})
    .limit(10);

  return datastore.runQuery(query);
};

app.get('/', async (req, res, next) => {
  // Create a visit record to be stored in the database
  const visit = {
    timestamp: new Date(),
    // Store a hash of the visitor's ip address
    userIp: crypto
      .createHash('sha256')
      .update(req.ip)
      .digest('hex')
      .substr(0, 7),
  };

  try {
    await insertVisit(visit);
    const [entities] = await getVisits();
    const visits = entities.map(
      entity => `Time: ${entity.timestamp}, AddrHash: ${entity.userIp}`
    );
    res
      .status(200)
      .set('Content-Type', 'text/plain')
      .send(`Last 10 visits:\n${visits.join('\n')}`)
      .end();
  } catch (error) {
    next(error);
  }
});

const PORT = parseInt(parseInt(process.env.PORT)) || 8080;
app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
  console.log('Press Ctrl+C to quit.');
});

index.yaml ファイルの使用

このサンプルアプリは簡単なクエリを実行しています。複雑な Datastore クエリには 1 つ以上のインデックスが必要です。インデックスは、アプリとともにアップロードする index.yaml ファイルで指定する必要があります。

ローカルテスト

アプリケーションを開発してローカルでテストする必要がある場合は、Datastore モードエミュレータを使用できます。

詳細情報

最適化やコンセプトなどの Datastore モードの詳細は、Datastore モードの Firestore に関するドキュメントをご覧ください。