Querying with SQL++

      +
      You can query for documents in Couchbase using the SQL++ query language, a language based on SQL, but designed for structured and flexible JSON documents.

      On this page we dive straight into using the Query Service API from the Go Analytics SDK. For a deeper look at the concepts, to help you better understand the Query Service, and the SQL++ language, see the links in the Further Information section at the end of this page.

      Here we show queries against the Travel Sample collection, at cluster and scope level, and give links to information on adding other collections to your data.

      Before You Start

      This page assumes that you have installed the Go Analytics SDK, and created an Enterprise Analytics cluster.

      Create a collection to work upon by importing the travel-sample dataset into your cluster.

      Querying Your Dataset

      Execute a query and print all rows:

      	scope := cluster.Database("my_database").Scope("my_scope")
      	result, err := scope.ExecuteQuery(ctx, "select 1")
      	handleErr(err)
      
      	for row := result.NextRow(); row != nil; row = result.NextRow() {
      		var content map[string]int
      
      		err = row.ContentAs(&content)
      		handleErr(err)
      
      		fmt.Printf("Got row content: %v", content)
      	}
      Cluster Level
      	result, err := cluster.ExecuteQuery(ctx, "select 1")
      	handleErr(err)
      
      	for row := result.NextRow(); row != nil; row = result.NextRow() {
      		var content map[string]int
      
      		err = row.ContentAs(&content)
      		handleErr(err)
      
      		fmt.Printf("Got row content: %v", content)
      	}

      Positional and Named Parameters

      Supplying parameters as individual arguments to the query allows the query engine to optimize the parsing and planning of the query. You can either supply these parameters by name or by position.

      Execute a streaming query with positional arguments:

      Positional Parameters
      	result, err := cluster.ExecuteQuery(
      		ctx,
      		"select ?=1",
      		cbanalytics.NewQueryOptions().SetPositionalParameters([]interface{}{1}),
      	)
      	handleErr(err)

      Execute a streaming query with named arguments:

      Named Parameters
      	result, err := cluster.ExecuteQuery(
      		ctx,
      		"select $foo=1",
      		cbanalytics.NewQueryOptions().SetNamedParameters(map[string]interface{}{"foo": 1}),
      	)
      	handleErr(err)

      Access query metadata

      Metadata
      	meta, err := result.MetaData()
      	handleErr(err)
      
      	fmt.Printf("Got meta: %v", meta)

      Further Information

      The SQL++ for Analytics Reference offers a complete guide to the SQL++ language for both of our analytics services, including all of the latest additions.