Skip to content

Instantly share code, notes, and snippets.

@sideshowcoder
Created July 11, 2014 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sideshowcoder/97051089965477166ba8 to your computer and use it in GitHub Desktop.
Save sideshowcoder/97051089965477166ba8 to your computer and use it in GitHub Desktop.
Couchbase View Query example key prefix matching
var couchbase = require("couchbase")
var async = require("async")
var bucket = new couchbase.Connection({})
function die(msg) {
if(msg) console.log(msg)
bucket.shutdown()
process.exit()
}
/* documents
* [
* { type: "hero", name: "superman", number: 1 },
* { type: "hero", name: "spiderman", number: 2 },
* { type: "hero", name: "batman", number: 3 },
* { type: "hero", name: "superman", number: 4 },
* ]
*/
/* views
*
* numbered_heros
*
* function(doc, meta) {
* if (doc.type === "hero") {
* emit([doc.number, doc.name], null)
* }
* }
*
* heros_numbered
*
* function(doc, meta) {
* if (doc.type === "hero") {
* emit([doc.name, doc.number], null)
* }
* }
*/
async.series([
function (cb) {
var options = {
startkey: [1, "superman"],
endkey: [9, "superman"]
}
var q = bucket.view("heros", "numbered_heros", options)
q.query(function (err, results) {
if(err) die(err)
console.log("key structure [number, name] startkey [1, superman], endkey [9,superman]\n")
console.log(results)
cb()
})
},
function (cb) {
var options = {
startkey: ["superman"],
endkey: ["superman", "ZZ"] // ZZ is higher thant the highest number
}
var q = bucket.view("heros", "heros_numbered", options)
q.query(function (err, results) {
if(err) die(err)
console.log("key structure [name, number] startkey [superman], endkey [superman]\n")
console.log(results)
cb()
})
},
bucket.shutdown.bind(bucket)
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment