Ruby on Rails 的 Meilisearch 集成
Meilisearch Rails
Meilisearch | Meilisearch Cloud | Documentation | Discord | Website | FAQ
⚡ The Meilisearch integration for Ruby on Rails
Meilisearch Rails is the Meilisearch integration for Ruby on Rails developers.
Meilisearch is an open-source search engine. Learn more about Meilisearch.
The whole usage of this gem is detailed in this README.
To learn more about Meilisearch, check out our Documentation or our API References.
This package guarantees compatibility with version v1.x of Meilisearch, but some features may not be present. Please check the issues for more info.
This package requires Ruby version 3.0 or later and Rails 6.1 or later. It may work in older versions but it is not officially supported.
With gem in command line:
gem install meilisearch-railsIn your Gemfile with bundler:
source 'https://rubygems.org'
gem 'meilisearch-rails'⚡️ Launch, scale, and streamline in minutes with Meilisearch Cloud—no maintenance, no commitment, cancel anytime. Try it free now.
Prefer to self-host? Download and deploy our fast, open-source search engine on your own infrastructure.
Create a new file config/initializers/meilisearch.rb to setup your MEILISEARCH_HOST and MEILISEARCH_API_KEY
Meilisearch::Rails.configuration = {
meilisearch_url: ENV.fetch('MEILISEARCH_HOST', 'http://localhost:7700'),
meilisearch_api_key: ENV.fetch('MEILISEARCH_API_KEY', 'YourMeilisearchAPIKey')
}Or you can run a rake task to create the initializer file for you:
bin/rails meilisearch:installThe gem is compatible with ActiveRecord, Mongoid and Sequel.
⚠️ Note that even if you want to use all the default options, you must declare an empty meilisearch block in your model.
The following code will create a Book index and add search capabilities to your Book model.
class Book {"id"=>"1", "name"=>"Harry Potter", "description"=>… Don't forget that attributes_to_highlight, attributes_to_crop, and
crop_length can be set up in the meilisearch block of your model.
As an example of how to use the sort option, here is how you could achieve returning all books sorted by title in ascending order:
Book.search('*', sort: ['title:asc']) Don't forget to set up the sortable_attributes option in the meilisearch block of your model.
Meilisearch supports searching multiple models at the same time (see Custom search for search options):
multi_search_results = Meilisearch::Rails.multi_search(
Book => { q: 'Harry' },
Manga => { q: 'Attack' }
)Use #each_result to loop through pairs of your provided keys and the results:
Books
Harry Potter and the Philosopher's Stone
Harry Potter and the Chamber of Secrets
Mangas
Attack on Titan
Records are loaded when the keys are models, or when :scope option is passed:
multi_search_results = Meilisearch::Rails.multi_search(
# scope may be a relation
'books' => { q: 'Harry', scope: Book.all },
# or a model
'mangas' => { q: 'Attack', scope: Manga }
)Otherwise, hashes are returned.
The index to search is inferred from the model if the key is a model, if the key is a string the key is assumed to be the index unless the :index_uid option is passed:
multi_search_results = Meilisearch::Rails.multi_search(
'western' => { q: 'Harry', scope: Book, index_uid: 'books_production' },
'japanese' => { q: 'Attack', scope: Manga, index_uid: 'mangas_production' }
)You can search the same index multiple times by specifying :index_uid:
query = 'hero'
multi_search_results = Meilisearch::Rails.multi_search(
'Isekai Manga' => { q: query, scope: Manga, filters: 'genre:isekai', index_uid: 'mangas_production' }
'Shounen Manga' => { q: query, scope: Manga, filters: 'genre:shounen', index_uid: 'mangas_production' }
'Steampunk Manga' => { q: query, scope: Manga, filters: 'genre:steampunk', index_uid: 'mangas_production' }
)DEPRECATED: You used to be able to iterate through a flattened collection with .each:
Harry Potter and the Philosopher's Stone
J. K. Rowling
Harry Potter and the Chamber of Secrets
J. K. Rowling
Attack on Titan
Iseyama
But this has been deprecated in favor of federated search.
See the official multi search documentation.
Federated search is similar to multi search, except that results are not grouped but sorted by ranking rules.
results = Meilisearch::Rails.federated_search(
queries: [
{ q: 'Harry', scope: Book.all },
{ q: 'Attack on Titan', scope: Manga.all }
]
)An enumerable FederatedSearchResult is returned, which can be iterated through with #each:
Attack on Titan
Harry Potter and the Philosopher's Stone
Harry Potter and the Chamber of Secrets
The queries parameter may be a multi-search style hash with keys that are either classes, index names, or neither:
results = Meilisearch::Rails.federated_search(
queries: {
Book => { q: 'Harry' },
Manga => { q: 'Attack on Titan' }
}
)results = Meilisearch::Rails.federated_search(
queries: {
'books_production' => { q: 'Harry', scope: Book.all },
'mangas_production' => { q: 'Attack on Titan', scope: Manga.all }
}
)results = Meilisearch::Rails.federated_search(
queries: {
'potter' => { q: 'Harry', scope: Book.all, index_uid: 'books_production' },
'titan' => { q: 'Attack on Titan', scope: Manga.all, index_uid: 'mangas_production' }
}
)Records are loaded when the :scope option is passed (may be a model or a relation),
or when a hash query is used with models as keys:
results = Meilisearch::Rails.federated_search(
queries: [
{ q: 'Harry', scope: Book },
{ q: 'Attack on Titan', scope: Manga },
]
)results = Meilisearch::Rails.federated_search(
queries: {
Book => { q: 'Harry' },
Manga => { q: 'Attack on Titan' }
}
)If the model is not provided, hashes are returned!
Any relation passed as :scope is used as the starting point when loading records:
results = Meilisearch::Rails.federated_search(
queries: [
{ q: 'Harry', scope: Book.where('year 0,
# "limit" => 20,
# "offset" => 0,
# "estimatedTotalHits" => 2,
# "semanticHitCount": 0
# }The metadata contains facet stats and pagination stats, among others. See the full response in the documentation.
More details on federated search (such as available federation: options) can be found on the official multi search documentation.
kaminari or will_paginateThis gem supports:
Specify the :pagination_backend in the configuration file:
Meilisearch::Rails.configuration = {
meilisearch_url: 'YourMeilisearchUrl',
meilisearch_api_key: 'YourMeilisearchAPIKey',
pagination_backend: :kaminari # :will_paginate
}Then, as soon as you use the search method, the returning results will be paginated:
# controller
@hits = Book.search('harry potter')
# views
# if using kaminari
# if using will_paginateThe number of hits per page defaults to 20, you can customize it by adding the hits_per_page parameter to your search:
Book.search('harry potter', hits_per_page: 10)pagyThis gem supports pagy to paginate your search results.
To use pagy with your meilisearch-rails you need to:
Add the pagy gem to your Gemfile.
Create a new initializer pagy.rb with this:
# config/initializers/pagy.rb
require 'pagy/extras/meilisearch'Then in your model you must extend Pagy::Meilisearch:
class Book :warning: There is no need to set pagination_backend in the configuration block Meilisearch::Rails.configuration for pagy.
Check ddnexus/pagy for more information.
By default, HTTP connections to the Meilisearch URL are always active, but sometimes you want to disable the HTTP requests in a particular moment or environment.
you have multiple ways to achieve this.
By adding active: false in the configuration initializer:
Meilisearch::Rails.configuration = {
meilisearch_url: 'YourMeilisearchUrl',
meilisearch_api_key: 'YourMeilisearchAPIKey',
active: false
}Or you can disable programmatically:
Meilisearch::Rails.deactivate! # all the following HTTP calls will be dismissed.
# or you can pass a block to it:
Meilisearch::Rails.deactivate! do
# every Meilisearch call here will be dismissed, no error will be raised.
# after the block, Meilisearch state will be active.
endYou can also activate if you deactivated earlier:
Meilisearch::Rails.activate!暂无开放 Issues,或尚未同步最近议题。