Home Manual Reference Source Test
import {InfluxDB} from 'influx'
public class | source

InfluxDB

InfluxDB is the public interface to run queries against the 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'
     ]
   }
 ]
})

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

Constructor Summary

Public Constructor
public

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

Method Summary

Public Methods
public

alterRetentionPolicy(name: String, options: Object): Promise<void>

Alters an existing retention policy on a database.

public

createContinuousQuery(name: String, query: String, database: String): Promise<void>

Creates a continuous query in a database

public

createDatabase(databaseName: string): Promise<void>

Creates a new database with the provided name.

public

createRetentionPolicy(name: String, options: Object): Promise<void>

Creates a new retention policy on a database.

public

createUser(username: String, password: String, admin: Boolean): Promise<void>

Creates a new InfluxDB user.

public

dropContinuousQuery(name: String, database: String): Promise<void>

Creates a continuous query in a database

public

dropDatabase(databaseName: string): Promise<void>

Deletes a database with the provided name.

public

dropMeasurement(measurement: String, database: String): Promise<void>

Removes a measurement from the database.

public

dropRetentionPolicy(name: String, database: String): Promise<void>

Deletes a retention policy and associated data.

public

dropSeries(options: *): Promise<void>

Removes a one or more series from InfluxDB.

public

dropUser(username: String): Promise<void>

Removes a user from the database.

public

Returns array of database names.

public

Returns array of measurements.

public

getSeries(options: Object): Promise<String[]>

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

public

getUsers(): Promise<Array<{user: String, admin: Boolean}>>

Returns a list of users on the Influx database.

public

grantAdminPrivilege(username: String): Promise<void>

Grants admin privileges to a specified user.

public

grantPrivilege(username: String, privilege: String, database: String): Promise<void>

Grants a privilege to a specified user.

public

ping(timeout: Number): Promise<IPingStats[]>

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

public

query(query: String | String[], options: IQueryOptions): Promise<IResults | Results[]>

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

public

queryRaw(query: String | String[], options: IQueryOptions): Promise<*>

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: String): Promise<void>

Removes a admin privilege from a specified user.

public

revokePrivilege(username: String, privilege: String, database: String): Promise<void>

Removes a privilege from a specified user.

public

setPassword(username: String, password: String): Promise<void>

Sets a password for an Influx user.

public

showContinousQueries(database: String): Promise<void>

Returns a list of continous queries in the database.

public

showRetentionPolicies(database: String): Promise<Array<{ name: String, duration: String, shardGroupDuration: String, replicaN: Number, default: Boolean }>>

Shows retention policies on the database

public

writeMeasurement(measurement: String, points: IPoint[], options: IWriteOptions): Promise<void>

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

public

writePoints(points: IPoint[], options: IWriteOptions): Promise<void>

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

Public Constructors

public constructor(options: IClusterConfig | ISingleHostConfig | string) source

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

Params:

NameTypeAttributeDescription
options IClusterConfig | ISingleHostConfig | string
  • 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'
      ]
    }
  ]
})

Public Methods

public alterRetentionPolicy(name: String, options: Object): Promise<void> source

Alters an existing retention policy on a database.

Params:

NameTypeAttributeDescription
name String

The retention policy name

options Object
options.database String
  • optional

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

options.duration String

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

options.replication Number

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

options.default Boolean
  • optional

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

Return:

Promise<void>

Example:

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

public createContinuousQuery(name: String, query: String, database: String): Promise<void> source

Creates a continuous query in a database

Params:

NameTypeAttributeDescription
name String

The query name, for later reference

query String

The body of the query to run

database String
  • optional

If not provided, uses the default database.

Return:

Promise<void>

Example:

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

public createDatabase(databaseName: string): Promise<void> source

Creates a new database with the provided name.

Params:

NameTypeAttributeDescription
databaseName string

Return:

Promise<void>

Example:

influx.createDatabase('mydb')

public createRetentionPolicy(name: String, options: Object): Promise<void> source

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

Params:

NameTypeAttributeDescription
name String

The retention policy name

options Object
options.database String
  • optional

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

options.duration String

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

options.replication Number

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

options.isDefault Boolean
  • optional

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

Return:

Promise<void>

Example:

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

public createUser(username: String, password: String, admin: Boolean): Promise<void> source

Creates a new InfluxDB user.

Params:

NameTypeAttributeDescription
username String
password String
admin Boolean
  • optional
  • default: false

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

Return:

Promise<void>

Example:

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

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

public dropContinuousQuery(name: String, database: String): Promise<void> source

Creates a continuous query in a database

Params:

NameTypeAttributeDescription
name String

The query name

database String
  • optional

If not provided, uses the default database.

Return:

Promise<void>

Example:

