Search code examples
elasticsearchgrafanagrafana-apigrafana-alerts

How to get number of rows in a table panel in Grafana through API?


As the question speaks for itself, I am aware that the latest Grafana has the option to Inspect Panels in the UI itself, but I wanted to expose the number of rows in the given table through an API. Wanted to write an automation code that deals with the number of rows, however, I cannot figure out an easier way to do that. The grafana I am dealing with is using elasticsearch nodes for querying.


Solution

  • Update:

    I didn't find any way to get the number of rows through an API endpoint from Grafana, however, what I did was, I copied the Elasticsearch query that the Grafana dashboard made for the given panel in the dashboard [You can copy the query either by using Networks tab on Chrome, or, you can simply follow this:

    • Get to this dropdown for panel: List item
    • Press "Inspect"
    • Click on "Query" tab here: enter image description here
    • There you will see the Query, copy it and use it in the Elasticsearch Query API, and you will get your desired JSON response ]

    , and counted the number of "buckets" that are at the deepest level (say, you have used 4 group-by, example: enter image description here

    then the deepest bucket would be at level 4), and calculated the number of such Buckets which have keys, and that gives me the number of rows in the table panel.

    This is a simple python code I wrote for the same:

    def get_rows(data, lev, max_depth):
    total_rows = 0
    if lev == max_depth and 'key' in data:
        total_rows += 1
    for key, value in data.items():
        if type(value) == dict:
            total_rows += get_rows(value, lev, max_depth)
        elif type(value) == list:
            if key == "buckets":
                for val in value:
                    total_rows += get_rows(val, lev+1, max_depth)
    return total_rows
    

    Here, max_depth = 4 for the above Screenshot. Hope it helps someone using Elasticsearch as Datasource.