Skip to content

Instantly share code, notes, and snippets.

@Epigene
Created October 13, 2014 12:56
Show Gist options
  • Save Epigene/1e79d6ca3a24f6f4d251 to your computer and use it in GitHub Desktop.
Save Epigene/1e79d6ca3a24f6f4d251 to your computer and use it in GitHub Desktop.
pg_search install
========= pg_search Workflow =========
# add to gemfile and bundle
gem 'pg_search', '0.7.8' # # Empowers PostgreSQL-driven ActiveRecord
# setup addon migrations
rails g migration add_contrib_extensions
class AddContribExtensions < ActiveRecord::Migration
def up
execute 'CREATE EXTENSION pg_trgm;'
execute 'CREATE EXTENSION fuzzystrmatch;'
end
end
# initialize multitable
rails g pg_search:migration:multisearch
# Setup dmetaphone
rails g pg_search:migration:dmetaphone
rake db:migrate
# configure model(s)
class Article
include PgSearch
multisearchable against: [:title, :body] # multisearchable against: :title
end
# OR if single entry
class Article
include PgSearch
pg_search_scope :search_by_title,
:against => :title,
end
pg_search_scope :kinda_matching,
:against => :text,
:using => {
tsearch: {dictionary: 'english'},
trigram: {threshold: 0.1},
dmetaphone: {}
},
:ignoring => :accents
# BlogPost.create!(:title => "Recent Developments in the World of Pastrami")
# BlogPost.create!(:title => "Prosciutto and You: A Retrospective")
# BlogPost.search_by_title("pastrami") # => [#<BlogPost id: 2, title: "Recent Developments in the World of Pastrami">]
# create init file in root
$ touch config/initializers/pg_search.rb :
PgSearch.multisearch_options = {
using: {
tsearch: {dictionary: 'english'},
trigram: {threshold: 0.1},
dmetaphone: {}
}
:ignoring => :accents
}
# USAGE
odyssey = EpicPoem.create!(:title => "Odyssey", :author => "Homer")
rose = Flower.create!(:color => "Red")
PgSearch.multisearch("Homer") #=> [#<PgSearch::Document searchable: odyssey>]
BlogPost.search_by_title("pastrami")
# Rebuilding index once in a while
rake pg_search:multisearch:rebuild[Initiative]
# as a method
PgSearch::Multisearch.rebuild(Product)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment