Search code examples
prometheuspromql

Aggregate two metrics with dynamic labels in PromQL


How to aggregate two metrics

metric1{ValueA=1, ValueB=2}
metrics2(ValueB=2, ValueC=3}

in PromQL where I want to have the following output?

{ValueA=1, ValueB=4, ValueC=3}

I'm trying to create a bar gauge in Grafana where I want to have the aggregate of this two metrics. Some previous answers here needs that you know the labels beforehand, but in my case, there might be new labels adding into either of the metrics.


Solution

  • You are using Prometheus incorrectly: whenever you find yourself in situation that you want/need to make some calculation over values of labels - you messed up.

    In your case all those "labels" should be their own metrics/time series.

    Based on your description I'd suggest changing your metrics to

    metric1{type="ValueA"} 1
    metric1{type="ValueB"} 2
     
    metric2{type="ValueB"} 2
    metric2{type="ValueC"} 3
    

    After that you could achieve your goal with query sum by(type) ({__name__=~"metric1|metric2"})


    Your current situation cannot be solved with promQL (AFAIK neither it can be done with Transformations in Grafana).