This gem let you easily integrate the Algolia Search API to your favorite ORM. It's based on the algoliasearch-client-ruby gem. Rails 5.x and 6.x are supported.
You might be interested in the sample Ruby on Rails application providing a autocomplete.js-based auto-completion and InstantSearch.js-based instant search results page: algoliasearch-rails-example.
You can find the full reference on Algolia's website.
gem install algoliasearch-rails
Add the gem to your <code>Gemfile</code>:
gem "algoliasearch-rails"
And run:
bundle install
Create a new file <code>config/initializers/algoliasearch.rb</code> to setup your <code>APPLICATION_ID</code> and <code>API_KEY</code>.
AlgoliaSearch.configuration = { application_id: 'YourApplicationID', api_key: 'YourAPIKey' }
The gem is compatible with ActiveRecord, Mongoid and Sequel.
You can configure a various timeout thresholds by setting the following options at initialization time:
AlgoliaSearch.configuration = { application_id: 'YourApplicationID', api_key: 'YourAPIKey', connect_timeout: 2, receive_timeout: 30, send_timeout: 30, batch_timeout: 120, search_timeout: 5 }
This gem makes extensive use of Rails' callbacks to trigger the indexing tasks. If you're using methods bypassing after_validation, before_save or after_commit callbacks, it will not index your changes. For example: update_attribute doesn't perform validations checks, to perform validations when updating use update_attributes.
All methods injected by the AlgoliaSearch module are prefixed by algolia_ and aliased to the associated short names if they aren't already defined.
Contact.algolia_reindex! # <=> Contact.reindex! Contact.algolia_search("jon doe") # <=> Contact.search("jon doe")
The following code will create a <code>Contact</code> index and add search capabilities to your <code>Contact</code> model:
class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch do attributes :first_name, :last_name, :email end end
You can either specify the attributes to send (here we restricted to <code>:first_name, :last_name, :email</code>) or not (in that case, all attributes are sent).
class Product < ActiveRecord::Base include AlgoliaSearch algoliasearch do # all attributes will be sent end end
You can also use the <code>add_attribute</code> method, to send all model attributes + extra ones:
class Product < ActiveRecord::Base include AlgoliaSearch algoliasearch do # all attributes + extra_attr will be sent add_attribute :extra_attr end def extra_attr "extra_val" end end
We provide many ways to configure your index allowing you to tune your overall index relevancy. The most important ones are the searchable attributes and the attributes reflecting record popularity.
class Product < ActiveRecord::Base include AlgoliaSearch algoliasearch do # list of attribute used to build an Algolia record attributes :title, :subtitle, :description, :likes_count, :seller_name # the `searchableAttributes` (formerly known as attributesToIndex) setting defines the attributes # you want to search in: here `title`, `subtitle` & `description`. # You need to list them by order of importance. `description` is tagged as # `unordered` to avoid taking the position of a match into account in that attribute. searchableAttributes ['title', 'subtitle', 'unordered(description)'] # the `customRanking` setting defines the ranking criteria use to compare two matching # records in case their text-relevance is equal. It should reflect your record popularity. customRanking ['desc(likes_count)'] end end
To index a model, simple call reindex on the class:
Product.reindex
To index all of your models, you can do something like this:
Rails.application.eager_load! # Ensure all models are loaded (required in development). algolia_models = ActiveRecord::Base.descendants.select{ |model| model.respond_to?(:reindex) } algolia_models.each(&:reindex)
Traditional search implementations tend to have search logic and functionality on the backend. This made sense when the search experience consisted of a user entering a search query, executing that search, and then being redirected to a search result page.
Implementing search on the backend is no longer necessary. In fact, in most cases it is harmful to performance because of added network and processing latency. We highly recommend the usage of our JavaScript API Client issuing all search requests directly from the end user's browser, mobile device, or client. It will reduce the overall search latency while offloading your servers at the same time.
The JS API client is part of the gem, just require algolia/v3/algoliasearch.min somewhere in your JavaScript manifest, for example in application.js if you are using Rails 3.1+:
//= require algolia/v3/algoliasearch.min
Then in your JavaScript code you can do:
var client = algoliasearch(ApplicationID, Search-Only-API-Key); var index = client.initIndex('YourIndexName'); index.search('something', { hitsPerPage: 10, page: 0 }) .then(function searchDone(content) { console.log(content) }) .catch(function searchFailure(err) { console.error(err); });
We recently (March 2015) released a new version (V3) of our JavaScript client, if you were using our previous version (V2), read the migration guide
Notes: We recommend the usage of our JavaScript API Client to perform queries directly from the end-user browser without going through your server.
A search returns ORM-compliant objects reloading them from your database. We recommend the usage of our JavaScript API Client to perform queries to decrease the overall latency and offload your servers.
hits = Contact.search("jon doe") p hits p hits.raw_answer # to get the original JSON raw answer
A highlight_result attribute is added to each ORM object:
hits[0].highlight_result['first_name']['value']
If you want to retrieve the raw JSON answer from the API, without re-loading the objects from the database, you can use:
json_answer = Contact.raw_search("jon doe") p json_answer p json_answer['hits'] p json_answer['facets']
Search parameters can be specified either through the index's settings statically in your model or dynamically at search time specifying search parameters as second argument of the search method:
class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch do attribute :first_name, :last_name, :email # default search parameters stored in the index settings minWordSizefor1Typo 4 minWordSizefor2Typos 8 hitsPerPage 42 end end
# dynamical search parameters p Contact.raw_search('jon doe', { hitsPerPage: 5, page: 2 })
Even if we highly recommend to perform all search (and therefore pagination) operations from your frontend using JavaScript, we support both will_paginate and kaminari as pagination backend.
To use <code>:will_paginate</code>, specify the <code>:pagination_backend</code> as follow:
AlgoliaSearch.configuration = { application_id: 'YourApplicationID', api_key: 'YourAPIKey', pagination_backend: :will_paginate }
Then, as soon as you use the search method, the returning results will be a paginated set:
# in your controller @results = MyModel.search('foo', hitsPerPage: 10) # in your views # if using will_paginate <%= will_paginate @results %> # if using kaminari <%= paginate @results %>
Use the <code>tags</code> method to add tags to your record:
class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch do tags ['trusted'] end end
or using dynamical values:
class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch do tags do [first_name.blank? || last_name.blank? ? 'partial' : 'full', has_valid_email? ? 'valid_email' : 'invalid_email'] end end end
At query time, specify <code>{ tagFilters: 'tagvalue' }</code> or <code>{ tagFilters: ['tagvalue1', 'tagvalue2'] }</code> as search parameters to restrict the result set to specific tags.
Facets can be retrieved calling the extra facets method of the search answer.
class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch do # [...] # specify the list of attributes available for faceting attributesForFaceting [:company, :zip_code] end end
hits = Contact.search('jon doe', { facets: '*' }) p hits # ORM-compliant array of objects p hits.facets # extra method added to retrieve facets p hits.facets['company'] # facet values+count of facet 'company' p hits.facets['zip_code'] # facet values+count of facet 'zip_code'
raw_json = Contact.raw_search('jon doe', { facets: '*' }) p raw_json['facets']
You can also search for facet values.
Product.search_for_facet_values('category', 'Headphones') # Array of {value, highlighted, count}
This method can also take any parameter a query can take. This will adjust the search to only hits which would have matched the query.
# Only sends back the categories containing red Apple products (and only counts those) Product.search_for_facet_values('category', 'phone', { query: 'red', filters: 'brand:Apple' }) # Array of phone categories linked to red Apple products
More info on distinct for grouping can be found here.
class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch do # [...] # specify the attribute to be used for distinguishing the records # in this case the records will be grouped by company attributeForDistinct "company" end end
Use the <code>geoloc</code> method to localize your record:
class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch do geoloc :lat_attr, :lng_attr end end
At query time, specify <code>{ aroundLatLng: "37.33, -121.89", aroundRadius: 50000 }</code> as search parameters to restrict the result set to 50KM around San Jose.
Each time a record is saved, it will be asynchronously indexed. On the other hand, each time a record is destroyed, it will be - asynchronously - removed from the index. That means that a network call with the ADD/DELETE operation is sent synchronously to the Algolia API but then the engine will asynchronously process the operation (so if you do a search just after,


稳定高效的流量提升解决方案,助力品牌曝光
稳定高效的流量提升解决方案,助力品牌曝光


最新版Sora2模型免费使用,一键生成无水印视频
最新版Sora2模型免费使用,一键生成无水印视频


实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。


选题、配图、成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。


AI辅助编程,代码自动修复
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。


最强AI数据分析助手
小浣熊家族Raccoon,您的AI智能助手,致力于通过先进的人工智能技术,为用户提供高效、便捷的智能服务。无论是日常咨询还是专业问题解答,小浣熊都能以快速、准确的响应满足您的需求,让您的生活更加智能便捷。


像人一样思考的AI智能体
imini 是一款超级AI智能体,能根据人类指令,自主思考、自主完成、并且交付结果的AI智能体。


AI数字人视频创作平台
Keevx 一款开箱即用的AI数字人视频创作平台,广泛适用于电商广告、企业培训与社媒宣传,让全球企业与个人创作者无需拍摄剪辑,就能快速生成多语言、高质量的专业视频。


一站式AI创作平台
提供 AI 驱动的图片、视频生成及数字人等功能,助力创意创作


AI办公助手,复杂任务高效处理
AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!
最新AI工具、AI资讯
独家AI资源、AI项目落地

微信扫一扫关注公众号