Skip to content

Instantly share code, notes, and snippets.

@frankie-loves-jesus
Last active August 29, 2015 14:01
Show Gist options
  • Save frankie-loves-jesus/dab333cff524b0f993af to your computer and use it in GitHub Desktop.
Save frankie-loves-jesus/dab333cff524b0f993af to your computer and use it in GitHub Desktop.
pg_search

Cool pg_search stats

Attempt to display some cool search stats using pg_search. About 759,000,000 results (0.29 seconds), Searches related to <keyword>: <keyword> <keyword> <keyword> etc.

Hi,

Here's a gist which sketches a very basic implementation. There are some shortcomings, but I hope it's clear how to tweak and extend it to fit your purposes. I'm not sure how to get ActiveRecord to return the duration of a single query, which is why I set the @duration to the "realtime" benchmark of the whole time spent in ActiveRecord. You may be able to do something hacky with ActiveSupport::Notifications, but I opted for an easy-to-understand solution over a technically precise solution.

P.S. the Case Commons Development Google Group is quite helpful for all things pg_search, and I'm sure they have more intelligent things to say than I!

Best, Brian

<p>About <%= @rough_count %> results (<%= @duration.round(2) %> seconds)</p>
<p>Searches related to "<%= @term %>": </p>
require 'benchmark'
module ResultsCount
def rough_count(count)
rounded_digits = String(count).size / 2
rounding_factor = 10 ** rounded_digits
(Integer(count) / rounding_factor) * rounding_factor
end
end
class SearchController < ApplicationController
include ResultsCount
def index
@term = params.require(:term)
@duration = Benchmark.realtime do
@scope = PgSearch.multisearch(@term)
@results = @scope.page(params.fetch(:page, 1))
end
@rough_count = rough_count(@scope.count)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment