Skip to content

Instantly share code, notes, and snippets.

@dzello
Last active December 18, 2015 17:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dzello/5816332 to your computer and use it in GitHub Desktop.
Save dzello/5816332 to your computer and use it in GitHub Desktop.
A simple Ruby script illustrating how to implement Redis-style ZRANK on the result of a Keen IO group_by query
# Example Keen IO API response for a count, grouped by an 'entry' field
keen_result = [
{
"entry" => "Apple",
"result" => 15
},
{
"entry" => "Orange",
"result" => 10
},
{
"entry" => "Grape",
"result" => 5
},
{
"entry" => "Pear",
"result" => 7
}
]
# flatten the API response into a single hash
# e.g. {"Apple"=>15, "Orange"=>10, "Grape"=>5, "Pear"=>7}
flat_hash = keen_result.inject({}) { |acc, entry|
acc[entry["entry"]] = entry["result"]; acc
}
# create a 'set', sorted by the entry count
# e.g. [["Grape", 5], ["Pear", 7], ["Orange", 10], ["Apple", 15]]
sorted_set = flat_hash.sort_by { |entry, count| count }
# given an sorted array of pairs, find the index of the pair
# whose value matches the 'entry' param
def zrank(entry, set)
set.each_with_index { |pair, index|
return index if entry == pair[0]
}
end
puts "Apple: #{zrank("Apple", sorted_set)}" #=> 3
puts "Orange: #{zrank("Orange", sorted_set)}" #=> 2
puts "Grape: #{zrank("Grape", sorted_set)}" #=> 0
puts "Pear: #{zrank("Pear", sorted_set)}" #=> 1
@dzello
Copy link
Author

dzello commented Jun 19, 2013

The Keen IO API doesn't have a formal ZRANK operation but it's fairly easy to implement using the response of a group by query.

@mikejholly
Copy link

Thanks :)

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