Home Manual Reference Source Test
import {InfluxDB} from 'influx/src/index.js'
public class | source

InfluxDB

InfluxDB is the public interface to run queries against your database. This is a 'driver-level' module, not a a full-fleged ORM or ODM; you run queries directly by calling methods on this class.

Please check out some of the tutorials if you want help getting started!

Example:

const Influx = require('influx');
const influx = new Influx.InfluxDB({
 host: 'localhost',
 database: 'express_response_db',
 schema: [
   {
     measurement: 'response_times',
     fields: {
       path: Influx.FieldType.STRING,
       duration: Influx.FieldType.INTEGER
     },
     tags: [
       'host'
     ]
   }
 ]
})
// Connect over HTTPS
const Influx = require('influx');
const influx = new Influx.InfluxDB({
 host: 'myinfluxdbhost',
 port: 443,
 protocol: 'https'
 database: 'express_response_db',
 schema: [
   {
     measurement: 'response_times',
     fields: {
       path: Influx.FieldType.STRING,
       duration: Influx.FieldType.INTEGER
     },
     tags: [
       'host'
     ]
   }
 ]
})

influx.writePoints([
  {
    measurement: 'response_times',
    tags: { host: os.hostname() },
    fields: { duration, path: req.path },
  }
]).then(() => {
  return influx.query(`
    select * from response_times
    where host = $<host>
    order by time desc
    limit 10
  `, {
     placeholders: {
       host: os.hostname()
     }
  })
}).then(rows => {
  rows.forEach(row => console.log(`A request to ${row.path} took ${row.duration}ms`))
})

Constructor Summary

Public Constructor
public

constructor(options: *)

Connect to a single InfluxDB instance by specifying a set of connection options.

Member Summary

Private Members
private

_schema: *

Map of Schema instances defining measurements in Influx.

Method Summary

Public Methods
public

addSchema(schema: ISchemaOptions)

Adds specified schema for better fields coercing.

public

alterRetentionPolicy(name: *, options: *): *

Alters an existing retention policy on a database.

public

createContinuousQuery(name: *, query: *, database: *, resample: *): *

Creates a continuous query in a database

public

createDatabase(databaseName: *): *

Creates a new database with the provided name.

public

createRetentionPolicy(name: *, options: *): *

Creates a new retention policy on a database.

public

createUser(username: *, password: *, admin: *): *

Creates a new InfluxDB user.

public

dropContinuousQuery(name: *, database: *): *

Creates a continuous query in a database

public

dropDatabase(databaseName: *): *

Deletes a database with the provided name.

public

dropMeasurement(measurement: *, database: *): *

Removes a measurement from the database.

public

dropRetentionPolicy(name: *, database: *): *

Deletes a retention policy and associated data.

public

dropSeries(options: *): *

Removes a one or more series from InfluxDB.

public

dropShard(shard_id: *): *

Drops a shard with the provided number.

public

dropUser(username: *): *

Removes a user from the database.

public

Returns array of database names.

public

getMeasurements(database: *): *

Returns array of measurements.

public

getSeries(options: *): *

Returns a list of all series within the target measurement, or from the entire database if a measurement isn't provided.

public

getUsers(): *

Returns a list of users on the Influx database.

public

grantAdminPrivilege(username: *): *

Grants admin privileges to a specified user.

public

grantPrivilege(username: *, privilege: *, database: *): *

Grants a privilege to a specified user.

public

parsePoint(point: *, options: *): {"fields": *, "tags": *, "measurement": *, "timestamp": *, "fieldsPairs": *, "tagsNames": *, "castedTimestamp": *}

ParsePoint will perform the coercions/schema checks and return the data required for writing a point.

public

ping(timeout: *): *

Pings all available hosts, collecting online status and version info.

public

query(query: *, options: *): *

.query() runs a query (or list of queries), and returns the results in a friendly format, IResults.

public

queryRaw(query: *, options: *): *

QueryRaw functions similarly to .query() but it does no fancy transformations on the returned data; it calls JSON.parse and returns those results verbatim.

public

revokeAdminPrivilege(username: *): *

Removes a admin privilege from a specified user.

public

revokePrivilege(username: *, privilege: *, database: *): *

Removes a privilege from a specified user.

public

setPassword(username: *, password: *): *

Sets a password for an Influx user.

public

showContinousQueries(database: *): *

Returns a list of continous queries in the database.

public

