Files
nexus/wiki/concepts/PromQL.md
2026-04-22 04:03:04 +08:00

84 lines
2.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: "PromQL"
type: concept
aliases: [Prometheus Query Language, Prometheus查询语言]
tags: [prometheus, query, monitoring, time-series]
date: 2025-11-11
---
# PromQL
## Overview
PromQLPrometheus Query Language是 Prometheus 内置的时序数据查询语言,用于从 Prometheus TSDB 中检索和处理指标数据。它支持即时向量查询(返回当前时间点的样本)、范围向量查询(返回一段时间内的样本序列)、标量转换、聚合操作和丰富的函数库。
## Query Types
### 即时向量查询Instant Vector
返回当前时刻的一组时间序列,每个序列只有一个样本值:
```promql
node_memory_MemAvailable_bytes
```
### 范围向量查询Range Vector
返回一段时间内的样本序列,用于计算速率:
```promql
rate(node_cpu_seconds_total{mode="user"}[2m])
```
### 标量Scalar
没有时间序列的单个数值:
```promql
count(node_cpu_seconds_total)
```
## Aggregation Operators
PromQL 内置丰富的聚合操作符:
| 操作符 | 说明 |
|--------|------|
| `sum()` | 求和 |
| `avg()` | 平均值 |
| `min()` / `max()` | 最小/最大值 |
| `count()` | 计数 |
| `stddev()` / `stdvar()` | 标准差/方差 |
| `topk()` / `bottomk()` | 最大/最小的 k 个值 |
| `rate()` | 平均速率(适合 Counter |
| `increase()` | 增量(适合 Counter |
| `irate()` | 瞬时速率(适合快速变化指标) |
## Common Patterns for Home Server Monitoring
```promql
# CPU 使用率5分钟平均 > 85%
avg(rate(node_cpu_seconds_total{mode="user"}[2m])) * 100 > 85
# 磁盘可用空间 < 10%
(node_filesystem_avail_bytes{fstype!~"tmpfs|overlay"} / node_filesystem_size_bytes{fstype!~"tmpfs|overlay"}) < 0.10
# 内存可用率 < 15%
(node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) < 0.15
# HTTP 探测失败(黑盒)
probe_success == 0
# TLS 证书剩余天数 < 14 天
(probe_ssl_earliest_cert_expiry - time()) / 86400 < 14
# 容器重启次数
increase(container_restart_count[5m]) > 0
```
## Label Matchers
| Matcher | 说明 |
|---------|------|
| `=` | 精确匹配 |
| `!=` | 不等于 |
| `=~` | 正则匹配 |
| `!~` | 正则不匹配 |
示例:`{job=~"node.*", mode!="idle"}`
## Related Entities
- [[Prometheus]] — 查询引擎宿主
## Related Concepts
- [[Prometheus告警规则]] — 基于 PromQL 的告警条件
- [[时序数据库]] — 数据模型基础
- [[Exporter]] — 指标来源