Skip to content

Instantly share code, notes, and snippets.

@ofonimefrancis ofonimefrancis/go
Last active Sep 5, 2018

Embed
What would you like to do?
package main
import (
"log"
"time"
client "github.com/influxdata/influxdb/client/v2"
)
const (
MYDB = "tutorial"
)
type Order struct {
UserID string
ProductName string
Quantity int
Price float32
TimePurchased time.Time
}
func main() {
c, err := client.NewHTTPClient(client.HTTPConfig{
Addr: "http://localhost:8086",
})
if err != nil {
log.Fatal(err)
}
defer c.Close()
var orders []Order
order1 := Order{UserID: "2221", Price: 90000, ProductName: "Bread", Quantity: 120, TimePurchased: time.Now()}
order2 := Order{UserID: "2221", Price: 10000, ProductName: "Cream", Quantity: 756, TimePurchased: time.Now()}
order3 := Order{UserID: "2221", Price: 9000, ProductName: "Biscuit", Quantity: 900, TimePurchased: time.Now()}
order4 := Order{UserID: "2221", Price: 40000, ProductName: "Shirt", Quantity: 110, TimePurchased: time.Now()}
order5 := Order{UserID: "2221", Price: 1000000, ProductName: "Watch", Quantity: 60, TimePurchased: time.Now()}
order6 := Order{UserID: "2221", Price: 100000, ProductName: "Bangles", Quantity: 100, TimePurchased: time.Now()}
orders = append(orders, order1)
orders = append(orders, order2)
orders = append(orders, order3)
orders = append(orders, order4)
orders = append(orders, order5)
orders = append(orders, order6)
writeOrders(c, orders)
}
func writeOrders(influxClient client.Client, orders []Order) {
batchPoint, err := client.NewBatchPoints(client.BatchPointsConfig{
Database: MYDB,
Precision: "us",
})
if err != nil {
log.Fatal(err)
}
for i := 0; i < len(orders); i++ {
//Create tags - We want to be able to search orders by user_id for example and since tags can be indexed
tags := map[string]string{
"user_id": orders[i].UserID,
"product_name": orders[i].ProductName,
}
//Create fields
fields := map[string]interface{}{
"price": orders[i].Price,
"qty": orders[i].Quantity,
}
point, err := client.NewPoint(
"orders",
tags,
fields,
time.Now(),
)
if err != nil {
log.Fatal(err)
}
batchPoint.AddPoint(point)
}
if err := influxClient.Write(batchPoint); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.