influx.dropContinuousQuery('downsample_cpu_1h')

public dropDatabase(databaseName: string): Promise<void> source

Deletes a database with the provided name.

Params:

NameTypeAttributeDescription
databaseName string

Return:

Promise<void>

Example:

influx.createDatabase('mydb')

public dropMeasurement(measurement: String, database: String): Promise<void> source

Removes a measurement from the database.

Params:

NameTypeAttributeDescription
measurement String
database String
  • optional

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

Return:

Promise<void>

Example:

influx.dropMeasurement('my_measurement')

public dropRetentionPolicy(name: String, database: String): Promise<void> 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 String

The retention policy name

database String
  • optional

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

Return:

Promise<void>

Example:

influx.dropRetentionPolicy('7d')

public dropSeries(options: *): Promise<void> source

Removes a one or more series from InfluxDB.

Params:

NameTypeAttributeDescription
options *

Return:

Promise<void>

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 dropUser(username: String): Promise<void> source

Removes a user from the database.

Params:

NameTypeAttributeDescription
username String

Return:

Promise<void>

Example:

influx.dropUser('connor')

public getDatabaseNames(): Promise<String[]> source

Returns array of database names. Requires cluster admin privileges.

Return:

Promise<String[]>

a list of database names

Example:

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

public getMeasurements(database: String): Promise<String[]> source

Returns array of measurements.

Params:

NameTypeAttributeDescription
database String
  • optional

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

Return:

Promise<String[]>

a list of measurement names

Example:

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

public getSeries(options: Object): Promise<String[]> 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 Object
  • optional
options.measurement String
  • optional

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

options.database String
  • optional

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

Return:

Promise<String[]>

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(): Promise<Array<{user: String, admin: Boolean}>> source

Returns a list of users on the Influx database.

Return:

Promise<Array<{user: String, admin: Boolean}>>

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: String): Promise<void> source

Grants admin privileges to a specified user.

Params:

NameTypeAttributeDescription
username String

Return:

Promise<void>

Example:

influx.grantAdminPrivilege('connor')

public grantPrivilege(username: String, privilege: String, database: String): Promise<void> source

Grants a privilege to a specified user.

Params:

NameTypeAttributeDescription
username String
privilege String

Should be one of 'READ' or 'WRITE'

database String
  • optional

If not provided, uses the default database.

Return:

Promise<void>

Example:

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

public ping(timeout: Number): Promise<IPingStats[]> source

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

Params:

NameTypeAttributeDescription
timeout Number

Given in milliseconds

Return:

Promise<IPingStats[]>

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: String | String[], options: IQueryOptions): Promise<IResults | Results[]> 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 String | String[]
options IQueryOptions
  • optional

Return:

Promise<IResults | Results[]>

result(s)

Example:

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

public queryRaw(query: String | String[], options: IQueryOptions): Promise<*> 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 String | String[]
options IQueryOptions
  • optional

Return:

Promise<*>

Example:

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

public revokeAdminPrivilege(username: String): Promise<void> source

Removes a admin privilege from a specified user.

Params:

NameTypeAttributeDescription
username String

Return:

Promise<void>

Example:

influx.revokeAdminPrivilege('connor')

public revokePrivilege(username: String, privilege: String, database: String): Promise<void> source

Removes a privilege from a specified user.

Params:

NameTypeAttributeDescription
username String
privilege String

Should be one of 'READ' or 'WRITE'

database String
  • optional

If not provided, uses the default database.

Return:

Promise<void>

Example:

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

public setPassword(username: String, password: String): Promise<void> source

Sets a password for an Influx user.

Params:

NameTypeAttributeDescription
username String
password String

Return:

Promise<void>

Example:

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

public showContinousQueries(database: String): Promise<void> source

Returns a list of continous queries in the database.

Params:

NameTypeAttributeDescription
database String
  • optional

If not provided, uses the default database.

Return:

Promise<void>

Example:

influx.showContinousQueries()

public showRetentionPolicies(database: String): Promise<Array<{ name: String, duration: String, shardGroupDuration: String, replicaN: Number, default: Boolean }>> source

Shows retention policies on the database

Params:

NameTypeAttributeDescription
database String
  • optional

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

Return:

Promise<Array<{ name: String, duration: String, shardGroupDuration: String, replicaN: Number, default: Boolean }>>

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 writeMeasurement(measurement: String, points: IPoint[], options: IWriteOptions): Promise<void> source

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

Params:

NameTypeAttributeDescription
measurement String
points IPoint[]
options IWriteOptions
  • optional

Return:

Promise<void>

Example:

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

public writePoints(points: IPoint[], options: IWriteOptions): Promise<void> 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 IPoint[]
options IWriteOptions
  • optional

Return:

Promise<void>

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'
})