When computing, how to handle null values in PromQL.

43 views
Skip to first unread message

lemon zhang

unread,
Dec 6, 2024, 4:58:28 AM12/6/24
to Prometheus Users
I have two metrics, A and B. I want the result of A + B to be as follows: for time points where A does not exist, the result should be the value of B at that time point; for time points where B does not exist, the result should be the value of A at that time point; and for time points where both A and B exist, the result should be A + B. How can I write this in PromQL? Currently, I can use (A + B) or A or B , but are there other ways to write it that are more performant and easier to read? If not, I would like to add an operator that specifies how to handle null values, such as A + null_as(0) B , which would be clearer, more readable, and potentially more performant.

Brian Candler

unread,
Dec 6, 2024, 5:25:26 AM12/6/24
to Prometheus Users
"(A + B) or A or B" is correct.

Remember that "A + B" is not a scalar arithmetic expression. It's a vector expression:
- for every element in vector A and B which have exactly matching label sets (apart from __name__), calculate the sum and put it in the result vector with the same set of labels
- for every element in vector A which doesn't have a corresponding label match in vector B, or vice versa, there is no result

Therefore, "null_as(0) B" makes no sense, because there are no "null" values in B. You could say there are "missing" values, but these are only "missing" when referenced to some other vector A.

"(A + B)" gives you the vector of results where labels match in both A and B. "or A" then adds appends those values where the label set only exists in A, and not in the sum (and hence implicitly not in B, since those which were in both A and B are already present). "or B" then appends those values where the label set only exists in B.
Reply all
Reply to author
Forward
0 new messages