A newer version of this documentation is available.

View Latest

MapReduce Views Using the Go SDK with Couchbase Server

    You can use MapReduce views to create queryable secondary indexes in Couchbase Server.

    The normal CRUD methods allow you to look up a document by its ID. A MapReduce (view query) allows you to look up one or more documents based on various criteria. MapReduce views are comprised of a map function that is executed once per document (this is done incrementally, so this is not run each time you query the view) and an optional reduce function that performs aggregation on the results of the map function. The map and reduce functions are stored on the server and written in JavaScript.

    MapReduce queries can be further customized during query time to allow only a subset (or range) of the data to be returned.

    See the Incremental MapReduce Views and Querying Data with Views sections of the general documentation to learn more about views and their architecture.

    The following example is the definition of a by_name view in a "beer" design document. This view 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 allows 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 views through the Go SDK

    Querying a view through the Go SDK is performed through the ViewQuery interface that is instantiated through the NewViewQuery method of the gocb library.

    myQuery := gocb.NewViewQuery("beer", "by_name")

    The ViewQuery interface enables you to query the view and specify various available options for the query. Once you have the query ready for execution, pass it to the ExecuteViewQuery method of the your Bucket instance:

    rows, err := myBucket.ExecuteViewQuery(myQuery)
    if err != nil {
            fmt.Printf("View query error: %s\n", err)
    var row interface{}
    for rows.Next(&row) {
            fmt.Printf("Row: %+v\n", row)
    if err := rows.Close(); err != nil {
            fmt.Printf("View query results error: %s\n", err)

    You can modify your view results by specifying various options before executing the query method. Here is an example that skips the first six items and limits the results to three items:

    myQuery = gocb.NewViewQuery("beer", "by_name").Skip(6).Limit(3)