Skip to content

Instantly share code, notes, and snippets.

@scalabl3
Created December 13, 2012 07:46
Show Gist options
  • Save scalabl3/4274831 to your computer and use it in GitHub Desktop.
Save scalabl3/4274831 to your computer and use it in GitHub Desktop.
Example of a Range Query to query on two properties

Document Examples we'll Index (Map/Reduce)

Document #1 (key: mobie::001)

{
  doctype: "mobie",
  year: 2002,
  rating: 3
}

Document #2 (key: mobie::002)

{
  doctype: "mobie",
  year: 2002,
  rating: 1
}

Document #3 (key: mobie::003)

{
  doctype: "mobie",
  year: 2003,
  rating: 2
}

Map Function

Every document gets run through the map function, in this case, only documents that are JSON and have the doctype of mobie (your application code set the doctype property for that document (likely your class name)).

function(doc, meta) {
  if (meta.type == "json" && doc.doctype == "mobie") {
    emit([year, rating], null)
  } 
}

Map Results

The resulting Index (like a table) and the key of the document this came from. You are only indexing specific properties here, so you can "get" the document to retrieve the full document/object based on your query results keys.

1: [2002,1] (mobie::002)
2: [2002,3] (mobie::001)
3: [2003,2] (mobie::003)

Range Query

If you notice in a compound index key, it is ordered by the elements of the array. Now you can query that View (Map/Reduce), with a range query by using a startkey and endkey, and because it's ordered, that's how you accomplish the mobie.year == xxxx and mobie.rating > 2

startkey=[2002,2]
endkey=[2002,5]

Range Query Results

In this case since the range is from 2002 to 2002, and rating is from 2 to 5 (or > 2 basically if you change 5 to 9999 or whatever you want) you return only one result from the examples.

[2002,3] (mobie::001)

If we change the range to this:

startkey=[2002,2]
endkey=[2003,5]

We will get these results for that query:

[2002,3] (mobie::001)
[2003,2] (mobie::003)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment