MCPcopy Index your code
hub / github.com/aprimadi/influxdb2

github.com/aprimadi/influxdb2 @v0.5.2

Chat with this repo
repository ↗ · DeepWiki ↗ · release v0.5.2 ↗ · + Follow
357 symbols 596 edges 74 files 105 documented · 29%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

influxdb2

This is a Rust client to InfluxDB using the 2.0 API.

Setup

Add this to cargo.toml:

influxdb2 = "0.3"
influxdb2-structmap = "0.2"
influxdb2-derive = "0.1.1"
num-traits = "0.2"

Usage

Querying

use chrono::{DateTime, FixedOffset};
use influxdb2::{Client, FromDataPoint};
use influxdb2::models::Query;

#[derive(Debug, FromDataPoint)]
pub struct StockPrice {
    ticker: String,
    value: f64,
    time: DateTime<FixedOffset>,
}

impl Default for StockPrice {
    fn default() -> Self {
        Self {
            ticker: "".to_string(),
            value: 0_f64,
            time: chrono::MIN_DATETIME.with_timezone(&chrono::FixedOffset::east(7 * 3600)),
        }
    }
}

async fn example() -> Result<(), Box<dyn std::error::Error>> {
    let host = std::env::var("INFLUXDB_HOST").unwrap();
    let org = std::env::var("INFLUXDB_ORG").unwrap();
    let token = std::env::var("INFLUXDB_TOKEN").unwrap();
    let client = Client::new(host, org, token);

    let qs = format!("from(bucket: \"stock-prices\") 
        |> range(start: -1w)
        |> filter(fn: (r) => r.ticker == \"{}\") 
        |> last()
    ", "AAPL");
    let query = Query::new(qs.to_string());
    let res: Vec<StockPrice> = client.query::<StockPrice>(Some(query))
        .await?;
    println!("{:?}", res);

    Ok(())
}

Writing

#[derive(Default, WriteDataPoint)]
#[measurement = "cpu_load_short"]
struct CpuLoadShort {
    #[influxdb(tag)]
    host: Option<String>,
    #[influxdb(tag)]
    region: Option<String>,
    #[influxdb(field)]
    value: f64,
    #[influxdb(timestamp)]
    time: i64,
}

async fn example() -> Result<(), Box<dyn std::error::Error>> {
    use chrono::Utc;
    use futures::prelude::*;
    use influxdb2::models::DataPoint;
    use influxdb2::Client;
    use influxdb2_derive::WriteDataPoint;

    let host = std::env::var("INFLUXDB_HOST").unwrap();
    let org = std::env::var("INFLUXDB_ORG").unwrap();
    let token = std::env::var("INFLUXDB_TOKEN").unwrap();
    let bucket = std::env::var("INFLUXDB_BUCKET").unwrap();
    let client = Client::new(host, org, token);

    let points = vec![
        CpuLoadShort {
            host: Some("server01".to_owned()),
            region: Some("us-west".to_owned()),
            value: 0.64,
            time: Utc::now().timestamp_nanos(),
        },
        CpuLoadShort {
            host: Some("server02".to_owned()),
            region: None,
            value: 0.64,
            time: Utc::now().timestamp_nanos(),
        },
    ];

    client.write(bucket, stream::iter(points)).await?;

    Ok(())
}

Supported Data Types

InfluxDB data point doesn't support every data types supported by Rust. So, the derive macro only allows for a subset of data types which is also supported in InfluxDB.

Supported struct field types:

  • bool
  • f64
  • i64
  • u64 - DEPRECATED, will be removed in version 0.4
  • String
  • Vec
  • chrono::Duration
  • DateTime

Features

Implemented API

  • [x] Query API
  • [x] Write API
  • [x] Delete API
  • [ ] Bucket API (partial: only list, create, delete)
  • [ ] Organization API (partial: only list)
  • [ ] Task API (partial: only list, create, delete)

TLS Implementations

This crate uses reqwest under the hood. You can choose between native-tls and rustls with the features provided with this crate. native-tls is chosen as the default, like reqwest does.

# Usage for native-tls (the default).
influxdb2 = "0.3"

# Usage for rustls.
influxdb2 = { version = "0.3", features = ["rustls"], default-features = false }

Development Status

This project is still at alpha status and all the bugs haven't been ironed yet. With that said, use it at your own risk and feel free to create an issue or pull request.

Extension points exported contracts — how you extend this code

ValueWritable (Interface)
InfluxDB WritableValue trait This type normally descript the type which could be written as FieldValue. Currently u64, [8 …
src/writable.rs
WriteDataPoint (Interface)
Transform a type into valid line protocol lines This trait is to enable the conversion of `DataPoint`s to line protocol [1 …
src/models/data_point.rs
FromMap (Interface)
(no doc)
influxdb2-structmap/src/lib.rs
KeyWritable (Interface)
InfluxDB Key This type normally descript the type which could be written as TagKey, TagValue or FieldKey. Influx suppo [5 …
src/writable.rs
WriteMeasurement (Interface)
The following are traits rather than free functions so that we can limit their implementations to only the data types su [1 …
src/models/data_point.rs
ToMap (Interface)
(no doc)
influxdb2-structmap/src/lib.rs
TimestampWritable (Interface)
Any type wants to be a timestamp needs to implement this [2 implementers]
src/writable.rs
WriteTagKey (Interface)
(no doc) [1 implementers]
src/models/data_point.rs

Core symbols most depended-on inside this repo

request
called by 29
src/lib.rs
url
called by 29
src/lib.rs
assert_utf8_strings_eq
called by 13
src/models/data_point.rs
query
called by 10
src/api/query.rs
parse_value
called by 7
src/api/query.rs
field
called by 7
src/models/data_point.rs
tag
called by 6
src/models/data_point.rs
write
called by 5
src/api/write.rs

Shape

Method 134
Function 96
Class 88
Enum 25
Interface 14

Languages

Rust100%

Modules by API surface

src/models/data_point.rs40 symbols
src/api/query.rs36 symbols
src/writable.rs15 symbols
src/api/label.rs15 symbols
test_helpers/src/tracing.rs13 symbols
src/lib.rs13 symbols
tests/common/server_fixture.rs12 symbols
test_helpers/src/lib.rs10 symbols
src/models/query.rs10 symbols
src/api/write.rs10 symbols
influxdb2-structmap/src/value.rs10 symbols
src/api/setup.rs8 symbols

For agents

$ claude mcp add influxdb2 \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page