showRetentionPolicies(database: *): *

Shows retention policies on the database

public

showShards(database: *): *

Shows shards on the database

public

writeMeasurement(measurement: *, points: *, options: *): *

WriteMeasurement functions similarly to InfluxDB#writePoints, but it automatically fills in the measurement value for all points for you.

public

writePoints(points: *, options: *): *

WritePoints sends a list of points together in a batch to InfluxDB.

Private Methods
private

_createSchema(schema: ISchemaOptions)

Creates specified measurement schema

private

_defaultDB(): *

Returns the default database that queries operates on.

private

_getQueryOpts(params: *, method: string): {"method": *, "path": string, "query": *}

Creates options to be passed into the pool to query databases.

Public Constructors

public constructor(options: *) source

Connect to a single InfluxDB instance by specifying a set of connection options.

Params:

NameTypeAttributeDescription
options *
  • optional
  • default: 'http://root:root@127.0.0.1:8086'

Example:

const Influx = require('influx')

// Connect to a single host with a DSN:
const influx = new Influx.InfluxDB('http://user:password@host:8086/database')
const Influx = require('influx')

// Connect to a single host with a full set of config details and
// a custom schema
const client = new Influx.InfluxDB({
  database: 'my_db',
  host: 'localhost',
  port: 8086,
  username: 'connor',
  password: 'pa$$w0rd',
  schema: [
    {
      measurement: 'perf',
      fields: {
        memory_usage: Influx.FieldType.INTEGER,
        cpu_usage: Influx.FieldType.FLOAT,
        is_online: Influx.FieldType.BOOLEAN
      }
      tags: [
        'hostname'
      ]
    }
  ]
})
const Influx = require('influx')

// Use a pool of several host connections and balance queries across them:
const client = new Influx.InfluxDB({
  database: 'my_db',
  username: 'connor',
  password: 'pa$$w0rd',
  hosts: [
    { host: 'db1.example.com' },
    { host: 'db2.example.com' },
  ],
  schema: [
    {
      measurement: 'perf',
      fields: {
        memory_usage: Influx.FieldType.INTEGER,
        cpu_usage: Influx.FieldType.FLOAT,
        is_online: Influx.FieldType.BOOLEAN
      }
      tags: [
        'hostname'
      ]
    }
  ]
})

Private Members

private _schema: * source

Map of Schema instances defining measurements in Influx.

Public Methods

public addSchema(schema: ISchemaOptions) source

Adds specified schema for better fields coercing.

Params:

NameTypeAttributeDescription
schema ISchemaOptions

public alterRetentionPolicy(name: *, options: *): * source

Alters an existing retention policy on a database.

Params:

NameTypeAttributeDescription
name *

The retention policy name

options *
options.database *
  • optional

Database to create the policy on, uses the default database if not provided.

options.duration *

How long data in the retention policy should be stored for, should be in a format like 7d. See details here

options.replication *

How many servers data in the series should be replicated to.

options.default *
  • optional

Whether the retention policy should be the default policy on the database.

Return:

*

Example:

influx.alterRetentionPolicy('7d', {
 duration: '7d',
 replication: 1,
 default: true
})

public createContinuousQuery(name: *, query: *, database: *, resample: *): * source

Creates a continuous query in a database

Params:

NameTypeAttributeDescription
name *

The query name, for later reference

query *

The body of the query to run

database *
  • optional

If not provided, uses the default database.

resample *
  • optional

If provided, adds resample policy

Return:

*

Example:

influx.createContinuousQuery('downsample_cpu_1h', `
  SELECT MEAN(cpu) INTO "7d"."perf"
  FROM "1d"."perf" GROUP BY time(1m)
`, undefined, 'RESAMPLE FOR 7m')

public createDatabase(databaseName: *): * source

Creates a new database with the provided name.

Params:

NameTypeAttributeDescription
databaseName *

Return:

*

Example:

influx.createDatabase('mydb')

public createRetentionPolicy(name: *, options: *): * source

Creates a new retention policy on a database. You can read more about Downsampling and Retention on the InfluxDB website.

Params:

NameTypeAttributeDescription
name *

The retention policy name

options *
options.database *
  • optional

Database to create the policy on, uses the default database if not provided.

options.duration *

How long data in the retention policy should be stored for, should be in a format like 7d. See details here

options.replication *

How many servers data in the series should be replicated to.

options.isDefault *
  • optional

