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,
字节跳动发布的AI编程神器IDE
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。
AI小说写作助手,一站式润色、改写、扩写
蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。
全能AI智能助手,随时解答生活与工作的多样问题
问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。
实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。
一键生成PPT和Word,让学习生活更轻松
讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。
深度推理能力全新升级,全面对标OpenAI o1
科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。
一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型
Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。
AI助力,做PPT更简单!
咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。
选题、配图、成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。
专业的AI公文写作平台,公文写作神器
AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。
最新AI工具、AI资讯
独家AI资源、AI项目落地
微信扫一扫关注 公众号