首页 > 解决方案 > 如何使用 NodeJS 将一组测量值写入 InfluxDB?

问题描述

我正在尝试将一组 CPU 温度注入 InfluxDB 实例。以下代码将仅注入集合中的最后一个样本 ( cpu= 5)。如何将一系列点注入测量?

const Influx = require("influx");
const os = require("os");

const influx = new Influx.InfluxDB({
    host: "localhost",
    database: "example",
    schema: [
        {
            measurement: 'cpu-temp',
            fields: { temp: Influx.FieldType.FLOAT, cpu: Influx.FieldType.INTEGER, socket: Influx.FieldType.INTEGER },
            tags: [ 'host' ]
        }
    ]
});


function writeTemps() {
    //In real life this would use something `sensors` package to obtain the data and transformed into this structure
    const data = [];
    for (let i = 0; i < 6; i++) {
        data.push({
            measurement: "cpu-temp",
            tags: {
                host: os.hostname()
            },
            fields: {
                cpu: i,
                temp: Math.round(((Math.random() * 24) + 24 * 10)) / 10,
                socket: 1
            }
        });
    }
    influx.writePoints(data).then(() => console.log("worked"), (e) => console.error(e));
}

writeTemps();

测量中的示例数据:

> select * from "cpu-temp"
name: cpu-temp
time                cpu host          socket temp
----                --- ----          ------ ----
1554481960188163700 5   Deckard.local 1      26.2
1554481961157513900 5   Deckard.local 1      24.3
1554481962159479300 5   Deckard.local 1      24.5
1554481963161301300 5   Deckard.local 1      24.9
1554481964166741100 5   Deckard.local 1      24.7
1554481965168176800 5   Deckard.local 1      26.2
1554481966168756700 5   Deckard.local 1      24.9
1554481967140210800 5   Deckard.local 1      25.6
1554481968145122000 5   Deckard.local 1      25.9
1554481969144965800 5   Deckard.local 1      25.9
1554481970150685100 5   Deckard.local 1      24.8
1554481971155935600 5   Deckard.local 1      25.7
1554481972160289200 5   Deckard.local 1      24.2
1554481973167241600 5   Deckard.local 1      26.3
1554481974172369600 5   Deckard.local 1      24.2
1554481975176451200 5   Deckard.local 1      25.1
1554481976179103100 5   Deckard.local 1      24.6
1554481977183923100 5   Deckard.local 1      26.2
1554481978189576000 5   Deckard.local 1      25.9
1554481979193856300 5   Deckard.local 1      24.2
1554481980199759900 5   Deckard.local 1      26.3
1554481981205830500 5   Deckard.local 1      24.4
>

标签: node.jsinfluxdb

解决方案


您的代码插入所有记录。但是,您不会插入唯一点,因此您的点在 InfluxDB 级别上被“重复数据删除”。如何定义独特点?

https://docs.influxdata.com/influxdb/v1.7/troubleshooting/frequently-asked-questions/#how-does-influxdb-handle-duplicate-points

一个点由测量名称、标签集和时间戳唯一标识。

因此,更改您的测量模式并插入cpu为 a tag,而不是 a field,您将插入唯一点 => 您将在 InfluxDB 中看到所有记录。


推荐阅读