Topic: Making Search Results Cacheable

I've deployed a vertical search site based on Rails.  Its works fine, but some db queries take several seconds.  Fortunately the search results are static for several weeks at a time and thus page caching seems like a good solution.  Search parameters are submitted by the user in a form.  Due to all the search parameters to the right of the ? in the url, standard rails page caching doesn't work without making some changes.  I was hoping someone had an elegant way to enable page caching to work in this situation. 

I've considered the following but it seems pretty nasty:
   - setup a named route that puts the search query parameters between slashes instead of to the right of the ?
   - let the user perform a query as today, but instead of the controller action running a search with the contents of params, it instead rewrites the search parameters into a pretty, cacheable url that matches the format of the named route and calls a redirect on this new pretty url
   - a second controller action responds to the named route with the pretty url and actually performs the db query.  Since the pretty url has no params to the right of the ?, its cacheable.
Hopefully there's a better way...



Re: Making Search Results Cacheable

I guess you could write a small caching method. I don't know whether the following is possible.

def cache_object(object, key)
  @@cached_objects = unless @@cached_objects
  @@cached_objects[key] = object

def cached(key)

Key would then be a hash of the query string, so perhaps you could do something like:

key = param[:one]
key << param[:two]
key = md5(key)
result = cached(key) || SomeModel.find(...)
cache_object(result, key)

Very crude.. hope you get my drift. One would also need to implement some expiry.

Otherwise I think the way to go is to use memcached or similar and cache the resultsets there.

Last edited by mrt (2007-07-23 21:09:41)

Re: Making Search Results Cacheable

Thanks the the reply.  Unfortunately neither of those approaches are going to do it - the caching has to work across user sessions otherwise it has no value.  Memcache would work, but is not worth the hastle until my traffic deserved a multi-server configuration.  What I'm looking for is a way to make the url cacheable, then use page caching.

Re: Making Search Results Cacheable

yep.. code should do that.. class variables (not class instance variables) should be available across user sessions.

But please correct me if I am wrong.

However, in development mode they will be reloaded with each request no matter what. In production it should stay until server reload (mongrel or whatever).