N1QL Queries

class couchbase_core.n1ql.N1QLQuery[source]
__init__(query, *args, **kwargs)[source]

Create an N1QL Query object. This may be passed as the params argument to N1QLRequest.

  • query – The query string to execute

  • args – Positional placeholder arguments. These satisfy the placeholder values for positional placeholders in the query string, such as $1, $2 and so on.

  • kwargs – Named placeholder arguments. These satisfy named placeholders in the query string, such as $name, $email and so on. For the placeholder values, omit the leading sigil ($).

Use positional parameters:

q = N1QLQuery('SELECT * FROM `travel-sample` '
              'WHERE type=$1 AND id=$2',
              'airline', 0)

for row in cb.n1ql_query(q):
    print 'Got', row

Use named parameters:

q = N1QLQuery('SELECT * FROM `travel-sample` '
              'WHERE type=$type AND id=$id',
               type='airline', id=0)
for row in cb.n1ql_query(q):
    print 'Got', row

When using placeholders, ensure that the placeholder value is the unserialized (i.e. native) Python value, not the JSON serialized value. For example the query SELECT * FROM products WHERE tags IN ["sale", "clearance"] can be rewritten using placeholders:


N1QLQuery('SELECT * FROM products WHERE tags IN $1',
          ['sale', 'clearance'])


N1QLQuery('SELECT * FROM products WHERE tags IN $1',

Since the placeholders are serialized to JSON internally anyway.

set_option(name, value)[source]

Set a raw option in the query. This option is encoded as part of the query parameters without any client-side verification. Use this for settings not directly exposed by the Python client.

  • name – The name of the option

  • value – The value of the option


Indicate that the query should be consistent with one or more mutations.


state (MutationState) – The state of the mutations it should be consistent with.


Sets the consistency level.




Get an encoded representation of the query.

This is used internally by the client, and can be useful to debug queries.


A non-adhoc query can be internally optimized so that repeated executions of the same query can be quicker. If this query is issued repeatedly in your application, then you should set this property to False.

Note that this optimization involves an up-front “preparation” cost, and should only be used for queries that are issued multiple times.


Optional per-query timeout. If set, this will limit the amount of time in which the query can be executed and waited for.


The effective timeout for the query will be either this property or the value of couchbase_core.bucket.Bucket.n1ql_timeout property, whichever is lower.

See also



Set this to true to indicate that the query string involves multiple buckets. This makes the query a “cluster-level” query. Cluster level queries have access to documents in multiple buckets, using credentials supplied via Bucket.add_bucket_creds()

couchbase_core.n1ql.NOT_BOUNDED = 'not_bounded'
couchbase_core.n1ql.REQUEST_PLUS = 'request_plus'
couchbase_core.n1ql.UNBOUNDED = 'none'
class couchbase_core.mutation_state.MutationState(*docs)[source]


The API and implementation of this class are subject to change.

This class acts as a container for one or more mutations. It may then be used with the consistent_with() method to indicate that a given query should be bounded by the contained mutations.

Using consistent_with is similar to setting consistency to REQUEST_PLUS, but is more optimal as the query will use cached data, except when the given mutation(s) are concerned. This option is useful for use patterns when an application has just performed a mutation, and wishes to perform a query in which the newly-performed mutation should reflect on the query results.


This feature requires Couchbase Server 4.5 or greater, and also requires that fetch_mutation_tokens=true be specified in the connection string when creating a Bucket

cb = Bucket('couchbase://localhost/default?fetch_mutation_tokens=true')

rvs = cb.upsert_multi({
    'foo': {'type': 'user', 'value': 'a foo value'},
    'bar': {'type': 'user', 'value': 'a bar value'}

nq = N1QLQuery('SELECT type, value FROM default WHERE type="user"')
ms = MutationToken()
for row in cb.n1ql_query(nq):
    # ...
class couchbase_core.n1ql.N1QLRequest[source]
__init__(params, parent, row_factory=<function N1QLRequest.<lambda>>, meta_lookahead=True, **kwargs)[source]

Object representing the execution of the request on the server.


You should typically not call this constructor by yourself, rather use the n1ql_query() method (or one of its async derivatives).

  • params – An N1QLQuery object.

  • parent – The parent Bucket object

  • row_factory – Callable which accepts the raw dictionary of each row, and can wrap them in a customized class. The default is simply to return the dictionary itself.

To actually receive results of the query, iterate over this object.


Execute the statement and raise an exception on failure.

This method is useful for statements which modify data or indexes, where the application does not need to extract any data, but merely determine success or failure.


Execute the statement and return its single result.

This should only be used on statements which are intended to return only a single result.


The single result, as encapsulated by the row_factory