Read result of n1ql query using python sdk

I am trying to read the output of the n1ql_query using python sdk, but no clue to do that. can anyone help in reading the output and parsing it.

from couchbase.cluster import Cluster, PasswordAuthenticator

cluster = Cluster('couchbase://localhost:8091')
print ('Authenticator as Administrator.')
cluster.authenticate(PasswordAuthenticator('Administrator', 'Password'))
print ('Opening travel-sample bucket as user.')
bucket = cluster.open_bucket('travel-sample')
result = bucket.n1ql_query('SELECT distinct META().id FROM `travel-sample`')
print (result)

Hi, bucket.n1ql_query returns a N1QLRequest object which is an iterable of responses, i.e. it exposes the contents via the iter method. You should therefore attempt to iterate through this object using any of the typical methods, e.g.

for entry in result:
    print(entry)

or

print(list(result))

etc.

Hope that helps!

Ellis

thanks @ellis.breen…this helps:smiley:

1 Like

@ellis.breen
How do you use that to print certain attributes only.
eg
if query was
result = bucket.n1ql_query(‘SELECT META().id as metaid, t.* FROM travel-sample t’)

How would your print each attribute
eg Maybe print only metaid
or
print any other single attribute in the returned resultset ?

Hi, you would simply do the following:

for line in result:
    print(line['metaid'])

Hope that helps.

@ellis.breen
It does thanks - for some reason I was trying to re-iterate through the dict via values ()

1 Like