Last active
December 18, 2015 17:09
-
-
Save joshed-io/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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.