stringsubstringextractgrafanapromql

How to extract a substring from a label value in promql?


I have a Prometheus metric as shown below

query_duration{query = "SELECT * FROM TABLE_NAME"}

I'm trying to extract only TABLE_NAME from the label query. I'm trying to use regex to extract TABLE_NAME.

How can I extract the table name from the query label in promql ?


Solution

  • To add one more label that would contain name of the table you can use label_replace function.

    label_replace(
     query_duration
     "table","$1",
     "query",".*FROM\\s+(\\S+).*"
    )
    

    Here, content of the label query is matched against regex .*FROM\s+(\S+).* (with duplication of slashes for Prometheus) and content of group #1 put into new label table. Demo of this query here.

    If your queries might have more than one FROM clause, or generally more intricate, you'd need to adjust regex for your needs.