Skip to content

Instantly share code, notes, and snippets.

@pfeiffer
Created January 5, 2011 14:02
Show Gist options
  • Save pfeiffer/766348 to your computer and use it in GitHub Desktop.
Save pfeiffer/766348 to your computer and use it in GitHub Desktop.
class SearchSession < ActiveRecord::Base
include Redis::Objects
belongs_to :user
validates :user_id, :presence => true
serialize :conditions, Hash
list :cached_results_ids
after_save :prune_cache
NUM_CACHE_RESULTS = 500
def results
SearchSessionResultSet.new(result_ids)
end
def result_ids
# Check if cached IDs exist, return collection of these
# Fetch IDs from ES
# Cache IDs
# Return collection
unless self.cached_results_ids.any?
hits = User.search_hits({:match_all => true}, {:fields => '_id', :size => NUM_CACHE_RESULTS}) # Only fetch _id field from ElasticSearch
hits.each do |hit|
self.cached_results_ids << hit.id
end
end
self.cached_results_ids
end
def clear!
self.cached_results_ids.clear
end
private
def prune_cache
clear! if conditions_changed?
end
end
######### SearchSessionResultSet ####
class SearchSessionResultSet < Array
def initialize(ids)
@ids = ids
@users = []
@populated = false
end
def before_any_array_method(method, *args)
fill_users_array_according_to_method_and_args
@users.send(method, *args)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment