influxdb-client-dart

    This repository contains the reference Dart client for the InfluxDB 2.x. It works on all platforms including web, server, and Flutter. Please submit issues and pull requests, help out, or just give encouragement.

    This section contains links to the client library documentation.

    Dart - 图11Features

    InfluxDB 2.x client supports:

    • Querying data using the Flux language
      • Streaming result to
    • Writing data
      • batched in chunks on background
      • automatic retries on write failures
    • Management API
      • provides all other InfluxDB 2.x APIs for managing
        • health check
        • sources, buckets
        • tasks
        • authorizations

    Library works in web, server, and Flutter.

    Installation

    Dart developer can add it as a dependency in their pubspec.yaml:

    1. import 'package:influxdb_client/api.dart';

    Dart - 图16Creating a client

    Specify url and token via parameters:

    1. var client = InfluxDBClient(
    2. url: 'http://localhost:8086',
    3. token: 'my-token',
    4. org: 'my-org',
    5. bucket: 'my-bucket',
    6. debug: true);

    Client Options

    Dart - 图18InfluxDB 1.8 API compatibility

    1. var client = InfluxDBClient(
    2. url: 'http://localhost:8086',
    3. username: '...',
    4. password: '...',
    5. org: 'my-org',
    6. bucket: 'my-bucket',
    7. debug: true);

    The WriteApi supports asynchronous writes into InfluxDB 2.x.

    The data could be written as:

    1. String that is formatted as a InfluxDB’s Line Protocol
    2. structure
    3. Array of above items

    The following example demonstrates how to write data with different type of records. For further information see docs and examples.

    1. import 'package:influxdb_client/api.dart';
    2. main() async {
    3. var client = InfluxDBClient(
    4. url: 'http://localhost:8086',
    5. token: 'my-token',
    6. org: 'my-org',
    7. debugEnabled: true);
    8. var writeApi = WriteService(client);
    9. var point = Point('h2o')
    10. .addTag('location', 'Prague')
    11. .addField('level', 1.12345)
    12. .time(DateTime.now().toUtc());
    13. await writeApi.write(point).then((value) {
    14. print('Write completed 1');
    15. }).catchError((exception) {
    16. // error block
    17. print("Handle write error here!");
    18. print(exception);
    19. });
    20. }

    WriteOptions

    Example how to modify default WriteOptions:

    • sources -

    Queries

    The result retrieved by QueryService could be formatted as a:

    Query to FluxRecord

    1. import 'package:influxdb_client/api.dart';
    2. void main() async {
    3. var client = InfluxDBClient(
    4. url: 'http://localhost:8086',
    5. token: 'my-token',
    6. org: 'my-org',
    7. bucket: 'my-bucket',
    8. );
    9. var queryService = client.getQueryService();
    10. var recordStream = await queryService.query('''
    11. from(bucket: "my-bucket")
    12. |> range(start: 0)
    13. |> filter(fn: (r) => r["_measurement"] == "cpu")
    14. |> aggregateWindow(every: 1m, fn: mean, createEmpty: false)
    15. |> yield(name: "mean")
    16. ''');
    17. var count = 0;
    18. await recordStream.forEach((record) {
    19. print(
    20. 'record: ${count++} ${record['_time']}: ${record['host']} ${record['cpu']} ${record['_value']}');
    21. });
    22. client.close();
    23. }

    Dart - 图23Query to String

    1. import 'package:influxdb_client/api.dart';
    2. main() async {
    3. var client = InfluxDBClient(url: 'http://localhost:8086',
    4. token: 'my-token', org: 'my-org', bucket: 'my-bucket');
    5. var queryService = client.getQueryService(client);
    6. var rawCSV = await queryService.queryRaw('''
    7. from(bucket: "my-bucket")
    8. |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
    9. |> filter(fn: (r) => r["_measurement"] == "h2o")
    10. |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)
    11. |> yield(name: "mean")''');
    12. print(rawCSV);
    13. }

    Parameterized queries

    InfluxDB Cloud supports 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. import 'package:influxdb_client/api.dart';
    2. void main() async {
    3. var client = InfluxDBClient(
    4. url: 'http://localhost:8086',
    5. token: 'my-token',
    6. org: 'my-org',
    7. );
    8. var queryService = client.getQueryService();
    9. var queryService = client.getQueryService();
    10. var queryString = '''
    11. from(bucket: params.bucketParam)
    12. |> range(start: duration(v: params.startParam))
    13. |> filter(fn: (r) => r["_measurement"] == "weather"
    14. and r["location"] == "Prague")''';
    15. var queryParams = {'bucketParam':'my-bucket', 'startParam':'-10d'};
    16. var query = Query(query: queryString, params: queryParams);
    17. // Using string for query and Map for params
    18. var recordMap = await queryService.query(queryString, params: queryParams);
    19. // Using Query class
    20. client.close();
    21. }

    The supports deletes points from an InfluxDB bucket.

    InfluxDB uses an InfluxQL-like syntax to determine what data points to delete.

    1. import 'package:influxdb_client/api.dart';
    2. void main() async {
    3. var client = InfluxDBClient(
    4. url: 'http://localhost:8086',
    5. token: 'my-token',
    6. org: 'my-org',
    7. bucket: 'my-bucket',
    8. debugEnabled: true);
    9. await client
    10. .getDeleteService()
    11. .delete(
    12. predicate: '_measurement="temperature"',
    13. start: '1970-01-01T00:00:00.000000001Z',
    14. stop: DateTime.now().toUtc().toIso8601String(),
    15. bucket: 'my-bucket',
    16. org: 'my-org')
    17. .catchError((e) => print(e));
    18. var queryService = client.getQueryService();
    19. var fluxQuery = '''
    20. from(bucket: "my-bucket")
    21. |> range(start: -1d)
    22. |> filter(fn: (r) => r["_measurement"] == "temperature")
    23. ''';
    24. // should be empty
    25. var records = await queryService.query(fluxQuery);
    26. assert(await records.isEmpty);
    27. client.close();
    28. }

    Management API

    The client supports following management API:

    The client supports following management API:

    By default the HttpClient uses the proxy configuration available from the environment, see findProxyFromEnvironment.

    1. export http_proxy="PROXY http://localhost:8080"

    Initialize a proxy from code:

    1. HttpClient httpClient = HttpClient();
    2. httpClient.findProxy = (url) => "PROXY localhost:8080";
    3. var client = IOClient(httpClient);
    4. var influxdb = InfluxDBClient(
    5. url: 'http://localhost:8086',
    6. token: 'my-token',
    7. org: 'my-org',
    8. bucket: 'my-bucket',
    9. client: client,
    10. followRedirects: true,
    11. maxRedirects: 5,
    12. debug: true);

    To turn off the use of proxies set the findProxy property to null.

    Client HTTP redirects for all GET and HEAD requests with status codes 301, 302, 303, 307, 308. The default redirect policy is to follow up to 5 consecutive requests.

    write and query APIs also support an automatic redirect of POST requests. You can disable followRedirects and change default maxRedirects on InfluxDBClient instance.

    Contributing

    If you would like to contribute code you can do through GitHub by forking the repository and sending a pull request into the master branch.

    Build Requirements:

    • dart 2.X

    Build source and test targets:

    1. ./scripts/influxdb-restart.sh
    2. dart test

    Check code coverage:

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