Skip to content

Views Query CouchDB using Scala

debasishg edited this page Sep 13, 2010 · 1 revision

CouchDB Views

One of the biggest hits of CouchDB is the view engine that uses the power of MapReduce to fetch data to the users. The current version of the framework does not offer much in terms of view creation apart from basic abstractions that allow plugging in “map” and “reduce” functions in Javascript to the design document. There are some plans to make this more Scala ish with little languages that will enable map and reduce function generation from Scala objects.

But what it offers today is a small DSL that enables building up view queries along with the sea of options that CouchDB server offers ..

// fetches records from the view named least_cost_lunch
http(test view(Views.builder("lunch/least_cost_lunch").build))

// fetches records from the view named least_cost_lunch 
// using key and limit options
couch(test view(
  Views.builder("lunch/least_cost_lunch")
       .options(optionBuilder key(List("apple", 0.79)) limit(10) build)
       .build))

// fetches records from the view named least_cost_lunch 
// using specific keys and other options for deciding output filters
http(test view(
  Views.builder("lunch/least_cost_lunch")
       .options(optionBuilder descending(true) limit(10) build)
       .keys(List(List("apple", 0.79), List("banana", 0.79)))
       .build))

// temporary views
val mf = 
  """function(doc) {
       var store, price;
       if (doc.item && doc.prices) {
         for (store in doc.prices) {
           price = doc.prices[store];
           emit(doc.item, price);
         }
       }
  }"""

val rf = 
  """function(key, values, rereduce) {
       return(sum(values))
  }"""

// with grouping
val aq = 
  Views.adhocBuilder(View(mf, rf))
       .options(optionBuilder group(true) build)
       .build
val s = http(test adhocView(aq))
s.size should equal(3)

// without grouping
val aq_1 = 
  Views.adhocBuilder(View(mf, rf))
       .build
val s_1 = http(test adhocView(aq_1))
s_1.size should equal(1)