Map/Reduce Views are used to create queryable, secondary indexes in Couchbase Server. The primary index for documents is the key you use when performing the standard CRUD methods described above. See the view documentation for more information on writing views.
For this example, a by_name view in a beer design document will be queried. This view simply checks whether a document is a beer and has a name. If it does, it emits the beer's name into the index. This view will allow for beers to be queried for by name. For example, it's now possible to ask the question "What beers start with A?"
function (doc, meta) { if (doc.type && doc.type == "beer" && doc.name) { emit(doc.name, null); } }
Querying a view through the Python client is performed through the view method.
view = bucket.view("_design/beer/_view/by_name")The view method returns a list with dictionary entries for each row in the view's results. Iterating over the results of the view, the "id" property of the row (currently the unicode id must be converted to an ASCII string) can be used to retrieve the original document.
for row in view: id = row["id"].__str__() beer = json.loads(bucket.get(id)[2]) print beer["name"]
Finally, the view results can be modified by specifying keyword arguments when first calling the view method.
view = bucket.view("_design/beer/_view/by_name", limit=10, key="Sundog")