Whether the retention policy should be the default policy on the database.

Return:

*

Example:

influx.createRetentionPolicy('7d', {
 duration: '7d',
 replication: 1
})

public createUser(username: *, password: *, admin: *): * source

Creates a new InfluxDB user.

Params:

NameTypeAttributeDescription
username *
password *
admin *
  • optional
  • default: false

If true, the user will be given all privileges on all databases.

Return:

*

Example:

influx.createUser('connor', 'pa55w0rd', true) // make 'connor' an admin

// make non-admins:
influx.createUser('not_admin', 'pa55w0rd')

public dropContinuousQuery(name: *, database: *): * source

Creates a continuous query in a database

Params:

NameTypeAttributeDescription
name *

The query name

database *
  • optional

If not provided, uses the default database.

Return:

*

Example:

influx.dropContinuousQuery('downsample_cpu_1h')

public dropDatabase(databaseName: *): * source

Deletes a database with the provided name.

Params:

NameTypeAttributeDescription
databaseName *

Return:

*

Example:

influx.dropDatabase('mydb')

public dropMeasurement(measurement: *, database: *): * source

Removes a measurement from the database.

Params:

NameTypeAttributeDescription
measurement *
database *
  • optional

the database the measurement lives in, optional if a default database is provided.

Return:

*

Example:

influx.dropMeasurement('my_measurement')

public dropRetentionPolicy(name: *, database: *): * source

Deletes a retention policy and associated data. Note that the data will not be immediately destroyed, and will hang around until Influx's bi-hourly cron.

Params:

NameTypeAttributeDescription
name *

The retention policy name

database *
  • optional

Database name that the policy lives in, uses the default database if not provided.

Return:

*

Example:

influx.dropRetentionPolicy('7d')

public dropSeries(options: *): * source

Removes a one or more series from InfluxDB.

Params:

NameTypeAttributeDescription
options *

Return:

*

Example:

// The following pairs of queries are equivalent: you can chose either to
// use our builder or pass in string directly. The builder takes care
// of escaping and most syntax handling for you.

influx.dropSeries({ where: e => e.tag('cpu').equals.value('cpu8') })
influx.dropSeries({ where: '"cpu" = \'cpu8\'' })
// DROP SERIES WHERE "cpu" = 'cpu8'

influx.dropSeries({ measurement: m => m.name('cpu').policy('autogen') })
influx.dropSeries({ measurement: '"cpu"."autogen"' })
// DROP SERIES FROM "autogen"."cpu"

influx.dropSeries({
  measurement: m => m.name('cpu').policy('autogen'),
  where: e => e.tag('cpu').equals.value('cpu8'),
  database: 'my_db'
})
// DROP SERIES FROM "autogen"."cpu" WHERE "cpu" = 'cpu8'

public dropShard(shard_id: *): * source

Drops a shard with the provided number.

Params:

NameTypeAttributeDescription
shard_id *

Return:

*

Example:

influx.dropShard(3)

public dropUser(username: *): * source

Removes a user from the database.

Params:

NameTypeAttributeDescription
username *

Return:

*

Example:

influx.dropUser('connor')

public getDatabaseNames(): * source

Returns array of database names. Requires cluster admin privileges.

Return:

*

a list of database names

Example:

influx.getDatabaseNames().then(names =>
  console.log('My database names are: ' + names.join(', ')));

public getMeasurements(database: *): * source

Returns array of measurements.

Params:

NameTypeAttributeDescription
database *
  • optional

the database the measurement lives in, optional if a default database is provided.

Return:

*

a list of measurement names

Example:

influx.getMeasurements().then(names =>
  console.log('My measurement names are: ' + names.join(', ')));

public getSeries(options: *): * source

Returns a list of all series within the target measurement, or from the entire database if a measurement isn't provided.

Params:

NameTypeAttributeDescription
options *
  • optional
options.measurement *
  • optional

if provided, we'll only get series from within that measurement.

options.database *
  • optional

the database the series lives in, optional if a default database is provided.

Return:

*

a list of series names

Example:

influx.getSeries().then(names => {
  console.log('My series names in my_measurement are: ' + names.join(', '))
})

influx.getSeries({
  measurement: 'my_measurement',
  database: 'my_db'
}).then(names => {
  console.log('My series names in my_measurement are: ' + names.join(', '))
})

public getUsers(): * source

Returns a list of users on the Influx database.

Return:

*

Example:

