Skip to content

Instantly share code, notes, and snippets.

@Harkishen-Singh
Forked from gouthamve/main.go
Created June 30, 2020 20:45
Show Gist options
  • Save Harkishen-Singh/9ea079b2861b2b2212611aaeda7d4a71 to your computer and use it in GitHub Desktop.
Save Harkishen-Singh/9ea079b2861b2b2212611aaeda7d4a71 to your computer and use it in GitHub Desktop.
A complete runnable example
package main
import (
"fmt"
"io/ioutil"
"os"
"time"
"github.com/prometheus/tsdb"
"github.com/prometheus/tsdb/labels"
)
func main() {
tmpdir, _ := ioutil.TempDir("", "test")
defer os.RemoveAll(tmpdir)
db, err := tsdb.Open(tmpdir, nil, nil, &tsdb.Options{
WALFlushInterval: 10 * time.Second,
BlockRanges: []int64{
15 * 60 * 1000, // 15mins in milliseconds
60 * 60 * 1000, // 1hr
4 * 60 * 60 * 1000, // 4hrs
},
RetentionDuration: uint64(15 * 24 * 60 * 60 * 1000), // 15d
})
if err != nil {
panic(err)
}
app := db.Appender()
app.Add(labels.FromStrings("foo", "bar"), 0, 0)
app.Add(labels.FromStrings("foo", "baz"), 0, 0)
app.Add(labels.FromStrings("foo", "fifi"), 0, 0)
app.Add(labels.Labels{{"a", "b"}}, 10, 0.5)
app.Add(labels.Labels{{"a", "b"}}, 11, 0.6)
app.Add(labels.Labels{{"a", "b"}}, 12, 1.5)
app.Add(labels.Labels{{"a", "b"}}, 13, 1.6)
app.Add(labels.Labels{{"a", "ball"}}, 1, 1.5)
app.Add(labels.Labels{{"a", "ball"}}, 3, 1.6)
if err := app.Commit(); err != nil {
panic(err)
}
q, err := db.Querier(1, 1000) // The data b/w t=1 to t=1000
if err != nil {
panic(err)
}
rem, err := labels.NewRegexpMatcher("a", "b.*")
seriesSet, err := q.Select(rem)
if err != nil {
panic(err)
}
for seriesSet.Next() {
// Get each Series
s := seriesSet.At()
fmt.Println("Labels:", s.Labels())
fmt.Println("Data:")
it := s.Iterator()
for it.Next() {
ts, v := it.At()
fmt.Println("ts =", ts, "v =", v)
}
if err := it.Err(); err != nil {
panic(err)
}
}
if err := seriesSet.Err(); err != nil {
panic(err)
}
q.Close() // To release locks.
// Close db cleanly.
if err := db.Close(); err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment