Analytics using the Go SDK

Parallel data management for complex queries over many records, using a familiar N1QL-like syntax.

For complex and long-running queries, involving large ad hoc join, set, aggregation, and grouping operations, Couchbase Data Platform offers the Couchbase Analytics Service (CBAS). This is the analytic counterpart to our operational data focussed Query Service. The analytics service is available in Couchbase Data Platform 6.0 and later (developer preview in 5.5).

Getting Started

After familiarizing yourself with our introductory primer, in particular creating a dataset and linking it to a bucket to shadow the operational data, try Couchbase Analytics using the Go SDK. Intentionally, the API for analytics is very similar to that of the query service. In these examples we will be using an airports dataset created on the travel-sample bucket.

In Go SDK 1.x, Analytics was only available on the Bucket object; in Go SDK 2.0, Analytics queries are submitted using the Cluster reference, not a Bucket or Collection:

When using a Couchbase version < 6.5 you must create a valid Bucket connection using cluster.Bucket(name) before you can use Analytics.
results, err := cluster.AnalyticsQuery("SELECT \"hello\" as greeting;", nil)
if err != nil {
	panic(err)
}

var greeting interface{}
for results.Next() {
	err := results.Row(&greeting)
	if err != nil {
		panic(err)
	}
	fmt.Println(greeting)
}

// always check for errors after iterating.
err = results.Err()
if err != nil {
	panic(err)
}

Queries

A query can either be simple or be parameterized. If parameters are used, they can either be positional or named. Here is one example of each:

results, err := cluster.AnalyticsQuery("select airportname, country from airports where country = 'France';", nil)
if err != nil {
	panic(err)
}

The query may be performed with positional parameters:

results, err := cluster.AnalyticsQuery(
	"select airportname, country from airports where country = ?;",
	&gocb.AnalyticsOptions{
		PositionalParameters: []interface{}{"France"},
	},
)

Alternatively, the query may be performed with named parameters:

results, err := cluster.AnalyticsQuery(
	"select airportname, country from airports where country = $country;",
	&gocb.AnalyticsOptions{
		NamedParameters: map[string]interface{}{"country": "France"},
	},
)
As timeouts are propagated to the server by the client, a timeout set on the client side may be used to stop the processing of a request, in order to save system resources. See example in the next section.

Options

Additional parameters may be sent as part of the query. There are currently three parameters:

  • Client Context ID, sets a context ID that is returned back as part of the result. Uses ClientContextID string default is a random UUID

  • Timeout, customizes the timeout sent to the server. Does not usually have to be set, as the client sets it based on the timeout on the operation. Uses Timeout time.Duration, and defaults to the Analytics timeout set on the client (75s). This can be adjusted at the cluster global config level.

  • Priority, set if the request should have priority over others. The Priority bool option defaults to false.

Here, we give the request priority over others, and set a custom, server-side timeout value:

results, err = cluster.AnalyticsQuery(
	"select airportname, country from airports where country = 'France';",
	&gocb.AnalyticsOptions{
		Priority: true,
		Timeout:  100 * time.Second,
	},
)

Handling the Response

These query result may contain various sorts of data and metadata, depending upon the nature of the query, as you will have seen when working through our introductory primer.

Results are iterated using the Next function. Within the for loop the result is read using the Row by supplying a pointer to the variable in which to store the value. Always remember to check the error value of Err after iterating the results, this is where any errors occurring whilst calling Next will be returned.

var rows []interface{}
for results.Next() {
	var row interface{}
	if err := results.Row(&row); err != nil {
		panic(err)
	}
	rows = append(rows, row)
}

if err := results.Err(); err != nil {
	panic(err)
}

Common errors are listed in our Errors Reference doc, with errors caused by resource unavailability (such as timeouts and Operation cannot be performed during rebalance messages) leading to an automatic retry by the SDK.

MetaData

The AnalyticsResultsMetadata object contains useful metadata, such as Metrics and ClientContextID. Note that before metadata can be accessed the results object must be closed. Here is a snippet using several items of metadata

// make sure that results has been iterated (and therefore closed) before calling this.
metadata, err := results.MetaData()
if err != nil {
	panic(err)
}

fmt.Printf("Client context id: %s\n", metadata.ClientContextID)
fmt.Printf("Elapsed time: %d\n", metadata.Metrics.ElapsedTime)
fmt.Printf("Execution time: %d\n", metadata.Metrics.ExecutionTime)
fmt.Printf("Result count: %d\n", metadata.Metrics.ResultCount)
fmt.Printf("Error count: %d\n", metadata.Metrics.ErrorCount)

For a listing of available Metrics in MetaData, see the Understanding Analytics SDK doc.