Get and aggregate metrics with PromQL

prometheus

PromQL is a query language for Prometheus, which can get single time samples of the metric as an Instant vector, or period samples as Range vector with specifying a time period in square brackets.

prometheus_http_requests_total{code="200",handler=~"/api/.*"}
prometheus_http_requests_total{code="200",handler=~"/api/.*"}[5m]

Functions take an Instant vector or a Range vector.

sum(prometheus_http_requests_total)
sum_over_time(prometheus_http_requests_total[5m])

rate(v range-vector) returns the average increment per second of a monotonically increasing counter, caring about resets of the value. It is used to calculate the current request rate, CPU usage, etc.

rate(prometheus_http_requests_total[5m])

by can perform the equivalent of “group by” in SQL.

sum by (handler) (rate(prometheus_http_requests_total[5m]))

(operator) on (label1) group_left/right (label2) can perform N:1/1:N JOIN on label1 and add label2. Unlike SQL, N:N JOIN is not possible.

sum by (handler) (rate(prometheus_http_requests_total[5m])) / on (code) group_left () sum(rate(prometheus_http_requests_total[5m]))

Since “A or B” takes values that labels are not included in A from B, you can treat metrics for times that have no value as 0 with absent(v instant-vector) that returns 1 if there is no value.

non_exist_metrics{aaa="bbb"} or (absent(non_exist_metrics{aaa="bbb"}) * 0)