在 Datastore 模式下使用 Cloud Firestore

Firestore 是一个 NoSQL 文档数据库,能够自动扩缩、具备出色的性能,并且易于进行应用开发。Firestore 是 Datastore 的最新版本;与 Datastore 相比,这个新版本引入了多项改进功能。

由于 Datastore 模式 Firestore 针对服务器用例和 App Engine 进行了优化,因此,对于主要将由 App Engine 应用使用的数据库,我们建议使用 Datastore 模式 Firestore。原生模式 Firestore 最适合移动和实时通知用例。如需详细了解 Firestore 模式,请参阅选择原生模式或 Datastore 模式

本文档介绍了如何使用 Google Cloud 客户端库将数据存储在 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 的简单双字段类,并使用数据集 save 命令保存到 Datastore 模式。然后,使用数据集 runQuery 命令,按降序检索最近的十条访问记录。

'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 模式查询需要使用一个或多个索引,您必须在随应用一起上传的 index.yaml 文件中指定这些索引。此文件可以手动创建,也可以在本地测试应用时自动生成。

本地测试

如果您需要在本地开发和测试应用,则可以使用 Datastore 模式模拟器

了解详情

如需全面了解 Datastore 模式(包括优化和概念),请参阅 Datastore 模式 Firestore 文档