Not able to retrive any data using gocb v2 sdk with couchbase 6.0.1 server

I am trying to update my gocb v1 to v2 and trying to execute a n1ql query but not able to fetch any results. Is there some issue with the below code,please advice::

func GetCluster() *gocb.Cluster{
return couchbasePrimaryConn.cluster
}

n1ql := “SELECT ordr_type,ordr_id FROM bucket_name WHERE doc_type=‘doc_type1’ and context.country_code=”+ fmt.Sprintf("%s",countryCode) +" and context.correlation_id="+fmt.Sprintf("%s",correlationID)
logrus.Info(“Query:”, n1ql)

rows, err := GetCluster().Query(n1ql, &gocb.QueryOptions{})
rows.Row(&tempDoc)
defer rows.Close()
if err != nil {
	logrus.Info("In func: "+funcName+",error..", err)
	return false, ""
}

if tempDoc.RoID != "" {
	return false, tempDoc.RoID
}

Hello @kapil welcome to the forums !

Assuming GetCluster() returns you back a handle to the cluster (i.e connection to the cluster is all good) and assuming your query works (you have tried it out in query workbench )

rows.Row(&tempDoc) , I think that needs to change to be iterating over rows something like below

query := "SELECT x.* FROM `travel-sample` x LIMIT 10;"
rows, err := cluster.Query(query, &gocb.QueryOptions{})
// check query was successful
if err != nil {
	panic(err)
}

type hotel struct {
	Name string `json:"name"`
}

var hotels []hotel
// iterate over rows
for rows.Next() {
	var h hotel // this could also just be an interface{} type
	err := rows.Row(&h)
	if err != nil {
		panic(err)
	}
	hotels = append(hotels, h)
}

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

Also, there are plenty of examples that you can refer to here.

If you think this helped please mark the issue as resolved.

Thanks

Hi @kapil, just a further note to the detail that @AV25242 has added - it’s not possible to tell from from your example so just to be clear. Against a 6.0.x cluster you need to first open a bucket before you can use cluster.Query. Even though you aren’t necessarily using the bucket the cluster.Bucket call is where the connection becomes available for queries against server versions prior to 6.5. Server 6.5+ supports querying without requiring a bucket level connection.

Also just a quick note on:

rows, err := GetCluster().Query(n1ql, &gocb.QueryOptions{})
rows.Row(&tempDoc)
defer rows.Close()
if err != nil {
	logrus.Info("In func: "+funcName+",error..", err)
	return false, ""
}

You should check the value of err before accessing rows. If any error is returned then rows will be nil and you will encounter a panic. i.e.:

rows, err := GetCluster().Query(n1ql, &gocb.QueryOptions{})
if err != nil {
	logrus.Info("In func: "+funcName+",error..", err)
	return false, ""
}
...
1 Like