![]() |
VOOZH | about |
dotnet add package InfluxDB.Client --version 5.1.0
NuGet\Install-Package InfluxDB.Client -Version 5.1.0
<PackageReference Include="InfluxDB.Client" Version="5.1.0" />
<PackageVersion Include="InfluxDB.Client" Version="5.1.0" />Directory.Packages.props
<PackageReference Include="InfluxDB.Client" />Project file
paket add InfluxDB.Client --version 5.1.0
#r "nuget: InfluxDB.Client, 5.1.0"
#:package InfluxDB.Client@5.1.0
#addin nuget:?package=InfluxDB.Client&version=5.1.0Install as a Cake Addin
#tool nuget:?package=InfluxDB.Client&version=5.1.0Install as a Cake Tool
The reference client that allows query, write and management (bucket, organization, users) for the InfluxDB 2.x.
This section contains links to the client library documentation.
For querying data we use QueryApi that allow perform asynchronous, streaming, synchronous and also use raw query response.
The asynchronous query is not intended for large query results because the Flux response can be potentially unbound.
using System;
using System.Threading.Tasks;
using InfluxDB.Client;
namespace Examples
{
public static class AsynchronousQuery
{
private static readonly string Token = "";
public static async Task Main()
{
using var client = new InfluxDBClient("http://localhost:8086", Token);
var flux = "from(bucket:\"temperature-sensors\") |> range(start: 0)";
var queryApi = client.GetQueryApi();
//
// QueryData
//
var tables = await queryApi.QueryAsync(flux, "org_id");
tables.ForEach(table =>
{
table.Records.ForEach(record =>
{
Console.WriteLine($"{record.GetTime()}: {record.GetValueByKey("_value")}");
});
});
}
}
}
The asynchronous query offers a possibility map FluxRecords to POCO:
using System;
using System.Threading.Tasks;
using InfluxDB.Client;
using InfluxDB.Client.Core;
namespace Examples
{
public static class AsynchronousQuery
{
private static readonly string Token = "";
public static async Task Main()
{
using var client = new InfluxDBClient("http://localhost:8086", Token);
var flux = "from(bucket:\"temperature-sensors\") |> range(start: 0)";
var queryApi = client.GetQueryApi();
//
// QueryData
//
var temperatures = await queryApi.QueryAsync<Temperature>(flux, "org_id");
temperatures.ForEach(temperature =>
{
Console.WriteLine($"{temperature.Location}: {temperature.Value} at {temperature.Time}");
});
}
[Measurement("temperature")]
private class Temperature
{
[Column("location", IsTag = true)] public string Location { get; set; }
[Column("value")] public double Value { get; set; }
[Column(IsTimestamp = true)] public DateTime Time { get; set; }
}
}
}
The Streaming query offers possibility to process unbound query and allow user to handle exceptions, stop receiving more results and notify that all data arrived.
using System;
using System.Threading.Tasks;
using InfluxDB.Client;
namespace Examples
{
public static class StreamingQuery
{
private static readonly string Token = "";
public static async Task Main()
{
using var client = new InfluxDBClient("http://localhost:8086", Token);
var flux = "from(bucket:\"temperature-sensors\") |> range(start: 0)";
var queryApi = client.GetQueryApi();
//
// QueryData
//
await queryApi.QueryAsync(flux, record =>
{
//
// The callback to consume a FluxRecord.
//
Console.WriteLine($"{record.GetTime()}: {record.GetValueByKey("_value")}");
}, exception =>
{
//
// The callback to consume any error notification.
//
Console.WriteLine($"Error occurred: {exception.Message}");
}, () =>
{
//
// The callback to consume a notification about successfully end of stream.
//
Console.WriteLine("Query completed");
}, "org_id");
}
}
}
And there is also a possibility map FluxRecords to POCO:
using System;
using System.Threading.Tasks;
using InfluxDB.Client;
using InfluxDB.Client.Core;
namespace Examples
{
public static class StreamingQuery
{
private static readonly string Token = "";
public static async Task Main()
{
using var client = new InfluxDBClient("http://localhost:8086", Token);
var flux = "from(bucket:\"temperature-sensors\") |> range(start: 0)";
var queryApi = client.GetQueryApi();
//
// QueryData
//
await queryApi.QueryAsync<Temperature>(flux, temperature =>
{
//
// The callback to consume a FluxRecord mapped to POCO.
//
Console.WriteLine($"{temperature.Location}: {temperature.Value} at {temperature.Time}");
}, org: "org_id");
}
[Measurement("temperature")]
private class Temperature
{
[Column("location", IsTag = true)] public string Location { get; set; }
[Column("value")] public double Value { get; set; }
[Column(IsTimestamp = true)] public DateTime Time { get; set; }
}
}
}
The Raw query allows direct processing original CSV response:
using System;
using System.Threading.Tasks;
using InfluxDB.Client;
namespace Examples
{
public static class RawQuery
{
private static readonly string Token = "";
public static async Task Main()
{
using var client = new InfluxDBClient("http://localhost:8086", Token);
var flux = "from(bucket:\"temperature-sensors\") |> range(start: 0)";
var queryApi = client.GetQueryApi();
//
// QueryData
//
var csv = await queryApi.QueryRawAsync(flux, org: "org_id");
Console.WriteLine($"CSV response: {csv}");
}
}
}
The Streaming version allows processing line by line:
using System;
using System.Threading.Tasks;
using InfluxDB.Client;
namespace Examples
{
public static class RawQueryAsynchronous
{
private static readonly string Token = "";
public static async Task Main()
{
using var client = new InfluxDBClient("http://localhost:8086", Token);
var flux = "from(bucket:\"temperature-sensors\") |> range(start: 0)";
var queryApi = client.GetQueryApi();
//
// QueryData
//
await queryApi.QueryRawAsync(flux, line =>
{
//
// The callback to consume a line of CSV response
//
Console.WriteLine($"Response: {line}");
}, org: "org_id");
}
}
}
The synchronous query is not intended for large query results because the response can be potentially unbound.
using System;
using InfluxDB.Client;
namespace Examples
{
public static class SynchronousQuery
{
public static void Main()
{
using var client = new InfluxDBClient("http://localhost:9999", "my-token");
const string query = "from(bucket:\"my-bucket\") |> range(start: 0)";
//
// QueryData
//
var queryApi = client.GetQueryApiSync();
var tables = queryApi.QuerySync(query, "my-org");
//
// Process results
//
tables.ForEach(table =>
{
table.Records.ForEach(record =>
{
Console.WriteLine($"{record.GetTime()}: {record.GetValueByKey("_value")}");
});
});
}
}
}
For writing data we use WriteApi or WriteApiAsync which is simplified version of WriteApi without batching support.
WriteApi supports:
WriteSuccessEvent - published when arrived the success response from serverWriteErrorEvent - published when occurs a unhandled exception from serverWriteRetriableErrorEvent - published when occurs a retriable error from serverWriteRuntimeExceptionEvent - published when occurs a runtime exception in background batch processingThe writes are processed in batches which are configurable by WriteOptions:
| Property | Description | Default Value |
|---|---|---|
| BatchSize | the number of data point to collect in batch | 1000 |
| FlushInterval | the number of milliseconds before the batch is written | 1000 |
| JitterInterval | the number of milliseconds to increase the batch flush interval by a random amount | 0 |
| RetryInterval | the number of milliseconds to retry unsuccessful write. The retry interval is used when the InfluxDB server does not specify "Retry-After" header. | 5000 |
| MaxRetries | the number of max retries when write fails | 3 |
| MaxRetryDelay | the maximum delay between each retry attempt in milliseconds | 125_000 |
| ExponentialBase | the base for the exponential retry delay, the next delay is computed using random exponential backoff as a random value within the interval retryInterval * exponentialBase^(attempts-1) and retryInterval * exponentialBase^(attempts). Example for retryInterval=5_000, exponentialBase=2, maxRetryDelay=125_000, maxRetries=5 Retry delays are random distributed values within the ranges of [5_000-10_000, 10_000-20_000, 20_000-40_000, 40_000-80_000, 80_000-125_000] |
2 |
Write Measurement into specified bucket:
using System;
using InfluxDB.Client;
using InfluxDB.Client.Api.Domain;
using InfluxDB.Client.Core;
namespace Examples
{
public static class WritePoco
{
private static readonly string Token = "";
public static void Main()
{
using var client = new InfluxDBClient("http://localhost:8086", Token);
//
// Write Data
//
using (var writeApi = client.GetWriteApi())
{
//
// Write by POCO
//
var temperature = new Temperature {Location = "south", Value = 62D, Time = DateTime.UtcNow};
writeApi.WriteMeasurement(temperature, WritePrecision.Ns, "bucket_name", "org_id");
}
}
[Measurement("temperature")]
private class Temperature
{
[Column("location", IsTag = true)] public string Location { get; set; }
[Column("value")] public double Value { get; set; }
[Column(IsTimestamp = true)] public DateTime Time { get; set; }
}
}
}
Write Data point into specified bucket:
using System;
using InfluxDB.Client;
using InfluxDB.Client.Api.Domain;
using InfluxDB.Client.Writes;
namespace Examples
{
public static class WriteDataPoint
{
private static readonly string Token = "";
public static void Main()
{
using var client = new InfluxDBClient("http://localhost:8086", Token);
//
// Write Data
//
using (var writeApi = client.GetWriteApi())
{
//
// Write by Data Point
var point = PointData.Measurement("temperature")
.Tag("location", "west")
.Field("value", 55D)
.Timestamp(DateTime.UtcNow.AddSeconds(-10), WritePrecision.Ns);
writeApi.WritePoint(point, "bucket_name", "org_id");
}
}
}
}
DataPoint Builder Immutability: The builder is immutable therefore won't have side effect when using for building multiple point with single builder.
using System;
using InfluxDB.Client;
using InfluxDB.Client.Api.Domain;
using InfluxDB.Client.Writes;
namespace Examples
{
public static class WriteDataPoint
{
private static readonly string Token = "";
public static void Main()
{
using var client = new InfluxDBClient("http://localhost:8086", Token);
//
// Write Data
//
using (var writeApi = client.GetWriteApi())
{
//
// Write by Data Point
var builder = PointData.Measurement("temperature")
.Tag("location", "west");
var pointA = builder
.Field("value", 55D)
.Timestamp(DateTime.UtcNow.AddSeconds(-10), WritePrecision.Ns);
writeApi.WritePoint(pointA, "bucket_name", "org_id");
var pointB = builder
.Field("age", 32)
.Timestamp(DateTime.UtcNow, WritePrecision.Ns);
writeApi.WritePoint(pointB, "bucket_name", "org_id");
}
}
}
}
Write Line Protocol record into specified bucket:
using InfluxDB.Client;
using InfluxDB.Client.Api.Domain;
namespace Examples
{
public static class WriteLineProtocol
{
private static readonly string Token = "";
public static void Main()
{
using var client = new InfluxDBClient("http://localhost:8086", Token);
//
// Write Data
//
using (var writeApi = client.GetWriteApi())
{
//
//
// Write by LineProtocol
//
writeApi.WriteRecord("temperature,location=north value=60.0", WritePrecision.Ns,"bucket_name", "org_id");
}
}
}
}
using System;
using System.Threading.Tasks;
using InfluxDB.Client;
using InfluxDB.Client.Api.Domain;
using InfluxDB.Client.Core;
using InfluxDB.Client.Writes;
namespace Examples
{
public static class WriteApiAsyncExample
{
[Measurement("temperature")]
private class Temperature
{
[Column("location", IsTag = true)] public string Location { get; set; }
[Column("value")] public double Value { get; set; }
[Column(IsTimestamp = true)] public DateTime Time { get; set; }
}
public static async Task Main()
{
using var client = new InfluxDBClient("http://localhost:8086",
"my-user", "my-password");
//
// Write Data
//
var writeApiAsync = client.GetWriteApiAsync();
//
//
// Write by LineProtocol
//
await writeApiAsync.WriteRecordAsync("temperature,location=north value=60.0", WritePrecision.Ns,
"my-bucket", "my-org");
//
//
// Write by Data Point
//
var point = PointData.Measurement("temperature")
.Tag("location", "west")
.Field("value", 55D)
.Timestamp(DateTime.UtcNow.AddSeconds(-10), WritePrecision.Ns);
await writeApiAsync.WritePointAsync(point, "my-bucket", "my-org");
//
// Write by POCO
//
var temperature = new Temperature {Location = "south", Value = 62D, Time = DateTime.UtcNow};
await writeApiAsync.WriteMeasurementAsync(temperature, WritePrecision.Ns, "my-bucket", "my-org");
//
// Check written data
//
var tables = await influxDbClient.GetQueryApi()
.QueryAsync("from(bucket:\"my-bucket\") |> range(start: 0)", "my-org");
tables.ForEach(table =>
{
var fluxRecords = table.Records;
fluxRecords.ForEach(record =>
{
Console.WriteLine($"{record.GetTime()}: {record.GetValue()}");
});
});
}
}
}
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${version} - application settings${env.hostname} - environment propertyIn a configuration file you are able to specify default tags by tags element.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="influx2" type="InfluxDB.Client.Configurations.Influx2, InfluxDB.Client" />
</configSections>
<appSettings>
<add key="SensorVersion" value="v1.00"/>
</appSettings>
<influx2 url="http://localhost:8086"
org="my-org"
bucket="my-bucket"
token="my-token"
logLevel="BODY"
timeout="10s">
<tags>
<tag name="id" value="132-987-655"/>
<tag name="customer" value="California Miner"/>
<tag name="hostname" value="${env.Hostname}"/>
<tag name="sensor-version" value="${SensorVersion}"/>
</tags>
</influx2>
</configuration>
var options = new InfluxDBClientOptions(Url)
{
Token = token,
DefaultTags = new Dictionary<string, string>
{
{"id", "132-987-655"},
{"customer", "California Miner"},
}
};
options.AddDefaultTag("hostname", "${env.Hostname}")
options.AddDefaultTags(new Dictionary<string, string>{{ "sensor-version", "${SensorVersion}" }})
Both of configurations will produce the Line protocol:
mine-sensor,id=132-987-655,customer="California Miner",hostname=example.com,sensor-version=v1.00 altitude=10
Events that can be handle by WriteAPI EventHandler are:
WriteSuccessEvent - for success response from serverWriteErrorEvent - for unhandled exception from serverWriteRetriableErrorEvent - for retriable error from serverWriteRuntimeExceptionEvent - for runtime exception in background batch processingNumber of events depends on number of data points to collect in batch. The batch size is configured by BatchSize option (default size is 1000) - in case
of one data point, event is handled for each point, independently on used writing method (even for mass writing of data like
WriteMeasurements, WritePoints and WriteRecords).
Events can be handled by register writeApi.EventHandler or by creating custom EventListener:
writeApi.EventHandler += (sender, eventArgs) =>
{
switch (eventArgs)
{
case WriteSuccessEvent successEvent:
string data = @event.LineProtocol;
//
// handle success response from server
// Console.WriteLine($"{data}");
//
break;
case WriteErrorEvent error:
string data = @error.LineProtocol;
string errorMessage = @error.Exception.Message;
//
// handle unhandled exception from server
//
// Console.WriteLine($"{data}");
// throw new Exception(errorMessage);
//
break;
case WriteRetriableErrorEvent error:
string data = @error.LineProtocol;
string errorMessage = @error.Exception.Message;
//
// handle retrievable error from server
//
// Console.WriteLine($"{data}");
// throw new Exception(errorMessage);
//
break;
case WriteRuntimeExceptionEvent error:
string errorMessage = @error.Exception.Message;
//
// handle runtime exception in background batch processing
// throw new Exception(errorMessage);
//
break;
}
};
//
// Write by LineProtocol
//
writeApi.WriteRecord("influxPoint,writeType=lineProtocol value=11.11" +
$" {DateTime.UtcNow.Subtract(EpochStart).Ticks * 100}", WritePrecision.Ns, "my-bucket", "my-org");
Advantage of using custom Event Listener is possibility of waiting on handled event between different writings - for more info see .
Delete data from specified bucket:
using InfluxDB.Client;
using InfluxDB.Client.Api.Domain;
namespace Examples
{
public static class WriteLineProtocol
{
private static readonly string Token = "";
public static void Main()
{
using var client = new InfluxDBClient("http://localhost:8086", Token);
//
// Delete data
//
await client.GetDeleteApi().Delete(DateTime.UtcNow.AddMinutes(-1), DateTime.Now, "", "bucket", "org");
}
}
}
You can filter out verbose messages from InfluxDB.Client by using TraceListener.
using System;
using System.Diagnostics;
using InfluxDB.Client.Core;
namespace Examples
{
public static class MyProgram
{
public static void Main()
{
TraceListener ConsoleOutListener = new TextWriterTraceListener(Console.Out)
{
Filter = InfluxDBTraceFilter.SuppressInfluxVerbose(),
};
Trace.Listeners.Add(ConsoleOutListener);
// My code ...
}
}
}
The client has following management API:
| API endpoint | Description | Implementation |
|---|---|---|
| /api/v2/authorizations | Managing authorization data | AuthorizationsApi |
| /api/v2/buckets | Managing bucket data | BucketsApi |
| /api/v2/orgs | Managing organization data | OrganizationsApi |
| /api/v2/users | Managing user data | UsersApi |
| /api/v2/sources | Managing sources | SourcesApi |
| /api/v2/tasks | Managing one-off and recurring tasks | TasksApi |
| /api/v2/scrapers | Managing ScraperTarget data | ScraperTargetsApi |
| /api/v2/labels | Managing resource labels | LabelsApi |
| /api/v2/telegrafs | Managing telegraf config data | TelegrafsApi |
| /api/v2/setup | Managing onboarding setup | InfluxDBClient#OnBoarding() |
| /ready | Get the readiness of a instance at startup | InfluxDBClient#Ready() |
| /health | Get the health of an instance anytime during execution | InfluxDBClient#Health() |
The following example demonstrates how to use a InfluxDB 2.x Management API. For further information see endpoints implementation.
using System;
using System.Collections.Generic;
using System.Linq;
using InfluxDB.Client;
using InfluxDB.Client.Api.Domain;
using Task = System.Threading.Tasks.Task;
namespace Examples
{
public static class ManagementExample
{
public static async Task Main()
{
const string url = "http://localhost:8086";
const string token = "my-token";
const string org = "my-org";
using var client = new InfluxDBClient(url, token);
// Find ID of Organization with specified name (PermissionAPI requires ID of Organization).
var orgId = (await client.GetOrganizationsApi().FindOrganizationsAsync(org: org)).First().Id;
//
// Create bucket "iot_bucket" with data retention set to 3,600 seconds
//
var retention = new BucketRetentionRules(BucketRetentionRules.TypeEnum.Expire, 3600);
var bucket = await client.GetBucketsApi().CreateBucketAsync("iot_bucket", retention, orgId);
//
// Create access token to "iot_bucket"
//
var resource = new PermissionResource(PermissionResource.TypeBuckets, bucket.Id, null,
orgId);
// Read permission
var read = new Permission(Permission.ActionEnum.Read, resource);
// Write permission
var write = new Permission(Permission.ActionEnum.Write, resource);
var authorization = await client.GetAuthorizationsApi()
.CreateAuthorizationAsync(orgId, new List<Permission> { read, write });
//
// Created token that can be use for writes to "iot_bucket"
//
Console.WriteLine($"Authorized token to write into iot_bucket: {authorization.Token}");
}
}
}
If there is no API implementation for particular service you could create the service by:
var dbrpService = _client.CreateService<DBRPsService>(typeof(DBRPsService));
The example below show how to create a check for monitoring a stock price. A Slack notification is created if the price is lesser than 35.
The Check set status to Critical if the current value for a stock measurement is lesser than 35.
var org = ...;
var query = "from(bucket: \"my-bucket\") "
+ "|> range(start: v.timeRangeStart, stop: v.timeRangeStop) "
+ "|> filter(fn: (r) => r._measurement == \"stock\") "
+ "|> filter(fn: (r) => r.company == \"zyz\") "
+ "|> aggregateWindow(every: 5s, fn: mean) "
+ "|> filter(fn: (r) => r._field == \"current\") "
+ "|> yield(name: \"mean\")";
var threshold = new LesserThreshold(value: 35F, level: CheckStatusLevel.CRIT,
type: LesserThreshold.TypeEnum.Lesser);
var message = "The Stock price for XYZ is on: ${ r._level } level!";
await Client
.GetChecksApi()
.CreateThresholdCheckAsync("XYZ Stock value", query, "5s", message, threshold, org.Id);
var url = "https://hooks.slack.com/services/x/y/z";
var endpoint = await Client
.GetNotificationEndpointsApi()
.CreateSlackEndpointAsync("Slack Endpoint", url, org.Id);
await Client
.GetNotificationRulesApi()
.CreateSlackRuleAsync("Critical status to Slack", "10s", "${ r._message }", RuleStatusLevel.CRIT, endpoint, org.Id);
The uses Column attributes to define how the DomainObject will be mapped to and from the InfluxDB.
The our APIs also allow to specify custom mapper. For more information see following example:
using System;
using System.Threading.Tasks;
using InfluxDB.Client;
using InfluxDB.Client.Api.Domain;
using InfluxDB.Client.Core.Flux.Domain;
using InfluxDB.Client.Writes;
namespace Examples
{
public static class CustomDomainMapping
{
/// <summary>
/// Define Domain Object
/// </summary>
private class Sensor
{
/// <summary>
/// Type of sensor.
/// </summary>
public String Type { get; set; }
/// <summary>
/// Version of sensor.
/// </summary>
public String Version { get; set; }
/// <summary>
/// Measured value.
/// </summary>
public double Value { get; set; }
public DateTimeOffset Timestamp { get; set; }
public override string ToString()
{
return $"{Timestamp:MM/dd/yyyy hh:mm:ss.fff tt} {Type}, {Version} value: {Value}";
}
}
/// <summary>
/// Define Custom Domain Object Converter
/// </summary>
private class DomainEntityConverter : IDomainObjectMapper
{
/// <summary>
/// Convert to DomainObject.
/// </summary>
public object ConvertToEntity(FluxRecord fluxRecord, Type type)
{
if (type != typeof(Sensor))
{
throw new NotSupportedException($"This converter doesn't supports: {type}");
}
var customEntity = new Sensor
{
Type = Convert.ToString(fluxRecord.GetValueByKey("type")),
Version = Convert.ToString(fluxRecord.GetValueByKey("version")),
Value = Convert.ToDouble(fluxRecord.GetValueByKey("data")),
Timestamp = fluxRecord.GetTime().GetValueOrDefault().ToDateTimeUtc(),
};
return Convert.ChangeType(customEntity, type);
}
/// <summary>
/// Convert to DomainObject.
/// </summary>
public T ConvertToEntity<T>(FluxRecord fluxRecord)
{
return (T)ConvertToEntity(fluxRecord, typeof(T));
}
/// <summary>
/// Convert to Point
/// </summary>
public PointData ConvertToPointData<T>(T entity, WritePrecision precision)
{
if (!(entity is Sensor sensor))
{
throw new NotSupportedException($"This converter doesn't supports: {entity}");
}
var point = PointData
.Measurement("sensor")
.Tag("type", sensor.Type)
.Tag("version", sensor.Version)
.Field("data", sensor.Value)
.Timestamp(sensor.Timestamp, precision);
return point;
}
}
public static async Task Main(string[] args)
{
const string host = "http://localhost:9999";
const string token = "my-token";
const string bucket = "my-bucket";
const string organization = "my-org";
var options = new InfluxDBClientOptions(host)
{
Token = token,
Org = organization,
Bucket = bucket
};
var converter = new DomainEntityConverter();
using var client = new InfluxDBClient(options);
//
// Prepare data to write
//
var time = new DateTimeOffset(2020, 11, 15, 8, 20, 15,
new TimeSpan(3, 0, 0));
var entity1 = new Sensor
{
Timestamp = time,
Type = "temperature",
Version = "v0.0.2",
Value = 15
};
var entity2 = new Sensor
{
Timestamp = time.AddHours(1),
Type = "temperature",
Version = "v0.0.2",
Value = 15
};
var entity3 = new Sensor
{
Timestamp = time.AddHours(2),
Type = "humidity",
Version = "v0.13",
Value = 74
};
var entity4 = new Sensor
{
Timestamp = time.AddHours(3),
Type = "humidity",
Version = "v0.13",
Value = 82
};
//
// Write data
//
await client.GetWriteApiAsync(converter)
.WriteMeasurementsAsync(new []{entity1, entity2, entity3, entity4}, WritePrecision.S);
//
// Query Data to Domain object
//
var queryApi = client.GetQueryApiSync(converter);
//
// Select ALL
//
var query = $"from(bucket:\"{bucket}\") " +
"|> range(start: 0) " +
"|> filter(fn: (r) => r[\"_measurement\"] == \"sensor\")" +
"|> pivot(rowKey:[\"_time\"], columnKey: [\"_field\"], valueColumn: \"_value\")";
var sensors = queryApi.QuerySync<Sensor>(query);
//
// Print result
//
sensors.ForEach(it => Console.WriteLine(it.ToString()));
}
}
}
A client can be configured via App.config file.
The following options are supported:
| Property name | default | description |
|---|---|---|
| Url | - | the url to connect to InfluxDB |
| Org | - | default destination organization for writes and queries |
| Bucket | - | default destination bucket for writes |
| Token | - | the token to use for the authorization |
| LogLevel | NONE | rest client verbosity level |
| Timeout | 10000 ms | The timespan to wait before the HTTP request times out |
| AllowHttpRedirects | false | Configure automatically following HTTP 3xx redirects |
| VerifySsl | true | Ignore Certificate Validation Errors when false |
The Timeout supports ms, s and m as unit. Default is milliseconds.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="influx2" type="InfluxDB.Client.Configurations.Influx2, InfluxDB.Client" />
</configSections>
<influx2 url="http://localhost:8086"
org="my-org"
bucket="my-bucket"
token="my-token"
logLevel="BODY"
timeout="10s">
</influx2>
</configuration>
and then:
var client = InfluxDBClientFactory.Create();
A client can be constructed using a connection string that can contain the InfluxDBClientOptions parameters encoded into the URL.
var client = new InfluxDBClient("http://localhost:8086?timeout=5000&logLevel=BASIC");
The following options are supported:
| Property name | default | description |
|---|---|---|
| org | - | default destination organization for writes and queries |
| bucket | - | default destination bucket for writes |
| token | - | the token to use for the authorization |
| logLevel | NONE | rest client verbosity level |
| timeout | 10000 ms | The timespan to wait before the HTTP request times out. |
| allowHttpRedirects | false | Configure automatically following HTTP 3xx redirects |
| verifySsl | true | Ignore Certificate Validation Errors when false |
The timeout supports ms, s and m as unit. Default is milliseconds.
InfluxDBClient does not enable gzip compress for http requests by default. If you want to enable gzip to reduce transfer data's size, you can call:
influxDBClient.EnableGzip();
You can configure the client to tunnel requests through an HTTP proxy. The WebProxy could be
configured via InfluxDBClientOptions parameter WebProxy:
var options = new InfluxDBClientOptions("http://localhost:8086")
{
Token = "my-token",
WebProxy = new WebProxy("http://proxyserver:80/", true)
};
var client = new InfluxDBClient(options);
Client automatically doesn't follows HTTP redirects. You can enable redirects by AllowRedirects configuration option:
var options = new InfluxDBClientOptions("http://localhost:8086")
{
Token = "my-token",
AllowRedirects = true
};
using var client = new InfluxDBClient(options);
⚠️ Due to a security reason
Authorizationheader is not forwarded when redirect leads to a different domain. You can create customAuthenticatorwhich change this behaviour - see more.
The Requests and Responses can be logged by changing the LogLevel. LogLevel values are None, Basic, Headers, Body. Note that
applying the Body LogLevel will disable chunking while streaming and will load the whole response into memory.
client.SetLogLevel(LogLevel.Body)
Server availability can be checked using the influxDBClient.PingAsync() endpoint.
The latest package for .NET CLI:
dotnet add package InfluxDB.Client
Or when using with Package Manager:
Install-Package InfluxDB.Client
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 net5.0 was computed. net5.0-windows net5.0-windows was computed. net6.0 net6.0 was computed. net6.0-android net6.0-android was computed. net6.0-ios net6.0-ios was computed. net6.0-maccatalyst net6.0-maccatalyst was computed. net6.0-macos net6.0-macos was computed. net6.0-tvos net6.0-tvos was computed. net6.0-windows net6.0-windows was computed. net7.0 net7.0 was computed. net7.0-android net7.0-android was computed. net7.0-ios net7.0-ios was computed. net7.0-maccatalyst net7.0-maccatalyst was computed. net7.0-macos net7.0-macos was computed. net7.0-tvos net7.0-tvos was computed. net7.0-windows net7.0-windows was computed. net8.0 net8.0 was computed. net8.0-android net8.0-android was computed. net8.0-browser net8.0-browser was computed. net8.0-ios net8.0-ios was computed. net8.0-maccatalyst net8.0-maccatalyst was computed. net8.0-macos net8.0-macos was computed. net8.0-tvos net8.0-tvos was computed. net8.0-windows net8.0-windows was computed. net9.0 net9.0 was computed. net9.0-android net9.0-android was computed. net9.0-browser net9.0-browser was computed. net9.0-ios net9.0-ios was computed. net9.0-maccatalyst net9.0-maccatalyst was computed. net9.0-macos net9.0-macos was computed. net9.0-tvos net9.0-tvos was computed. net9.0-windows net9.0-windows was computed. net10.0 net10.0 was computed. net10.0-android net10.0-android was computed. net10.0-browser net10.0-browser was computed. net10.0-ios net10.0-ios was computed. net10.0-maccatalyst net10.0-maccatalyst was computed. net10.0-macos net10.0-macos was computed. net10.0-tvos net10.0-tvos was computed. net10.0-windows net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 netcoreapp2.0 was computed. netcoreapp2.1 netcoreapp2.1 was computed. netcoreapp2.2 netcoreapp2.2 was computed. netcoreapp3.0 netcoreapp3.0 was computed. netcoreapp3.1 netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 netstandard2.0 is compatible. netstandard2.1 netstandard2.1 is compatible. |
| .NET Framework | net461 net461 was computed. net462 net462 was computed. net463 net463 was computed. net47 net47 was computed. net471 net471 was computed. net472 net472 was computed. net48 net48 was computed. net481 net481 was computed. |
| MonoAndroid | monoandroid monoandroid was computed. |
| MonoMac | monomac monomac was computed. |
| MonoTouch | monotouch monotouch was computed. |
| Tizen | tizen40 tizen40 was computed. tizen60 tizen60 was computed. |
| Xamarin.iOS | xamarinios xamarinios was computed. |
| Xamarin.Mac | xamarinmac xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos xamarinwatchos was computed. |
Showing the top 5 NuGet packages that depend on InfluxDB.Client:
| Package | Downloads |
|---|---|
|
InfluxDB.Client.Linq
The library supports querying InfluxDB 2.x by LINQ expressions. |
|
|
NBomber.Sinks.InfluxDB
NBomber sink that writes stats data to InfluxDB. |
|
|
OpenTelemetry.Exporter.InfluxDB
An OpenTelemetry .NET exporter that exports to InfluxDB. |
|
|
Serilog.Sinks.InfluxDB.Syslog
InfluxDB sink for Serilog with .NET standard 2.0 using syslog format for Influx 2.X |
|
|
AspNetCore.HealthChecks.InfluxDB
HealthChecks.InfluxDB is the health check package for InfluxDB. |
Showing the top 11 popular GitHub repositories that depend on InfluxDB.Client:
| Repository | Stars |
|---|---|
|
Xabaril/AspNetCore.Diagnostics.HealthChecks
Enterprise HealthChecks for ASP.NET Core Diagnostics Package
|
|
|
testcontainers/testcontainers-dotnet
A library to support tests with throwaway instances of Docker containers for all compatible .NET Standard versions.
|
|
|
IoTSharp/IoTSharp
IoTSharp is an open-source IoT platform for data collection, processing, visualization, and device management.
|
|
|
dotnet/dotnet
Home of .NET's Virtual Monolithic Repository which includes all the code needed to build the .NET SDK.
|
|
|
Ozark-Connect/NetworkOptimizer
Self-hosted optimization, monitoring, and security audit tool for UniFi Networks. Includes Wi-Fi Optimizer for wireless health scoring and channel optimization, advanced DNS/VLAN/firewall security checks, config optimization suggestions, centralized WAN and LAN speed test server w/ L2 tracing, ONT, SFP, UniFi 5G modem stats, and more.
|
|
|
open-telemetry/opentelemetry-dotnet-contrib
This repository contains set of components extending functionality of the OpenTelemetry .NET SDK. Instrumentation libraries, exporters, and other components can find their home here.
|
|
|
ConcreteMC/Alex
A Minecraft client written in C# aimed at compatibility with MC:Java & MC:Bedrock
|
|
|
nickbabcock/OhmGraphite
Expose hardware sensor data to Graphite / InfluxDB / Prometheus / Postgres / Timescaledb
|
|
|
RapidScada/scada-v6
Contains Rapid SCADA 6 source code.
|
|
|
dotnetcore/mocha
Mocha is an application performance monitor tools based on OpenTelemetry, which also provides a scalable platform for observability data analysis and storage.
|
|
|
Ladder99/fanuc-driver
Configurable Fanuc Focas data collector and post processor.
|
| Version | Downloads | Last Updated |
|---|---|---|
| 5.2.0-dev.18128 | 61 | 6/10/2026 |
| 5.1.0 | 3,789 | 6/10/2026 |
| 5.1.0-dev.18117 | 50 | 6/9/2026 |
| 5.1.0-dev.17908 | 129 | 5/19/2026 |
| 5.1.0-dev.17889 | 61 | 5/19/2026 |
| 5.1.0-dev.17861 | 57 | 5/19/2026 |
| 5.1.0-dev.17824 | 62 | 5/19/2026 |
| 5.1.0-dev.17796 | 60 | 5/19/2026 |
| 5.1.0-dev.17768 | 71 | 5/19/2026 |
| 5.1.0-dev.17704 | 65 | 5/19/2026 |
| 5.1.0-dev.17614 | 121 | 5/11/2026 |
| 5.1.0-dev.17405 | 60 | 5/11/2026 |
| 5.1.0-dev.17386 | 65 | 5/11/2026 |
| 5.1.0-dev.17367 | 70 | 5/11/2026 |
| 5.1.0-dev.17312 | 67 | 5/11/2026 |
| 5.1.0-dev.17257 | 64 | 5/11/2026 |
| 5.1.0-dev.17202 | 64 | 5/11/2026 |
| 5.1.0-dev.17120 | 62 | 5/11/2026 |
| 5.1.0-dev.17101 | 62 | 5/11/2026 |
| 5.1.0-dev.16945 | 62 | 5/6/2026 |