Book Image

Couchbase Essentials

Book Image

Couchbase Essentials

Overview of this book

Table of Contents (15 chapters)
Couchbase Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Multiple keys per document


The preceding map function we just wrote has a limitation—it will identify only those last names where the desired name appears before the hyphen. Therefore, the last name Van Der Beek-Moody would not be found. To address this issue, we could query a second time, with the startkey and endkey parameters reversed from our previous query. However, there is a better way.

There is no rule that a document must have only one key per row in an index. Therefore, we can rewrite our index to emit an index row for every possible last name. In this example, a possible last name is anything appearing before or after a hyphen:

function(doc, meta) {
  if (doc.type == "user" && doc.lastName) {
    var parts = doc.lastName.split("-");
    for(vari = 0; i<parts.length; i++) {
      emit(parts[i], null);
    }
  }
}

In this new map function, we use JavaScript's string split() function to return each of the names contained in a last name. For each match name we find, we send...