influx.getUsers().then(users => {
  users.forEach(user => {
    if (user.admin) {
      console.log(user.user, 'is an admin!')
    } else {
      console.log(user.user, 'is not an admin!')
    }
  })
})

public grantAdminPrivilege(username: *): * source

Grants admin privileges to a specified user.

Params:

NameTypeAttributeDescription
username *

Return:

*

Example:

influx.grantAdminPrivilege('connor')

public grantPrivilege(username: *, privilege: *, database: *): * source

Grants a privilege to a specified user.

Params:

NameTypeAttributeDescription
username *
privilege *

Should be one of 'READ' or 'WRITE'

database *
  • optional

If not provided, uses the default database.

Return:

*

Example:

influx.grantPrivilege('connor', 'READ', 'my_db') // grants read access on my_db to connor

public parsePoint(point: *, options: *): {"fields": *, "tags": *, "measurement": *, "timestamp": *, "fieldsPairs": *, "tagsNames": *, "castedTimestamp": *} source

ParsePoint will perform the coercions/schema checks and return the data required for writing a point. This will throw an error if a schema check or coercion fails. This can be useful for flagging or "throwing out" bad points in a batch write to prevent the entire batch from getting aborted


A note when using this function, InfluxDB#writePoints will still perform the same checks, so any pre-processed data will be checked for validity twice which has potential performance implications on large data sets

Params:

NameTypeAttributeDescription
point *
options *
  • optional

Return:

{"fields": *, "tags": *, "measurement": *, "timestamp": *, "fieldsPairs": *, "tagsNames": *, "castedTimestamp": *}

Example:

// parse a point as if it is getting written to the default
// databse with the default time precision
influx.parsePoint({
    measurement: 'perf',
    tags: { host: 'box1.example.com' },
    fields: { cpu: getCpuUsage(), mem: getMemUsage() },
})

// you can manually specify the database and time precision
influx.parsePoint({
    measurement: 'perf',
    tags: { host: 'box1.example.com' },
    fields: { cpu: getCpuUsage(), mem: getMemUsage() },
}, {
  precision: 's',
  database: 'my_db'
})

// if an error occurs, you can catch the error with try...catch
try {
  influx.parsePoint({
    measurement: 'perf',
    tags: { host: 'box1.example.com', myExtraneousTag: 'value' },
    fields: { cpu: getCpuUsage(), mem: getMemUsage(), myExtraneousField: 'value' },
  })
} catch(err) {
  handleError(err);
}

public ping(timeout: *): * source

Pings all available hosts, collecting online status and version info.

Params:

NameTypeAttributeDescription
timeout *

Given in milliseconds

Return:

*

Example:

influx.ping(5000).then(hosts => {
  hosts.forEach(host => {
    if (host.online) {
      console.log(`${host.url.host} responded in ${host.rtt}ms running ${host.version})`)
    } else {
      console.log(`${host.url.host} is offline :(`)
    }
  })
})

public query(query: *, options: *): * source

.query() runs a query (or list of queries), and returns the results in a friendly format, IResults. If you run multiple queries, an array of results will be returned, otherwise a single result (array of objects) will be returned.

Params:

NameTypeAttributeDescription
query *
options *
  • optional

Return:

*

result(s)

Example:

influx.query('select * from perf').then(results => {
  console.log(results)
})

public queryRaw(query: *, options: *): * source

QueryRaw functions similarly to .query() but it does no fancy transformations on the returned data; it calls JSON.parse and returns those results verbatim.

Params:

NameTypeAttributeDescription
query *
options *
  • optional

Return:

*

Example:

influx.queryRaw('select * from perf').then(rawData => {
  console.log(rawData)
})

public revokeAdminPrivilege(username: *): * source

Removes a admin privilege from a specified user.

Params:

NameTypeAttributeDescription
username *

Return:

*

Example:

influx.revokeAdminPrivilege('connor')

public revokePrivilege(username: *, privilege: *, database: *): * source

Removes a privilege from a specified user.

Params:

NameTypeAttributeDescription
username *
privilege *

Should be one of 'READ' or 'WRITE'

database *
  • optional

If not provided, uses the default database.

Return:

*

Example:

influx.revokePrivilege('connor', 'READ', 'my_db') // removes read access on my_db from connor

public setPassword(username: *, password: *): * source

Sets a password for an Influx user.

Params:

NameTypeAttributeDescription
username *
password *

Return:

