Categorygithub.com/InfluxCommunity/flux
modulepackage
0.195.1
Repository: https://github.com/influxcommunity/flux.git
Documentation: pkg.go.dev

# README

Flux - Community fork of Influx data language

Flux is a lightweight scripting language for querying databases (like InfluxDB) and working with data. It is part of InfluxDB 1.7 and 2.0, but can be run independently of those. This repository contains the language definition and an implementation of the language core.

Note: This is the community fork of Flux. The Flux version that is maintained by InfluxData lives here. If you are seeking to make changes to Flux for use in your own projects, this repo is the right place to be.

Specification

A complete specification can be found in SPEC.md. The specification contains many examples to start learning Flux.

Requirements

Building Flux requires the following:

  • Go 1.16 or greater with module support enabled
  • Latest stable version of Rust and Cargo (can be installed with rustup)
  • Clang

Getting Started

Flux is currently available in InfluxDB 1.7 and 2.0, or through the REPL that can be compiled from this repository.

To build Flux, first install the GNU pkg-config utility on your system, then ensure the pkg-config wrapper is also installed.

# First install GNU pkg-config.
# On Debian/Ubuntu
$ sudo apt-get install -y clang pkg-config

# Or on Mac OS X with Homebrew
$ brew install pkg-config

# Next, install the pkg-config wrapper utility
$ go get github.com/influxdata/pkg-config

# Optionally, add the GOBIN directory to your PATH
$ export PATH=${GOPATH}/bin:${PATH}

If GOBIN is in your PATH, ensure that pkg-config is configured correctly by using which -a.

$ which -a pkg-config
/home/user/go/bin/pkg-config
/usr/bin/pkg-config

To compile and use the REPL, use the following command to run the repl with suggestions enabled:

$ go build ./cmd/flux
$ ./flux --enable-suggestions

Alternatively, because the pkg-config wrapper may not work in all projects you may not want to add the wrapper pkg-config to your PATH. In this case you can set PKG_CONFIG and Go will use it. Eg, to build and install to ${GOPATH}/bin using PKG_CONFIG:

$ PKG_CONFIG=/home/user/go/bin/pkg-config go install ./cmd/flux
$ ${GOPATH}/bin/flux repl

From within the REPL, you can run any Flux expression. You can also load a file directly into the REPL by typing @ followed by the filename.

> @my_file_to_load.flux

Basic Syntax

Here are a few examples of the language to get an idea of the syntax.

// This line is a comment

// Support for traditional math operators
1 + 1

// Several data types are built-in
true                     // a boolean true value
1                        // an int
1.0                      // a float
"this is a string"       // a string literal
1h5m                     // a duration of time representing 1 hour and 5 minutes
2018-10-10               // a time starting at midnight for the default timezone on Oct 10th 2018
2018-10-10T10:05:00      // a time at 10:05 AM for the default timezone on Oct 10th 2018
[1,1,2]                  // an array of integers
{foo: "str", bar: false} // an object with two keys and their values

// Values can be assigned to identifiers
x = 5.0
x + 3.0 // 8.0

// Import libraries
import "math"

// Call functions always using keyword arguments
math.pow(x: 5.0, y: 3.0) // 5^3 = 125

// Functions are defined by assigning them to identifiers
add = (a, b) => a + b

// Call add using keyword arguments
add(a: 5, b: 3) // 8

// Functions are polymorphic
add(a: 5.5, b: 2.5) // 8.0

// And strongly typed
add(a: 5, b: 2.5) // type error

// Access data from a database and store it as an identifier
// This is only possible within the influxdb repl (at the moment).
import "influxdata/influxdb"
data = influxdb.from(bucket:"telegraf/autogen")

// When running inside of influxdb, the import isn't needed.
data = from(bucket:"telegraf/autogen")

// Chain more transformation functions to further specify the desired data
cpu = data
    // only get the last 5m of data
    |> range(start: -5m)
    // only get the "usage_user" data from the _measurement "cpu"
    |> filter(fn: (r) => r._measurement == "cpu" and r._field == "usage_user")

// Return the data to the client
cpu |> yield()

// Group an aggregate along different dimensions
cpu
    // organize data into groups by host and region
    |> group(columns:["host","region"])
    // compute the mean of each group
    |> mean()
    // yield this result to the client
    |> yield()

// Window an aggregate over time
cpu
    // organize data into groups of 1 minute
    // compute the mean of each group
    |> aggregateWindow(every: 1m, fn: mean)
    // yield this result to the client
    |> yield()

// Gather different data
mem = data
    // only get the last 5m of data
    |> range(start: -5m)
    // only get the "used_percent" data from the _measurement "mem"
    |> filter(fn: (r) => r._measurement == "mem" and r._field == "used_percent")


