N1QL Queries

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

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

Parameters:
  • 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:

Correct:

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

Incorrect:

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

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.

Parameters:
  • name – The name of the option
  • value – The value of the option
consistent_with(state)[source]

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

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

Sets the consistency level.

See:NOT_BOUNDED, REQUEST_PLUS
encoded

Get an encoded representation of the query.

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

adhoc

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.

timeout

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

Note

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

See also

couchbase.bucket.Bucket.n1ql_timeout

cross_bucket

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.n1ql.NOT_BOUNDED = 'not_bounded'

For use with consistency, will allow cached values to be returned. This will improve performance but may not reflect the latest data in the server.

couchbase.n1ql.REQUEST_PLUS = 'request_plus'

For use with consistency, will ensure that query results always reflect the latest data in the server

couchbase.n1ql.UNBOUNDED = 'none'

Deprecated since version 2.3.3: Use couchbase.n1ql.NOT_BOUNDED instead. This had no effect in its advertised usage as a value for consistency before.

class couchbase.n1ql.MutationState(*docs)[source]

Warning

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.

Note

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()
ms.add_result(rv
nq.consistent_with_ops(*rvs.values())
for row in cb.n1ql_query(nq):
    # ...
class couchbase.n1ql.N1QLRequest[source]
__init__(params, parent, row_factory=<function N1QLRequest.<lambda>>)[source]

Object representing the execution of the request on the server.

Warning

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

Parameters:
  • 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.

__iter__()[source]
execute()[source]

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.

meta

Get metadata from the query itself. This is guaranteed to only return a Python dictionary.

Note that if the query failed, the metadata might not be in JSON format, in which case there may be additional, non-JSON data which can be retrieved using the following

raw_meta = req.raw.value
Returns:A dictionary containing the query metadata
get_single_result()[source]

Execute the statement and return its single result.

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

Returns:The single result, as encapsulated by the row_factory