*

Example:

influx.setPassword('connor', 'pa55w0rd')

public showContinousQueries(database: *): * source

Returns a list of continous queries in the database.

Params:

NameTypeAttributeDescription
database *
  • optional

If not provided, uses the default database.

Return:

*

Example:

influx.showContinousQueries()

public showRetentionPolicies(database: *): * source

Shows retention policies on the database

Params:

NameTypeAttributeDescription
database *
  • optional

The database to list policies on, uses the default database if not provided.

Return:

*

Example:

influx.showRetentionPolicies().then(policies => {
  expect(policies.slice()).to.deep.equal([
    {
      name: 'autogen',
      duration: '0s',
      shardGroupDuration: '168h0m0s',
      replicaN: 1,
      default: true,
    },
    {
      name: '7d',
      duration: '168h0m0s',
      shardGroupDuration: '24h0m0s',
      replicaN: 1,
      default: false,
    },
  ])
})

public showShards(database: *): * source

Shows shards on the database

Params:

NameTypeAttributeDescription
database *
  • optional

The database to list policies on, uses the default database if not provided.

Return:

*

Example:

influx.showShards().then(shards => {
  expect(shards.slice()).to.deep.equal([
    {
	id: 1
	database: 'database',
	retention_policy: 'autogen',
	shard_group: 1,
	start_time: '2019-05-06T00:00:00Z',
	end_time: '2019-05-13T00:00:00Z',
	expiry_time: '2019-05-13T00:00:00Z',
	owners: null,
    },
  ])
})

public writeMeasurement(measurement: *, points: *, options: *): * source

WriteMeasurement functions similarly to InfluxDB#writePoints, but it automatically fills in the measurement value for all points for you.

Params:

NameTypeAttributeDescription
measurement *
points *
options *
  • optional

Return:

*

Example:

influx.writeMeasurement('perf', [
  {
    tags: { host: 'box1.example.com' },
    fields: { cpu: getCpuUsage(), mem: getMemUsage() },
  }
])

public writePoints(points: *, options: *): * source

WritePoints sends a list of points together in a batch to InfluxDB. In each point you must specify the measurement name to write into as well as a list of tag and field values. Optionally, you can specify the time to tag that point at, defaulting to the current time.

If you defined a schema for the measurement in the options you passed to new Influx(options), we'll use that to make sure that types get cast correctly and that there are no extraneous fields or columns.

For best performance, it's recommended that you batch your data into sets of a couple thousand records before writing it. In the future we'll have some utilities within node-influx to make this easier.


A note when using manually-specified times and precisions: by default we write using the ms precision since that's what JavaScript gives us. You can adjust this. However, there is some special behaviour if you manually specify a timestamp in your points:

  • if you specify the timestamp as a Date object, we'll convert it to milliseconds and manipulate it as needed to get the right precision
  • if provide a INanoDate as returned from toNanoTime or the results from an Influx query, we'll be able to pull the precise nanosecond timestamp and manipulate it to get the right precision
  • if you provide a string or number as the timestamp, we'll pass it straight into Influx.

Please see the IPoint and IWriteOptions types for a full list of possible options.

Params:

NameTypeAttributeDescription
points *
options *
  • optional

Return:

*

Example:

// write a point into the default database with
// the default retention policy.
influx.writePoints([
  {
    measurement: 'perf',
    tags: { host: 'box1.example.com' },
    fields: { cpu: getCpuUsage(), mem: getMemUsage() },
  }
])

// you can manually specify the database,
// retention policy, and time precision:
influx.writePoints([
  {
    measurement: 'perf',
    tags: { host: 'box1.example.com' },
    fields: { cpu: getCpuUsage(), mem: getMemUsage() },
    timestamp: getLastRecordedTime(),
  }
], {
  database: 'my_db',
  retentionPolicy: '1d',
  precision: 's'
})

Private Methods

private _createSchema(schema: ISchemaOptions) source

Creates specified measurement schema

Params:

NameTypeAttributeDescription
schema ISchemaOptions

private _defaultDB(): * source

Returns the default database that queries operates on. It throws if called when a default database isn't set.

Return:

*

private _getQueryOpts(params: *, method: string): {"method": *, "path": string, "query": *} source

Creates options to be passed into the pool to query databases.

Params:

NameTypeAttributeDescription
params *
method string
  • optional
  • default: GET

Return:

{"method": *, "path": string, "query": *}