Last active
February 6, 2018 19:14
-
-
Save nilsmagnus/ffdcbe295f80104b6dc77ae712a0cbfd to your computer and use it in GitHub Desktop.
Join several time-series from influxdb to a single csv output.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"github.com/influxdata/influxdb/client/v2" | |
"strings" | |
"flag" | |
) | |
func main() { | |
database := flag.String("database", "forecasts", "specify database name") | |
username := flag.String("username", "admin", "specify database user") | |
password := flag.String("password", "password", "specify user password") | |
hostname := flag.String("hostname", "http://localhost:8086", "specify database hostname") | |
query := flag.String("query", "select * from oslo, trondheim, stavanger", "query to execute") | |
flag.Parse() | |
// Create a new HTTPClient | |
c, err := client.NewHTTPClient(client.HTTPConfig{ | |
Addr: *hostname, | |
Username: *username, | |
Password: *password, | |
InsecureSkipVerify: true, | |
}) | |
if err != nil { | |
log.Fatal(err) | |
} | |
res, err := queryDB(c, *database, *query) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// headers | |
for _, r := range res { | |
var colNames []string | |
for _, series := range r.Series { | |
colNames = append(colNames, series.Columns...) | |
} | |
fmt.Println(strings.Join(colNames, ", ")) | |
} | |
// join all values | |
allValues := make(map[interface{}][]interface{}) | |
allTimes := make([]interface{}, 0) | |
for _, r := range res { | |
for _, series := range r.Series { | |
for rowNumber, rowValues := range series.Values { | |
if _, exists := allValues[rowValues[0]]; exists { | |
allValues[rowValues[0]] = append(allValues[rowValues[0]], rowValues[1:]...) | |
} else { | |
allTimes = append(allTimes, rowValues[0]) | |
allValues[rowValues[0]] = rowValues | |
} | |
} | |
} | |
} | |
// print results | |
for _, time := range allTimes { | |
fmt.Println(join(allValues[time], ",")) | |
} | |
} | |
// join values to a comma-separated string | |
func join(values []interface{}, sep string) (string) { | |
ss := make([]string, len(values)) | |
for k, v := range values { | |
ss[k] = fmt.Sprintf("%v", v) | |
} | |
return strings.Join(ss, sep) | |
} | |
func queryDB(clnt client.Client, database, cmd string) (res []client.Result, err error) { | |
q := client.Query{ | |
Command: cmd, | |
Database: database, | |
} | |
if response, err := clnt.Query(q); err == nil { | |
if response.Error() != nil { | |
return res, response.Error() | |
} | |
res = response.Results | |
} else { | |
return res, err | |
} | |
return res, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment