N1QL Queries Using the Python SDK with Couchbase Server

Simple Queries

To issue N1QL queries, you should create a couchbase.n1ql.N1QLQuery object, and pass it (as the query keyword argument) to the n1ql_query() method in the Bucket class.
Simple queries (that is, ones that are only strings and do not use placeholders) can be supplied directly to the n1ql_query() function, which will implicitly create the N1QLQuery object internally.

The return value from n1ql_query() is a N1QLRequest object.
Iterating over the object will yield the rows returned by the server for the given query (as a dict).
Each row represents a row received for the query.

Simple N1QL Query

for row in bkt.n1ql_query('SELECT * FROM default'):
print row

Querying with Placeholders

You can use N1QL placeholders in the query.
Placeholders allow you to specify variable constraints for an otherwise constant query.
A named or positional parameter is a placeholder for a value in the WHERE, LIMIT or OFFSET clause of a query.
To use placeholders, manually construct an N1QLQuery object with the base query string, and simply use keyword and positional arguments for named or positional placeholders, respectively:

For queries which are expected to run for a long time, you may set the timeout on a per-query basis using the query.timeout parameter:

query.timeout = 300 # 5 minutes

No-result queries

As a convenience for queries which are not intended to yield multiple rows, you may use the returned N1QLRequest object’s execute() method.
For queries which are intended to return only a single result, you can use the get_single_result() method.
Both of the aforementioned methods are wrappers that iterate over the object internally and are intended to provide additional clarity inside your application’s code.