Skip to content

Litesearch Sequel guide

Mohammad A. Ali edited this page Oct 11, 2023 · 2 revisions

Litesearch provides strong integration with Sequel and makes it pretty simple to use full text indexing and searching in your Sequel powered apps.

Installation

You only need to configure your application to use the litedb Sequel adapter

Usage

Imagine an app with a book and an author models, you can define search index schemas as follows

class Author < Sequel::Model
  one_to_many :books`
  
  include Litesearch::Model

  litesearch do |schema|
    schema.field :name
  end
end

class Book < Sequel::Model
  many_to_one :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 Sequel 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.

Searching the index

You can search individual models, search is integrated in the Sequel query interface

Book.search('author: penguin').limit(10).all
Author.search('penguin').all

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 model objects, they cannot be chained with other AR query methods.

Modifying the index

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 < Sequel::Model
  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

Manipulating the index

You can manipulate the index through the model classes as follows:

Book.rebuild_index!
Book.clear_index!
Book.drop_index!