-
Notifications
You must be signed in to change notification settings - Fork 66
Litesearch ActiveRecord Guide
Litesearch provides strong integration with ActiveRecord and makes it pretty simple to use full text indexing and searching in your Rails apps.
You only need to configure your application to use the litedb ActiveRecord adapter
Imagine an app with a book and an author models, you can define search index schemas as follows
class Author < ActiveRecord::Base
has_many :books`
include Litesearch::Model
litesearch do |schema|
schema.field :name
end
end
class Book < ActiveRecord::Base
belongs_to :author
include Litesearch::Model
litesearch do |schema|
schema.fields [:publishing_year, :description] # these fields has a weight of 1
schema.field :title, weight: 5 # higher weight field
schema.field :ISBN, col: :isbn_code # a field mapping to a different column name
schema.field :author, target: 'auhtors.name', col: :author_id
schema.filter_column :indexed # a column (can be virtual, with any expression) whose value (true or false) determines whether to index or not
end
end
Modifying records through the AR interface (or even directly through INSERT, UPDATE or DELETE statements against the database) will automatically update the index content and allow you to search them.
You can search individual models, search is integrated in the AR query interface
Book.search('author: penguin').limit(10)
Author.search('penguin')
You can also search for multiple, or all models at once
# search all models, from any model
Book.search_all('penguin', limit: 50)
# search specific models, also from any model
Book.search_all('penguin', models: [Author])
The results of #search_all are actual arrays of AR objects, they cannot be chained with other AR query methods.
You can change the index schema as it is defined in the model class, you can change column weights, add columns, and set columns to zero weights to exclude them from insertion and search results and remove them completely after a rebuild
class Book < ActiveRecord::Base
belongs_to :author
belongs_to :publisher
include Litesearch::Model
litesearch do |schema|
schema.fields [:publishing_year, :description]
schema.field :title, weight: 1 # weight change
schema.field :author, target: 'auhtors.name', col: :author_id
schema.field :publisher, target: 'publishers.name' # col is optional if it is {field_name}_id
end
end
You can manipulate the index through the model classes as follows:
Book.rebuild_index!
Book.clear_index!
Book.drop_index!