Timescale 代码快速入门指南旨在帮助您将 Timescale 集成到您自己的程序中。它们使用您最喜欢的编程语言来解释如何连接到 Timescale 数据库、创建和管理超表以及摄取和查询数据。

本快速入门指南将引导您完成以下步骤

在开始之前,请确保您已拥有

  • 安装了 TimescaleDB。有关更多信息,请参阅安装文档
  • 安装了 Node.js
  • 安装了 Node.js 包管理器 npm

在本节中,您将使用一个名为 Sequelize 的常用 Node.js ORM(对象关系映射器)创建与 TimescaleDB 的连接。

  1. 在命令提示符下,初始化一个新的 Node.js 应用程序

    npm init -y

    这会在您的目录中创建一个 package.json 文件,其中包含您项目的所有依赖项。它看起来像这样

    {
    "name": "node-sample",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC"
    }
  2. 安装 Express.js

    npm install express
  3. 创建一个简单的网页以检查连接。创建一个名为 index.js 的新文件,内容如下

    const express = require('express')
    const app = express()
    const port = 3000;
    app.use(express.json());
    app.get('/', (req, res) => res.send('Hello World!'))
    app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))
  4. 通过启动应用程序来测试您的连接

    node index.js

    在您的 Web 浏览器中,导航到 http://localhost:3000。如果连接成功,它将显示“Hello World!”

  5. 将 Sequelize 添加到您的项目

    npm install sequelize sequelize-cli pg pg-hstore
  6. 找到您的 TimescaleDB 凭据,并使用它们来编写 Sequelize 的连接字符串。

    您将需要

    • 密码
    • 用户名
    • 主机 URL
    • 端口
    • 数据库名称
  7. 使用以下格式编写您的连接字符串变量

    'postgres://<user>:<password>@<host>:<port>/<dbname>'
  8. 打开您创建的 index.js 文件。在应用程序中引入 Sequelize,并声明连接字符串

    const Sequelize = require('sequelize')
    const sequelize = new Sequelize('postgres://<user>:<password>@<host>:<port>/<dbname>',
    {
    dialect: 'postgres',
    protocol: 'postgres',
    dialectOptions: {
    ssl: {
    require: true,
    rejectUnauthorized: false
    }
    }
    })

    确保在 dialectOptions 部分中添加 SSL 设置。如果不添加这些设置,您将无法使用 SSL 连接到 TimescaleDB。

  9. 您可以通过在 app.get 语句之后将以下行添加到 index.js 来测试连接

    sequelize.authenticate().then(() => {
    console.log('Connection has been established successfully.');
    }).catch(err => {
    console.error('Unable to connect to the database:', err);
    });

    在命令行启动应用程序

    node index.js

    如果连接成功,您将获得如下所示的输出

    Example app listening at http://localhost:3000
    Executing (default): SELECT 1+1 AS result
    Connection has been established successfully.

在本节中,您将创建一个名为 page_loads 的关系表。

  1. 使用 Sequelize 命令行工具创建一个名为 page_loads 的表和模型

    npx sequelize model:generate --name page_loads \
    --attributes userAgent:string,time:date

    输出结果类似于这样

    Sequelize CLI [Node: 12.16.2, CLI: 5.5.1, ORM: 5.21.11]
    New model was created at <PATH>.
    New migration was created at <PATH>.
  2. 编辑迁移文件,使其设置迁移键

    'use strict';
    module.exports = {
    up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('page_loads', {
    userAgent: {
    primaryKey: true,
    type: Sequelize.STRING
    },
    time: {
    primaryKey: true,
    type: Sequelize.DATE
    }
    });
    },
    down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable('page_loads');
    }
    };
  3. 迁移更改并确保它反映在数据库中

    npx sequelize db:migrate

    输出结果类似于这样

    Sequelize CLI [Node: 12.16.2, CLI: 5.5.1, ORM: 5.21.11]
    Loaded configuration file "config/config.json".
    Using environment "development".
    == 20200528195725-create-page-loads: migrating =======
    == 20200528195725-create-page-loads: migrated (0.443s)
  4. 在您的代码中创建 PageLoads 模型。在 index.js 文件中,在 app.use 语句上方,添加以下行

    let PageLoads = sequelize.define('page_loads', {
    userAgent: {type: Sequelize.STRING, primaryKey: true },
    time: {type: Sequelize.DATE, primaryKey: true }
    }, { timestamps: false });
  5. 实例化一个 PageLoads 对象并将其保存到数据库。

创建关系表后,您可以创建超表。创建表和索引、更改表、插入数据、选择数据以及大多数其他任务都在超表上执行。

  1. 创建一个迁移来修改 page_loads 关系表,并通过首先运行以下命令将其更改为超表

    npx sequelize migration:generate --name add_hypertable

    输出结果类似于这样

    Sequelize CLI [Node: 12.16.2, CLI: 5.5.1, ORM: 5.21.11]
    migrations folder at <PATH> already exists.
    New migration was created at <PATH>/20200601202912-add_hypertable.js .
  2. migrations 文件夹中,现在有一个新文件。打开该文件,并添加以下内容

    'use strict';
    module.exports = {
    up: (queryInterface, Sequelize) => {
    return queryInterface.sequelize.query("SELECT create_hypertable('page_loads', by_range('time'));");
    },
    down: (queryInterface, Sequelize) => {
    }
    };
    注意

    by_range 维度构建器是 TimescaleDB 2.13 的新增功能。

  3. 在命令提示符下,运行迁移命令

    npx sequelize db:migrate

    输出结果类似于这样

    Sequelize CLI [Node: 12.16.2, CLI: 5.5.1, ORM: 5.21.11]
    Loaded configuration file "config/config.json".
    Using environment "development".
    == 20200601202912-add_hypertable: migrating =======
    == 20200601202912-add_hypertable: migrated (0.426s)

本节介绍如何将数据插入到您的超表中。

  1. index.js 文件中,修改 / 路由以从请求对象 (req) 获取 user-agent 和当前时间戳。然后,在 PageLoads 模型上调用 create 方法,提供用户代理和时间戳参数。create 调用在数据库上执行 INSERT

    app.get('/', async (req, res) => {
    // get the user agent and current time
    const userAgent = req.get('user-agent');
    const time = new Date().getTime();
    try {
    // insert the record
    await PageLoads.create({
    userAgent, time
    });
    // send response
    res.send('Inserted!');
    } catch (e) {
    console.log('Error inserting data', e)
    }
    })

本节介绍如何对您的数据库执行查询。在本示例中,每次重新加载页面时,都会显示表中当前的所有信息。

  1. 修改 index.js 文件中的 / 路由,以调用 Sequelize findAll 函数,并使用 PageLoads 模型从 page_loads 表中检索所有数据

    app.get('/', async (req, res) => {
    // get the user agent and current time
    const userAgent = req.get('user-agent');
    const time = new Date().getTime();
    try {
    // insert the record
    await PageLoads.create({
    userAgent, time
    });
    // now display everything in the table
    const messages = await PageLoads.findAll();
    res.send(messages);
    } catch (e) {
    console.log('Error inserting data', e)
    }
    })

现在,当您重新加载页面时,您应该看到 page_loads 表中当前的所有行。

关键词

在此页面上发现问题?报告问题 或 在 GitHub 上编辑此页