这些函数用于操作标签——它们允许您将标签连接到其他标签、提取标签值的一部分,甚至删除标签(尽管使用标准聚合运算符执行该特定操作更容易且更符合人体工程学)。在这两个函数中,如果定义的目标标签是一个新的,它将被添加到标签集中;如果它是现有标签,它将被替换。
使用 label_join 时,您需要提供即时向量、定义结果标签、识别结果连接的分隔符并建立要连接的标签,如以下语法所示:
label_join(<vector>, <resulting_label>, <separator>, source_label1, source_labelN)
例如,假设我们使用以下示例数据:
http_requests_total{code="200",endpoint="hey-port", handler="/",instance="172.17.0.10:8000",job="hey-service",method="get"} 1366
http_requests_total{code="200",endpoint="hey-port", handler="/health",instance="172.17.0.10:8000",job="hey-service",method="get"} 942
然后我们应用以下表达式:
label_join(http_requests_total{instance="172.17.0.10:8000"}, "url", "", "instance", "handler")
我们最终得到以下即时向量:
http_requests_total{code="200",endpoint="hey-port", handler="/",instance="172.17.0.10:8000",job="hey-service", method="get",url="172.17.0.10:8000/"} 1366
http_requests_total{code="200",endpoint="hey-port", handler="/health",instance="172.17.0.10:8000",job="hey-service", method="get",url="172.17.0.10:8000/health"} 942
当您需要任意操作标签时,label_replace 就是要使用的函数。它的工作方式是将正则表达式应用于所选源标签的值并将匹配的捕获组存储在目标标签上。源和目标都可以是同一个标签,有效地替换它的值。这听起来很复杂,但事实并非如此;我们来看看label_replace的语法:
label_replace(<vector>, <destination_label>, <regex_match_result>, <source_label>, <regex>)
假设我们采用前面的样本数据并应用以下表达式:
label_replace(http_requests_total{instance="172.17.0.10:8000"}, "port", "$1", "instance", ".*:(.*)")
结果将是带有新标签的匹配元素,称为 port:
http_requests_total{code="200",endpoint="hey-port",handler="/", instance="172.17.0.10:8000", job="hey-service",method="get",port="8000"} 1366
http_requests_total{code="200",endpoint="hey-port",handler="/health", instance="172.17.0.10:8000", job="hey-service",method="get",port="8000"} 942
使用 label_replace 时,如果正则表达式与标签值不匹配,则原始时间序列将原样返回。