node-influx
    Preparing search index...

    Class 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!

    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`))
    })
    Index
    • Alters an existing retention policy on a database.

      Parameters

      Returns Promise<void>

      influx.alterRetentionPolicy('7d', {
      duration: '7d',
      replication: 1,
      default: true
      })
    • Creates a continuous query in a database

      Parameters

      • name: string

        The query name, for later reference

      • query: string

        The body of the query to run

      • Optionaldatabase: string = ...

        If not provided, uses the default database.

      • Optionalresample: string = ""

        If provided, adds resample policy

      Returns Promise<void>

      influx.createContinuousQuery('downsample_cpu_1h', `
      SELECT MEAN(cpu) INTO "7d"."perf"
      FROM "1d"."perf" GROUP BY time(1m)
      `, undefined, 'RESAMPLE FOR 7m')
    • Creates a new database with the provided name.

      Parameters

      • databaseName: string

      Returns Promise<void>

      influx.createDatabase('mydb')
      
    • Creates a new InfluxDB user.

      Parameters

      • username: string
      • password: string
      • Optionaladmin: boolean = false

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

      Returns Promise<void>

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

      // make non-admins:
      influx.createUser('not_admin', 'pa55w0rd')
    • Creates a continuous query in a database

      Parameters

      • name: string

        The query name

      • Optionaldatabase: string = ...

        If not provided, uses the default database.

      Returns Promise<void>

      influx.dropContinuousQuery('downsample_cpu_1h')
      
    • Deletes a database with the provided name.

      Parameters

      • databaseName: string

      Returns Promise<void>

      influx.dropDatabase('mydb')
      
    • Removes a measurement from the database.

      Parameters

      • measurement: string
      • Optionaldatabase: string = ...

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

      Returns Promise<void>

      influx.dropMeasurement('my_measurement')
      
    • 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.

      Parameters

      • name: string

        The retention policy name

      • Optionaldatabase: string = ...

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

      Returns Promise<void>

      influx.dropRetentionPolicy('7d')
      
    • Removes a one or more series from InfluxDB.

      Parameters

      Returns Promise<void>

      // 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'
    • Drops a shard with the provided number.

      Parameters

      • shard_id: number

      Returns Promise<void>

      influx.dropShard(3)
      
    • Removes a user from the database.

      Parameters

      • username: string

      Returns Promise<void>

      influx.dropUser('connor')
      
    • Returns array of database names. Requires cluster admin privileges.

      Returns Promise<string[]>

      a list of database names

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

      Parameters

      • Optionaldatabase: string = ...

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

      Returns Promise<string[]>

      a list of measurement names

      influx.getMeasurements().then(names =>
      console.log('My measurement names are: ' + names.join(', ')));
    • Returns a list of all series within the target measurement, or from the entire database if a measurement isn't provided.

      Parameters

      • Optionaloptions: { database?: string; measurement?: string } = {}
        • Optionaldatabase?: string

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

        • Optionalmeasurement?: string

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

      Returns Promise<string[]>

      a list of series names

      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(', '))
      })
    • Returns a list of users on the Influx database.

      Returns Promise<IResults<{ admin: boolean; user: string }>>

      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!')
      }
      })
      })
    • Grants admin privileges to a specified user.

      Parameters

      • username: string

      Returns Promise<void>

      influx.grantAdminPrivilege('connor')
      
    • Grants a privilege to a specified user.

      Parameters

      • username: string
      • privilege: "READ" | "WRITE"

        Should be one of 'READ' or 'WRITE'

      • Optionaldatabase: string = ...

        If not provided, uses the default database.

      Returns Promise<void>

      influx.grantPrivilege('connor', 'READ', 'my_db') // grants read access on my_db to connor
      
    • 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

      Parameters

      Returns IParsedPoint

      // 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);
      }
    • Pings all available hosts, collecting online status and version info.

      Parameters

      • timeout: number

        Given in milliseconds

      Returns Promise<IPingStats[]>

      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 :(`)
      }
      })
      })
    • QueryRaw functions similarly to .query() but it does no fancy transformations on the returned data; it calls JSON.parse and returns those results verbatim.

      Parameters

      Returns Promise<any>

      influx.queryRaw('select * from perf').then(rawData => {
      console.log(rawData)
      })
    • Removes a admin privilege from a specified user.

      Parameters

      • username: string

      Returns Promise<void>

      influx.revokeAdminPrivilege('connor')
      
    • Removes a privilege from a specified user.

      Parameters

      • username: string
      • privilege: "READ" | "WRITE"

        Should be one of 'READ' or 'WRITE'

      • Optionaldatabase: string = ...

        If not provided, uses the default database.

      Returns Promise<void>

      influx.revokePrivilege('connor', 'READ', 'my_db') // removes read access on my_db from connor
      
    • Sets a password for an Influx user.

      Parameters

      • username: string
      • password: string

      Returns Promise<void>

      influx.setPassword('connor', 'pa55w0rd')
      
    • Returns a list of continous queries in the database.

      Parameters

      • Optionaldatabase: string = ...

        If not provided, uses the default database.

      Returns Promise<IResults<{ name: string; query: string }>>

      influx.showContinousQueries()
      
    • Shows retention policies on the database

      Parameters

      • Optionaldatabase: string = ...

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

      Returns Promise<
          IResults<
              {
                  default: boolean;
                  duration: string;
                  name: string;
                  replicaN: number;
                  shardGroupDuration: string;
              },
          >,
      >

      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,
      },
      ])
      })
    • Shows shards on the database

      Parameters

      • Optionaldatabase: string = ...

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

      Returns Promise<
          {
              database: string;
              end_time: string;
              expiry_time: string;
              id: number;
              owners: string;
              retention_policy: string;
              shard_group: number;
              start_time: string;
          }[],
      >

      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,
      },
      ])
      })
    • WriteMeasurement functions similarly to InfluxDB#writePoints, but it automatically fills in the measurement value for all points for you.

      Parameters

      Returns Promise<void>

      influx.writeMeasurement('perf', [
      {
      tags: { host: 'box1.example.com' },
      fields: { cpu: getCpuUsage(), mem: getMemUsage() },
      }
      ])
    • 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.

      Parameters

      Returns Promise<void>

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