Search code examples
indexingmaxriak

Finding maximum value for numeric secondary index in Riak


Given a numeric secondary index in Riak I can do range queries, like:

"Find me all values* with index "sn" between 1 and 10".

Is there a way to find the maximum value for a numeric index? I.e.

"Find me a maximum value of index "sn".

* It actually finds all primary keys (not the values themselves), but here it does not matter.


Solution

  • No, you can't ask Riak to give you the maximum value for the 2i. You will have to execute a map/reduce job and parse each 2i value which includes a reduce job to find the maximum.

    If this is an important part of your application there are other ways you can get around the problem. Once you find the maximum you can add a secondary index to the value which indicates that it's the maximum. If the maximum value changes over time you could:

    • Map/reduce over the bucket where the 2i for maxval_int is 1.
    • If there's only one result, return it.
    • If there are multiple results, reduce to find the max.
    • Remove the maxval_int index from each object that is no longer the maximum.
    • When adding new values check against the current maximum value, update indexes accordingly.

    The little read-repair-like function is there to handle cases where nodes in your cluster are partitioned.

    HTH.