// Join data to create wider tables and map a function over the result
join(tables: {cpu:cpu, mem:mem}, on:["_time", "host"])
    // compute the ratio of cpu usage to mem used_percent
    |> map(fn:(r) => {_time: r._time, _value: r._value_cpu / r._value_mem)
    // again yield this result to the client
    |> yield()

The above examples give only a taste of what is possible with Flux. See the complete documentation for more complete examples and instructions for how to use Flux with InfluxDB 2.0.

Contributing

Flux welcomes contributions to the language and the runtime.

If you are interested in contributing, please read the contributing guide for more information.

Development basics

If you modify any Rust code, you will need to force Go to rebuild the library.

$ go generate ./libflux/go/libflux

If you create or change any Flux functions, you will need to rebuild the stdlib and inform Go that it must rebuild libflux:

$ go generate ./stdlib ./libflux/go/libflux

Your new Flux's code should be formatted to coexist nicely with the existing codebase with go fmt. For example, if you add code to stdlib/universe:

$ go fmt ./stdlib/universe/

Don't forget to add your tests and make sure they work. Here is an example showing how to run the tests for the stdlib/universe package:

$ go test ./stdlib/universe/

If you modify the flatbuffer files you need to run make generate to update the generated bindings. To ensure that you have the correct version of flatc you may use ./install_flatc.sh.

$ ./install_flatc.sh
$ make generate

# Packages

No description provided by the author
No description provided by the author
Package ast declares the types used to represent the syntax tree for Flux source code.
No description provided by the author
Package codes defines the error codes used by flux.
The compiler package provides a compiler and Go runtime for a subset of the Flux language.
Package complete provides types to aid with auto-completion of Flux scripts in editors.
Package csv contains the csv result encoders and decoders.
No description provided by the author
No description provided by the author
No description provided by the author
Package execute contains the implementation of the execution phase in the query engine.
Package fluxinit is used to initialize the flux library for compilation and execution of Flux.
Package interpreter provides the implementation of the Flux interpreter.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Package mock contains mock implementations of the query package interfaces for testing.
Package parser implements a parser for Flux source files.
No description provided by the author
Package querytest contains utilities for testing the query end-to-end.
Package repl implements the read-eval-print-loop for the command line flux query console.
No description provided by the author
The semantic package provides a graph structure that represents the meaning of a Flux script.
Package stdlib represents the Flux standard library.
Package values declares the flux data types and implements them.

# Functions

ColumnType returns the column type when given a semantic.Type.
ConvertDurationNsecs will convert a time.Duration into a flux.Duration.
ErrorCode returns the error code for the given error.
ErrorDocURL returns the DocURL associated with this error if one exists.
FunctionValue creates a values.Value from the operation spec and signature.
FunctionValueWithSideEffect creates a values.Value from the operation spec and signature.
No description provided by the author
GetDialer will return a net.Dialer using the injected dependencies within the context.Context.
MustValue panics if err is not nil, otherwise value is returned.
NewDefaultDependencies produces a set of dependencies.
NewEmptyDependencies produces an empty set of dependencies.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
SetNowOption returns a ScopeMutator that sets the `now` option to the given time.
SetOption returns a func that adds a var binding to a scope.
No description provided by the author

# Constants

GroupModeBy produces a table for each unique value of the specified GroupKeys.
GroupModeExcept produces a table for the unique values of all keys, except those specified by GroupKeys.
GroupModeNone indicates that no grouping action is specified.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Variables

No description provided by the author
No description provided by the author
No description provided by the author

# Structs

No description provided by the author
No description provided by the author
No description provided by the author
ColMeta contains the information about the column metadata.
DelimitedMultiResultEncoder encodes multiple results using a trailing delimiter.
Deps implements Dependencies.
ResourceManagement defines how the query should consume avaliable resources.
Statistics is a collection of statistics about the processing of a query.
TableObject represents the value returned by a transformation.
Time represents either a relative or absolute time.
TransportProfile holds the profile for transport statistics.
TransportProfileSpan is a span that tracks the lifetime of a transport operation.
No description provided by the author

# Interfaces

ASTHandle is an opaque type that represents an abstract syntax tree.
BufferedTable is an implementation of Table that has all of its data buffered.
ColReader allows access to reading arrow buffers of column data.
Compiler produces a specification for the query.
No description provided by the author
Dialect describes how to encode results.
EncoderError is an interface that any error produced from a ResultEncoder implementation should conform to.
No description provided by the author
MultiResultDecoder can decode multiple results from a reader.
MultiResultEncoder can encode multiple results into a writer.
OperationSpec specifies an operation as part of a query.
Program defines a Flux script which has been compiled.
Query represents an active query.
No description provided by the author
ResultDecoder can decode a result from a reader.
ResultEncoder can encode a result into a writer.
ResultIterator allows iterating through all results synchronously.
Runtime encapsulates the operations supported by the flux runtime.
Table represents a set of streamed data with a common schema.
No description provided by the author

# Type aliases

ColType is the type for a column.
No description provided by the author
CompilerType is the name of a query compiler.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
DialectType is the name of a query result dialect.
Duration is a marshalable duration type.
No description provided by the author
GroupKeys provides a sortable collection of group keys.
GroupMode represents the method for grouping data.
OperationKind denotes the kind of operations.
ScopeMutator is any function that mutates the scope of an identifier.