In addition to fetching documents by keys, you can also employ Views to retrieve information using secondary indexes. This guide gets you started on how to use them from the Python SDK. If you want to learn more about views, see the chapter in the Couchbase Server 2.0 documentation.
First, create your view definition using by the web UI (though you may also do this directly from the Python SDK, as will be shown later).
You can then query the view results by calling the
query method on the
Connection object. Simply pass it the design
and view name.
view_results = client.query("beer", "brewery_beers") for result in view_results: print "Mapped key: %r" % (result.key,) print "Emitted value: %r" % (result.value,) print "Document ID: %s" % (result.docid,)
query method returns a
couchbase.views.iterator.View object, which
is an iterator. You can simply iterate over it to retrieve the
results for the query. Each object yielded is a
ViewRow, which is a simple object containing
the key, value, document ID, and optionally the document itself
for each of the results returned by the view.
In addition to the design and view name, the
query method accepts additional keyword
arguments that control the behavior of the results returned. You
can thus use it as follows:
results = client.query("beer", "brewery_beers", opt1=value1, opt2=value2, ...) for result in results: # do something with result..
Here are some of the available parameters for the
query method. A full listing can be found in
the API documentation.
This boolean parameter indicates whether the corresponding
document should be retrieved for each row fetched. If this
is true, the
doc property of the
ViewRow object yielded by the iterator
query contains a
Result object that contains the document
for the key.
This boolean parameter indicates whether the server should
also pass the results to the view’s
reduce function. An exception is raised
if the view does not have a
This numeric parameter indicates the maximum amount of results to fetch from the query. This parameter is handy if your query can produce a lot of results.
This boolean parameter indicates that the results should be returned in reverse order.
This boolean parameter controls the tradeoff between performance and freshness of data.
This boolean parameter fetches low-level debugging information from the view engine.
This boolean parameter indicates whether the view results should be decoded in a streaming manner. When enabled, the iterator internally fetches chunks of the response as required.
As this is less efficient than fetching all results at once, it is disabled by default, but can be very useful if you have a large dataset because it prevents the entire view from being buffered in memory.
results = client.query("beer", "brewery_beers", include_docs=True, limit=5) for result in results: print "key is %r" % (result.key) doc = result.doc.value if doc['type'] == "beer": print "Got a beer. It's got %0.2f ABV" % (doc['abv'],)