Reputation: 75
How to query the raw time series values of a specified metrics in prometheus without step? For example, I want to query how many datapoints are actually available in 1 minute, but when I specify step as 15s, 4 results will be generated regardless of the number of datapoints
package main
import (
"context"
"fmt"
"github.com/prometheus/client_golang/api"
v1 "github.com/prometheus/client_golang/api/prometheus/v1"
"log"
"time"
)
var (
prometheus string = "http://10.22.5.54:8481/select/0/prometheus"
timeout time.Duration = time.Second * 30
)
func main() {
client, err := api.NewClient(api.Config{Address: prometheus})
if err != nil {
log.Fatalln("Error connect to the prometheus: ", err)
}
v1api := v1.NewAPI(client)
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
result, warnings, err := v1api.QueryRange(ctx, "up{app=\"activity-api\"}", v1.Range{Start: time.Now().Add(-time.Minute * 1), End: time.Now(), Step: time.Second * 15})
if err != nil {
log.Printf("Error querying Prometheus: %s\n", err)
}
if len(warnings) > 0 {
log.Printf("Warnings: %s", warnings)
}
fmt.Println(result)
}
Upvotes: 1
Views: 3640
Reputation: 18084
You need to use v1api.Query
instead of v1api.QueryRange
, and add the needed interval in square brackets at the end of series selector. For example, the following query should return raw samples for time series matching up{app="activity-api"}
for the last 15 seconds ending at the given time
.
t := time.Now()
result, warnings, err := v1api.Query(ctx, `up{app="activity-api"}[15s]`, t)
See more details here.
Internally the github.com/prometheus/client_golang
package just queries /api/v1/query HTTP endpoint, so it may be easier to just issue HTTP request to this endpoint without the need to figure out how to use github.com/prometheus/client_golang
. For example, the following command will return raw samples from VictoriaMetrics cluster:
curl http://10.22.5.54:8481/select/0/prometheus/api/v1/query -d 'up{app="activity-api"}[15s]'
VictoriaMetrics also provides APIs for exporting raw samples.
See also https://valyala.medium.com/analyzing-prometheus-data-with-external-tools-5f3e5e147639 .
Upvotes: 2