Skip to content

Instantly share code, notes, and snippets.

@floere
Created July 18, 2012 02:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save floere/3133802 to your computer and use it in GitHub Desktop.
Save floere/3133802 to your computer and use it in GitHub Desktop.
A 5 minute implementation of facets on Picky.
# Run using
# ruby facets.rb
#
require 'picky'
# Define index.
#
data = Picky::Index.new :models do
category :id
category :name
category :surname
end
# Add data.
#
data.replace_from id: 1, name: 'Picky', surname: 'McNamara'
data.replace_from id: 2, name: 'Florian', surname: 'Hanke'
data.replace_from id: 3, name: 'Tentacles', surname: 'Jellyfish'
data.replace_from id: 4, name: 'Tentacles', surname: 'Florian'
data.replace_from id: 5, name: 'Florian', surname: 'Tentacles'
# Look facets up in the index.
#
puts data[:name].exact.inverted.map { |name, ids|
[name, ids.size]
}
# Add convenience method.
#
class Picky::Index
def facets category
self[category].exact.inverted.inject({}) { |result, token_ids|
token, ids = token_ids
result[token] = ids.size
result
}
end
end
# Use convenience method.
#
puts data.facets :name # => {"picky"=>1, "florian"=>2, "tentacles"=>2}
puts data.facets :surname # => {"mcnamara"=>1, "hanke"=>1, "jellyfish"=>1, "florian"=>1, "tentacles"=>1}
# Query generation.
#
puts "Queries: (with original query 'something')"
queries = data.facets(:name).map do |token, _|
"name:#{token} something"
end
puts queries
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment