Ordering results

  1. When you query a view, you can provide parameters that indicate the order of results; there are also parameters you use to indicate a start and end for a result set as we described earlier. When you provide these types of query parameters, this is how Couchbase functions:Begin collecting results from the top of the index, or at the start position specified.

  2. Provide one row from the index at a time, until the end of the index, or until the specified end key.

For instance imagine the simplest case where Couchbase Server generates this index based on a view:

KeyValue
0        "foo"
1        "bar"
2        "baz"

We use the Ruby SDK to retrieve all the results in descending order:

doc.foo_bar(:descending => :true )

We query the view named foo_bar and indicate we want the results to be in descending order by providing the :descending parameter set to true. In this case our result set would appear as follows:

KeyValue
2        "baz"
1        "bar"
0        "foo"

Imagine we want to provide another query parameter along with the :descending, such as a start key. In this case our query would look like this in Ruby:

doc.foo_bar(:descending => :true, :start_key => 1)

Here our result set would look like this:

KeyValue
1        "bar"
0        "foo"

This might not be what you expected: when you indicated the start key, you probably expected the last two items in the index sorted in descending order. But when you specify the order :descending to be true, Couchbase Server will read index items from the bottom of the index upwards. Therefore you get the items in position 1 then 0 from the index. To get the results in position 1 and 2, you would invert the logic of your query and use the :endkey parameter set to 1:

doc.foo_bar(:descending => :true, :end_key => 1)

In this case Couchbase Server will start reading items at the last position of 2, and then add the item from position 1. Your result set will appear as follows:

KeyValue
2        "baz"
1        "bar"

Couchbase Server sorts results in ascending or descending order based on the value of the key; for instance if you sort in ascending order, keys starting with ‘a’ will be in a higher position than those starting with ‘c’. For more information about sorting rules and values in Couchbase Server, see ordering.