• influxdb-client-ruby
    • Note: Use this client library with InfluxDB 2.x and InfluxDB 1.8+ ( see details ). For connecting to InfluxDB 1.7 or earlier instances, use the influxdb-ruby client library.
  • Documentation
  • Features
  • Installation
    • Install the Gem
  • Usage
    • Creating a client
      • Client Options
    • Queries
      • Query raw
      • Synchronous query
      • Query stream
      • Parameterized queries
    • Writing data
      • Batching
      • Time precision
      • Configure destination
      • Data format
      • Default Tags
        • Via API
    • Delete data
    • Management API
  • Advanced Usage
    • Check the server status
    • Proxy configuration
    • InfluxDB 1.8 API compatibility
  • Local tests
  • Contributing
  • License

    Ruby - 图1influxdb-client-ruby

    CircleCI codecov Gem Version License GitHub issues GitHub pull requests Slack Status

    This repository contains the reference Ruby client for the InfluxDB 2.x.

    Ruby - 图9Note: Use this client library with InfluxDB 2.x and InfluxDB 1.8+ (see details). For connecting to InfluxDB 1.7 or earlier instances, use the influxdb-ruby client library.

    Ruby - 图10Documentation

    This section contains links to the client library documentation.

    Ruby - 图11Features

    InfluxDB 2.x client consists of two packages

    • influxdb-client
      • Querying data using the Flux language
      • Writing data
        • batched in chunks on background
        • automatic retries on write failures
    • influxdb-client-apis
      • provides all other InfluxDB 2.x APIs for managing
        • buckets
        • labels
        • authorizations
      • built on top of influxdb-client

    Ruby - 图12Installation

    The InfluxDB 2 client is bundled as a gem and is hosted on Rubygems.

    Ruby - 图13Install the Gem

    The client can be installed manually or with bundler.

    To install the client gem manually:

    1. gem install influxdb-client -v 2.9.0

    For management API:

    1. gem install influxdb-client-apis -v 2.9.0

    Ruby - 图14Usage

    Ruby - 图15Creating a client

    Use InfluxDB::Client to create a client connected to a running InfluxDB 2 instance.

    1. client = InfluxDB2::Client.new('https://localhost:8086', 'my-token')
    2. client.do_something
    3. client.close!

    the InfluxDB::Client can be also used as a resource:

    1. InfluxDB2::Client.use('https://localhost:8086', 'my-token') do |client|
    2. client.do_something
    3. end

    Ruby - 图16Client Options

    OptionDescriptionTypeDefault
    bucketDefault destination bucket for writesStringnone
    orgDefault organization bucket for writesStringnone
    precisionDefault precision for the unix timestamps within the body line-protocolStringnone
    open_timeoutNumber of seconds to wait for the connection to openInteger10
    write_timeoutNumber of seconds to wait for one block of data to be writtenInteger10
    read_timeoutNumber of seconds to wait for one block of data to be readInteger10
    max_redirect_countMaximal number of followed HTTP redirectsInteger10
    redirect_forward_authorizationPass Authorization header to different domain during HTTP redirect.boolfalse
    use_sslTurn on/off SSL for HTTP communicationbooltrue
    verify_modeSets the flags for the certification verification at beginning of SSL/TLS session.OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEERnone
    loggerLogger used for logging. Disable logging by set to false.LoggerSTDOUT
    debuggingEnable debugging for HTTP request/response.boolfalse
    1. client = InfluxDB2::Client.new('https://localhost:8086', 'my-token',
    2. bucket: 'my-bucket',
    3. org: 'my-org',
    4. precision: InfluxDB2::WritePrecision::NANOSECOND)

    Ruby - 图17Queries

    The result retrieved by QueryApi could be formatted as a:

    1. Raw query response
    2. Flux data structure: FluxTable, FluxColumn and FluxRecord
    3. Stream of FluxRecord

    Ruby - 图18Query raw

    Synchronously executes the Flux query and return result as unprocessed String

    1. InfluxDB2::Client.use('https://localhost:8086', 'my-token', org: 'my-org') do |client|
    2. result = client
    3. .create_query_api
    4. .query_raw(query: 'from(bucket:"my-bucket") |> range(start: 1970-01-01) |> last()')
    5. puts result
    6. end

    Ruby - 图19Synchronous query

    Synchronously executes the Flux query and return result as a Array of FluxTables

    1. InfluxDB2::Client.use('https://localhost:8086', 'my-token', org: 'my-org') do |client|
    2. result = client
    3. .create_query_api
    4. .query(query: 'from(bucket:"my-bucket") |> range(start: 1970-01-01) |> last()')
    5. result.each do |table|
    6. table.records.each { |record| puts record.values }
    7. end
    8. end

    Ruby - 图20Query stream

    Synchronously executes the Flux query and return stream of FluxRecord

    1. InfluxDB2::Client.use('https://localhost:8086', 'my-token', org: 'my-org') do |client|
    2. stream = client
    3. .create_query_api
    4. .query_stream(query: 'from(bucket:"my-bucket") |> range(start: 1970-01-01) |> last()')
    5. stream.each do |record|
    6. puts record.values
    7. end
    8. end

    Ruby - 图21Parameterized queries

    InfluxDB Cloud supports Parameterized Queries that let you dynamically change values in a query using the InfluxDB API. Parameterized queries make Flux queries more reusable and can also be used to help prevent injection attacks.

    InfluxDB Cloud inserts the params object into the Flux query as a Flux record named params. Use dot or bracket notation to access parameters in the params record in your Flux query. Parameterized Flux queries support only int , float, and string data types. To convert the supported data types into other Flux basic data types, use Flux type conversion functions.

    Parameterized query example:

    ⚠️ Parameterized Queries are supported only in InfluxDB Cloud, currently there is no support in InfluxDB OSS.

    1. InfluxDB2::Client.use('https://localhost:8086', 'my-token', org: 'my-org') do |client|
    2. query = 'from(bucket: params.bucketParam) |> range(start: duration(v: params.startParam))'
    3. params = { 'bucketParam' => 'my-bucket', 'startParam' => '-1h' }
    4. query_api = client.create_query_api
    5. result = query_api.query(query: query, params: params)
    6. result[0].records.each { |record| puts "#{record.time} #{record.measurement}: #{record.field} #{record.value}" }
    7. end

    Ruby - 图22Writing data

    The WriteApi supports synchronous and batching writes into InfluxDB 2.x. In default api uses synchronous write. To enable batching you can use WriteOption.

    1. InfluxDB2::Client.use('https://localhost:8086', 'my-token',
    2. bucket: 'my-bucket',
    3. org: 'my-org',
    4. precision: InfluxDB2::WritePrecision::NANOSECOND) do |client|
    5. write_api = client.create_write_api
    6. write_api.write(data: 'h2o,location=west value=33i 15')
    7. end

    Ruby - 图23Batching

    The writes are processed in batches which are configurable by WriteOptions:

    PropertyDescriptionDefault Value
    batchSizethe number of data point to collect in batch1_000
    flush_intervalthe number of milliseconds before the batch is written1_000
    retry_intervalthe number of milliseconds to retry unsuccessful write. The retry interval is used when the InfluxDB server does not specify “Retry-After” header.5_000
    jitter_intervalthe number of milliseconds to increase the batch flush interval by a random amount0
    max_retriesthe number of max retries when write fails5
    max_retry_delaymaximum delay when retrying write in milliseconds125_000
    max_retry_timemaximum total retry timeout in milliseconds180_000
    exponential_basethe base for the exponential retry delay, the next delay is computed using random exponential backoff as a random value within the interval retry_interval exponential_base^(attempts-1) and retry_interval exponential_base^(attempts). Example for retry_interval=5000, exponential_base=2, max_retry_delay=125000, total=5 Retry delays are random distributed values within the ranges of [5000-10000, 10000-20000, 20000-40000, 40000-80000, 80000-125000]2
    batch_abort_on_exceptionthe batching worker will be aborted after failed retry strategyfalse
    1. InfluxDB2::Client.use('http://localhost:8086',
    2. 'my-token',
    3. bucket: 'my-bucket',
    4. org: 'my-org',
    5. precision: InfluxDB2::WritePrecision::NANOSECOND,
    6. use_ssl: false) do |client|
    7. write_options = InfluxDB2::WriteOptions.new(write_type: InfluxDB2::WriteType::BATCHING,
    8. batch_size: 10, flush_interval: 5_000,
    9. max_retries: 3, max_retry_delay: 15_000,
    10. exponential_base: 2)
    11. write_api = client.create_write_api(write_options: write_options)
    12. write_api.write(data: 'h2o,location=west value=33i 15')
    13. end

    Ruby - 图24Time precision

    Configure default time precision:

    1. InfluxDB2::Client.use('https://localhost:8086', 'my-token',
    2. bucket: 'my-bucket',
    3. org: 'my-org',
    4. precision: InfluxDB2::WritePrecision::NANOSECOND) do |client|
    5. client.do_something
    6. end

    Configure precision per write:

    1. InfluxDB2::Client.use('https://localhost:8086', 'my-token',
    2. bucket: 'my-bucket',
    3. org: 'my-org',
    4. precision: InfluxDB2::WritePrecision::NANOSECOND) do |client|
    5. write_api = client.create_write_api
    6. write_api.write(data: 'h2o,location=west value=33i 15', precision: InfluxDB2::WritePrecision::SECOND)
    7. end

    Allowed values for precision are:

    • InfluxDB2::WritePrecision::NANOSECOND for nanosecond
    • InfluxDB2::WritePrecision::MICROSECOND for microsecond
    • InfluxDB2::WritePrecision::MILLISECOND for millisecond
    • InfluxDB2::WritePrecision::SECOND for second

    Ruby - 图25Configure destination

    Default bucket and organization destination are configured via InfluxDB::Client:

    1. InfluxDB2::Client.use('https://localhost:8086', 'my-token',
    2. bucket: 'my-bucket',
    3. org: 'my-org') do |client|
    4. client.do_something
    5. end

    but there is also possibility to override configuration per write:

    1. InfluxDB2::Client.use('https://localhost:8086', 'my-token') do |client|
    2. write_api = client.create_write_api
    3. write_api.write(data: 'h2o,location=west value=33i 15', bucket: 'production-data', org: 'customer-1')
    4. end

    Ruby - 图26Data format

    The data could be written as:

    1. String that is formatted as a InfluxDB’s line protocol
    2. Hash with keys: name, tags, fields and time
    3. Data Point structure
    4. Array of above items
    1. InfluxDB2::Client.use('https://localhost:8086', 'my-token',
    2. bucket: 'my-bucket',
    3. org: 'my-org',
    4. precision: InfluxDB2::WritePrecision::NANOSECOND) do |client|
    5. point = InfluxDB2::Point.new(name: 'h2o')
    6. .add_tag('location', 'europe')
    7. .add_field('level', 2)
    8. hash = { name: 'h2o',
    9. tags: { host: 'aws', region: 'us' },
    10. fields: { level: 5, saturation: '99%' }, time: 123 }
    11. write_api = client.create_write_api
    12. write_api.write(data: ['h2o,location=west value=33i 15', point, hash])
    13. end

    Ruby - 图27Default Tags

    Sometimes is useful to store same information in every measurement e.g. hostname, location, customer. The client is able to use static value, app settings or env variable as a tag value.

    The expressions:

    • California Miner - static value
    • ${env.hostname} - environment property
    Ruby - 图28Via API
    1. InfluxDB2::Client.use('http://localhost:8086', 'my-token',
    2. bucket: 'my-bucket',
    3. org: 'my-org',
    4. precision: InfluxDB2::WritePrecision::NANOSECOND,
    5. use_ssl: false,
    6. tags: { id: '132-987-655' }) do |client|
    7. point_settings = InfluxDB2::PointSettings.new(default_tags: { customer: 'California Miner' })
    8. point_settings.add_default_tag('data_center', '${env.data_center}')
    9. write_api = client.create_write_api(write_options: InfluxDB2::SYNCHRONOUS,
    10. point_settings: point_settings)
    11. write_api.write(data: InfluxDB2::Point.new(name: 'h2o')
    12. .add_tag('location', 'europe')
    13. .add_field('level', 2))
    14. end

    Ruby - 图29Delete data

    The DeleteApi supports deletes points from an InfluxDB bucket.

    1. InfluxDB2::Client.use('http://localhost:8086', 'my-token',
    2. bucket: 'my-bucket',
    3. org: 'my-org',
    4. precision: InfluxDB2::WritePrecision::NANOSECOND) do |client|
    5. client.create_delete_api.delete(DateTime.rfc3339('2019-02-03T04:05:06+07:00'),
    6. DateTime.rfc3339('2019-03-03T04:05:06+07:00'),
    7. predicate: 'key1="value1" AND key2="value"')
    8. end

    The time range could be specified as:

    1. String - "2019-02-03T04:05:06+07:00"
    2. DateTime - DateTime.rfc3339('2019-03-03T04:05:06+07:00')
    3. Time - Time.utc(2015, 10, 16, 8, 20, 15)

    Ruby - 图30Management API

    The client supports following management API:

    API docs
    AuthorizationsApihttps://docs.influxdata.com/influxdb/latest/api/#tag/Authorizations
    BucketsApihttps://docs.influxdata.com/influxdb/latest/api/#tag/Buckets
    LabelsApihttps://docs.influxdata.com/influxdb/latest/api/#tag/Labels
    OrganizationsApihttps://docs.influxdata.com/influxdb/latest/api/#tag/Organizations
    UsersApihttps://docs.influxdata.com/influxdb/latest/api/#tag/Users

    The following example demonstrates how to use a InfluxDB 2.x Management API to create new bucket. For further information see docs and examples.

    1. #
    2. # This is an example how to create new bucket with permission to write.
    3. #
    4. # You could run example via: `cd apis && bundle exec ruby ../examples/create_new_bucket.rb`
    5. #
    6. $LOAD_PATH.unshift File.expand_path('../lib', __dir__)
    7. require 'influxdb-client'
    8. $LOAD_PATH.unshift File.expand_path('../apis/lib', __dir__)
    9. require 'influxdb-client-apis'
    10. url = 'http://localhost:8086'
    11. bucket = 'my-bucket'
    12. org = 'my-org'
    13. token = 'my-token'
    14. InfluxDB2::Client.use(url,
    15. token,
    16. bucket: bucket,
    17. org: org,
    18. use_ssl: false,
    19. precision: InfluxDB2::WritePrecision::NANOSECOND) do |client|
    20. api = InfluxDB2::API::Client.new(client)
    21. # Find my organization
    22. organization = api.create_organizations_api
    23. .get_orgs
    24. .orgs
    25. .select { |it| it.name == 'my-org' }
    26. .first
    27. #
    28. # Create new Bucket
    29. #
    30. retention_rule = InfluxDB2::API::RetentionRule.new(type: 'expire', every_seconds: 3600)
    31. bucket_name = 'new-bucket-name'
    32. request = InfluxDB2::API::PostBucketRequest.new(org_id: organization.id,
    33. name: bucket_name,
    34. retention_rules: [retention_rule])
    35. bucket = api.create_buckets_api
    36. .post_buckets(request)
    37. #
    38. # Create Permission to read/write from Bucket
    39. #
    40. resource = InfluxDB2::API::Resource.new(type: 'buckets',
    41. id: bucket.id,
    42. org_id: organization.id)
    43. authorization = InfluxDB2::API::Authorization.new(description: "Authorization to read/write bucket: #{bucket.name}",
    44. org_id: organization.id,
    45. permissions: [
    46. InfluxDB2::API::Permission.new(action: 'read', resource: resource),
    47. InfluxDB2::API::Permission.new(action: 'write', resource: resource)
    48. ])
    49. result = api.create_authorizations_api
    50. .post_authorizations(authorization)
    51. print("The token: '#{result.token}' is authorized to read/write from/to bucket: '#{bucket.name}'.")
    52. end

    Ruby - 图31Advanced Usage

    Ruby - 图32Check the server status

    Server availability can be checked using the client.ping method. That is equivalent of the influx ping.

    Ruby - 图33Proxy configuration

    You can configure the client to tunnel requests through an HTTP proxy. To configure the proxy use a http_proxy environment variable.

    1. ENV['HTTP_PROXY'] = 'http://my-user:my-password@my-proxy:8099'

    Client automatically follows HTTP redirects. The default redirect policy is to follow up to 10 consecutive requests. You can configure redirect counts by the client property: max_redirect_count.

    Due to a security reason Authorization header is not forwarded when redirect leads to a different domain. To overcome this limitation you have to set the client property redirect_forward_authorization to true.

    Ruby - 图34InfluxDB 1.8 API compatibility

    InfluxDB 1.8.0 introduced forward compatibility APIs for InfluxDB 2.x. This allow you to easily move from InfluxDB 1.x to InfluxDB 2.x Cloud or open source.

    The following forward compatible APIs are available:

    APIEndpointDescription
    query_api.rb/api/v2/queryQuery data in InfluxDB 1.8.0+ using the InfluxDB 2.x API and Flux (endpoint should be enabled by flux-enabled option)
    write_api.rb/api/v2/writeWrite data to InfluxDB 1.8.0+ using the InfluxDB 2.x API
    health_api.rb/healthCheck the health of your InfluxDB instance

    For detail info see InfluxDB 1.8 example.

    Ruby - 图35Local tests

    1. brew install wget # on a mac, if not yet installed!
    2. bin/influxdb-restart.sh
    3. rake test

    Ruby - 图36Contributing

    Bug reports and pull requests are welcome on GitHub at https://github.com/influxdata/influxdb-client-ruby.

    Ruby - 图37License

    The gem is available as open source under the terms of the MIT License.