Skip to content

Instantly share code, notes, and snippets.

@imsickofmaps
Created November 22, 2012 15:08
Show Gist options
  • Save imsickofmaps/4131625 to your computer and use it in GitHub Desktop.
Save imsickofmaps/4131625 to your computer and use it in GitHub Desktop.
MapReduce Challenge - sort by non-key value
{
"5af5c2c8144a11e28f9f001c14010046": {
"category": "clothing",
"available": 20,
"pricefrom": 180.0,
"title": "2-Pack Heart Top",
"created": 1350032036,
"lastUpdated": 1351691717
}
},
"4bce12d2121a11e2934a001c14010046": {
"category": "clothing",
"available": 1,
"pricefrom": 1270.52,
"title": "Tiger Coffee Travel Bag",
"created": 1353511317,
"lastUpdated": 1353511317
}
},
"827dc48c12bd11e2994e001c14010046": {
"category": "clothing",
"available": 1,
"pricefrom": 596.2,
"title": "Cagua Carry All Bag",
"created": 1353411297,
"lastUpdated": 1353511297
}
},
}
Question: How do change the reduce phase to sort (forward or backwards) on the lastUpdated timestamp array column?
import riak
import pprint
# Connect to riak
client = riak.RiakClient(host='127.0.0.1', port=8087, prefix='riak', transport_class=riak.RiakPbcTransport)
query = client.add('test_products') # Set the bucket
arg = {"category": "clothing"} # set the argument
query.map("""
function(v, meta, arg) {
var data = JSON.parse(v.values[0].data);
if (arg.category == data.category) {
return [[v.key, data.lastUpdated]];
} else {
return []
}
}""", {"arg": arg})
query.reduce("function(v, arg) { return v.sort(); }")
products = query.run()
if products is None:
products = []
pprint.pprint(products)
import riak
import pprint
# Connect to riak
client = riak.RiakClient(host='127.0.0.1', port=8087, prefix='riak', transport_class=riak.RiakPbcTransport)
query = client.add('test_products') # Set the bucket
arg = {"category": "clothing"} # set the argument
query.map("""
function(v, meta, arg) {
var data = JSON.parse(v.values[0].data);
if (arg.category == data.category) {
return [v.key];
} else {
return []
}
}""", {"arg": arg})
query.reduce("function(v, arg) { return v.sort(); }")
products = query.run()
if products is None:
products = []
pprint.pprint(products)
@imsickofmaps
Copy link
Author

Answer:

query.reduce("""
    function(v, arg) { return v.sort(
         function(x,y){
             return y[1] - x[1];
         }
    );
}""")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment