Шпаргалка PromQL

О шпаргалке

Эта шпаргалка содержит основные конструкции языка запросов PromQL/MetricsQL, используемого в Astra Monitoring для работы с метриками. Все примеры можно копировать и использовать в интерфейсе Astra Monitoring .

Selecting series / Выбор серий

Example

Meaning / Значение

node_cpu_seconds_total

Select latest sample for series with a given metric name / Выбрать последнее значение метрики с заданным именем

node_cpu_seconds_total[5m]

Select 5-minute range of samples for series with a given metric name / Выбрать 5-минутный диапазон значений метрики с заданным именем

node_cpu_seconds_total{cpu="0",mode="idle"}

Only series with given label values / Только ряды с указанными значениями меток

`node_cpu_seconds_total{cpu!=»0»,mode=~»user

system»}`

process_resident_memory_bytes offset 1d

Select data from one day ago and shift it to the current time / Взять значения за сутки назад и сдвинуть их ко времени запроса

Rates of increase for counters / Скорость увеличения счетчиков

Example

Meaning / Значение

rate(demo_api_request_duration_seconds_count[5m])

Per-second rate of increase, averaged over last 5 minutes / Средняя скорость увеличения в секунду за последние 5 минут

irate(demo_api_request_duration_seconds_count[1m])

Per-second rate of increase, calculated over last two samples in a 1-minute time window / Скорость увеличения в секунду по последним двум значениям за минуту

increase(demo_api_request_duration_seconds_count[1h])

Absolute increase over last hour / Абсолютное увеличение за час

Aggregating over multiple series / Агрегация по нескольким рядам

Example

Meaning / Значение

sum(node_filesystem_size_bytes)

Sum over all series / Сумма по всем рядам

sum by(job, instance) (node_filesystem_size_bytes)

Preserve the instance and job label dimensions / Сохранять метки instance, job

sum without(instance, job) (node_filesystem_size_bytes)

Aggregate away the instance and job label dimensions / Агрегировать, убрав метки instance, job

Available aggregation operators / Доступные операторы агрегации:
sum(), min(), max(), avg(), stddev(), stdvar(), count(), count_values(), group(), bottomk(), topk(), quantile()

Math between series / Математика между рядами

Example

Meaning / Значение

node_memory_MemFree_bytes + node_memory_Cached_bytes

Add all equally-labelled series from both sides / Сложить ряды с одинаковыми метками

node_memory_MemFree_bytes + on(instance, job) node_memory_Cached_bytes

Add series, matching only on the instance and job labels / Складывать, совпадая только по меткам instance и job

node_memory_MemFree_bytes + ignoring(instance, job) node_memory_Cached_bytes

Add series, ignoring the instance and job labels for matching / Складывать, игнорируя метки instance и job

rate(demo_cpu_usage_seconds_total[1m]) / on(instance, job) group_left demo_num_cpus

Explicitly allow many-to-one matching / Явно разрешить сопоставление многие-к-одному

node_filesystem_avail_bytes * on(instance, job) group_left(version) node_exporter_build_info

Include the version label from «one» (right) side in the result / Включить метку version из правой части результата

Available arithmetic operators / Доступные арифметические операторы:
+, -, *, /, %, ^

Filtering series by value / Фильтрация рядов по значению

Example

Meaning / Значение

node_filesystem_avail_bytes > 10*1024*1024

Only keep series with a sample value greater than a given number / Оставить только ряды со значениями больше заданного

go_goroutines > go_threads

Only keep series from the left-hand side whose sample values are larger than their right-hand-side matches / Оставить только левые ряды, значения которых больше правых

go_goroutines > bool go_threads

Instead of filtering, return 0 or 1 for each compared series / Возвращать 0 или 1 вместо фильтрации

go_goroutines > bool on(job, instance) go_threads

Match only on specific labels / Сравнивать только по указанным меткам

Available comparison operators / Доступные операторы сравнения:
==, !=, >, <, >=, <=

Example

Meaning / Значение

histogram_quantile(0.9, sum by(le, path, method)(rate(demo_api_request_duration_seconds_bucket[5m])))

Calculate 90th percentile for only the path and method dimensions / 90-й процентиль только для меток path и method

Changes in gauges / Изменение измеряемых метрик (gauge)

Example

Meaning / Значение

deriv(demo_disk_usage_bytes[1h])

Per-second derivative using linear regression / Производная в секунду (линейная регрессия)

delta(demo_disk_usage_bytes[1h])

Absolute change in value over last hour / Абсолютное изменение значения за час

predict_linear(demo_disk_usage_bytes[4h], 3600)

Predict value in 1 hour, based on last 4 hours / Прогноз значения через час по последним четырём часам

Aggregating over time / Агрегация по времени

Example

Meaning / Значение

avg_over_time(go_goroutines[5m])

Average within each series over a 5-minute period / Среднее по каждому ряду за 5 минут

max_over_time(process_resident_memory_bytes[1d])

Get the maximum for each series over a one-day period / Максимум для каждого ряда за сутки

count_over_time(process_resident_memory_bytes[5m])

Count the number of samples for each series over a 5-minute period / Количество значений за 5 минут

Time / Работа со временем

Example

Meaning / Значение

time()

Get the Unix time in seconds at each resolution step / Получить Unix-время в секундах для каждого шага

time() - demo_batch_last_success_timestamp_seconds

Get the age of the last successful batch job run / Возраст последнего успешного выполнения batch-задачи

time() - demo_batch_last_success_timestamp_seconds > 3600

Find batch jobs which haven’t succeeded in an hour / Batch-задачи, неудавшиеся за последний час

Dealing with missing data / Работа с отсутствующими данными

Example

Meaning / Значение

absent(up{job="some-job"})

Create one output series when the input vector is empty / Создать один ряд если входной вектор пуст

absent_over_time(up{job="some-job"}[5m])

Create one output series when the input range vector is empty for 5 minutes / Создать один ряд, если вектор пуст 5 минут

Manipulating labels / Работа с метками

Example

Meaning / Значение

label_join(rate(demo_api_request_duration_seconds_count[5m]), "endpoint", " ", "method", "path")

Join the values of two labels with a ‘ ’ (space) separator into a new endpoint label / Объединить значения меток method и path в новую метку endpoint через пробел

label_replace(up, "hostname", "$1", "instance", "(.+):(\\d+)")

Extract part of a label and store it in a new label / Извлечь часть значения метки в новую метку

Subqueries / Подзапросы

Example

Meaning / Значение

rate(demo_api_request_duration_seconds_count[5m])[1h:]

Calculate the 5-minute-averaged rate over a 1-hour period, at the default subquery resolution (= global rule evaluation interval) / 5-минутное среднее за час с дефолтным разрешением подзапроса

rate(demo_api_request_duration_seconds_count[5m])[1h:15s]

Calculate the 5-minute-averaged rate over a 1-hour period, at a 15-second subquery resolution / 5-минутное среднее за час с разрешением подзапроса 15 секунд

max_over_time(rate(demo_api_request_duration_seconds_count[5m])[1h:])

Using the subquery result to get the maximum rate over a 1-hour period / Максимальный rate из подзапроса за час

Документация: