A newer version of this documentation is available.

View Latest

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:

Named Placeholders
from couchbase.n1ql import N1QLQuery
# ...
q = N1QLQuery('SELECT fname, lname, age FROM default WHERE age > $age', age=22)
for row in bkt.n1ql_query(q):
print row  # {'age': .., 'lname': ..., 'fname': ...}
Positional Placeholders
q = N1QLQuery('SELECT fname, lname, age FROM default WHERE fname LIKE $1 or lname LIKE $2',
              '%ty%', '%thon%')


You may configure the N1QLQuery object with various options to control query behavior. You may set the query.adhoc parameter to False to make use of prepared queries

query = N1QLQuery(query_string)
query.adhoc = False

and you can also set query.consistency to couchbase.n1ql.CONSISTENCY_REQUEST to employ the read-your-own-writes consistency mechanism.

from couchbase.n1ql import CONSISTENCY_REQUEST
query.consistency = CONSISTENCY_REQUEST

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.

bkt.n1ql_query("CREATE PRIMARY INDEX ON default").execute()

Index Creation

In order to query a bucket, it must have an index defined. You can create indexes using raw N1QL statements (e.g. CREATE INDEX) or via the Python SDK’s cluster management interface