github.com/newrelic/newrelic-client-go@v1.1.0/pkg/nrdb/example_query_test.go (about)

     1  package nrdb
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"os"
     7  	"strconv"
     8  
     9  	"github.com/newrelic/newrelic-client-go/pkg/config"
    10  )
    11  
    12  func Example_query() {
    13  	// Initialize the client configuration.  A Personal API key is required to
    14  	// communicate with the backend API.
    15  	cfg := config.New()
    16  	cfg.PersonalAPIKey = os.Getenv("NEW_RELIC_API_KEY")
    17  
    18  	accountID, err := strconv.Atoi(os.Getenv("NEW_RELIC_ACCOUNT_ID"))
    19  	if err != nil {
    20  		log.Fatal("example requires NEW_RELIC_ACCONT_ID to be set, got error: ", err)
    21  	}
    22  
    23  	// Initialize the client.
    24  	client := New(cfg)
    25  
    26  	// Execute a NRQL query to retrieve the average duration of transactions for
    27  	// the "Example application" app.
    28  	query := NRQL("SELECT average(duration) FROM Transaction TIMESERIES WHERE appName = 'Example application'")
    29  
    30  	resp, err := client.Query(accountID, query)
    31  	if err != nil {
    32  		log.Fatal("error running NerdGraph query: ", err)
    33  	}
    34  
    35  	var durations []float64
    36  	for _, r := range resp.Results {
    37  		durations = append(durations, r["average.duration"].(float64))
    38  	}
    39  
    40  	// Output the raw time series values for transaction duration.
    41  	fmt.Printf("durations: %v\n", durations)
    42  }