algoliasearch-rails

algoliasearch-rails

Rails框架的Algolia搜索集成解决方案

algoliasearch-rails是一个Rails框架的Algolia搜索集成方案。它可与ActiveRecord、Mongoid和Sequel等ORM无缝对接,支持自动索引、异步处理、地理位置搜索和分面搜索等功能。该gem提供了前后端搜索接口,能显著提升Rails应用的搜索性能。对于需要实现高效实时搜索的Rails项目来说,这是一个理想的选择。

AlgoliaRails搜索索引异步Github开源项目
<p align="center"> <a href="https://www.algolia.com"> <img alt="Algolia for Rails" src="https://raw.githubusercontent.com/algolia/algoliasearch-client-common/master/banners/rails.png"/> </a> </p> <h4 align="center">The perfect starting point to integrate <a href="https://algolia.com" target="_blank">Algolia</a> within your Rails project</h4> <p align="center"> <a href="https://circleci.com/gh/algolia/algoliasearch-rails"><img src="https://circleci.com/gh/algolia/algoliasearch-rails.svg?style=shield" alt="CircleCI" /></a> <a href="http://badge.fury.io/rb/algoliasearch-rails"><img src="https://badge.fury.io/rb/algoliasearch-rails.svg" alt="Gem Version"/></a> <a href="https://codeclimate.com/github/algolia/algoliasearch-rails"><img src="https://codeclimate.com/github/algolia/algoliasearch-rails.svg" alt="Code Climate"/></a> <img src="https://img.shields.io/badge/ActiveRecord-yes-blue.svg?style=flat-square" alt="ActiveRecord"/> <img src="https://img.shields.io/badge/Mongoid-yes-blue.svg?style=flat-square" alt="Mongoid"/> <img src="https://img.shields.io/badge/Sequel-yes-blue.svg?style=flat-square" alt="Sequel"/> </p> <p align="center"> <a href="https://www.algolia.com/doc/framework-integration/rails/getting-started/setup/?language=ruby" target="_blank">Documentation</a> • <a href="https://discourse.algolia.com" target="_blank">Community Forum</a> • <a href="http://stackoverflow.com/questions/tagged/algolia" target="_blank">Stack Overflow</a> • <a href="https://github.com/algolia/algoliasearch-rails/issues" target="_blank">Report a bug</a> • <a href="https://www.algolia.com/doc/framework-integration/rails/troubleshooting/faq/" target="_blank">FAQ</a> • <a href="https://www.algolia.com/support" target="_blank">Support</a> </p>

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.

API Documentation

You can find the full reference on Algolia's website.

  1. Setup

  2. Usage

  3. Options

  4. Indices

  5. Testing

  6. Troubleshooting

Setup

Install

gem install algoliasearch-rails

Add the gem to your <code>Gemfile</code>:

gem "algoliasearch-rails"

And run:

bundle install

Configuration

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.

Timeouts

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 }

Notes

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")

Usage

Index Schema

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

Relevancy

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

Indexing

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)

Frontend Search (realtime experience)

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

Backend Search

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 })

Backend Pagination

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 %>

Tags

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.

Faceting

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']

Faceted search

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

Group by

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

Geo-Search

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.

Options

Auto-indexing & asynchronism

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,

编辑推荐精选

Vora

Vora

免费创建高清无水印Sora视频

Vora是一个免费创建高清无水印Sora视频的AI工具

Refly.AI

Refly.AI

最适合小白的AI自动化工作流平台

无需编码,轻松生成可复用、可变现的AI自动化工作流

酷表ChatExcel

酷表ChatExcel

大模型驱动的Excel数据处理工具

基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。

AI工具酷表ChatExcelAI智能客服AI营销产品使用教程
TRAE编程

TRAE编程

AI辅助编程,代码自动修复

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

AI工具TraeAI IDE协作生产力转型热门
AIWritePaper论文写作

AIWritePaper论文写作

AI论文写作指导平台

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

AI辅助写作AI工具AI论文工具论文写作智能生成大纲数据安全AI助手热门
博思AIPPT

博思AIPPT

AI一键生成PPT,就用博思AIPPT!

博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。

AI办公办公工具AI工具博思AIPPTAI生成PPT智能排版海量精品模板AI创作热门
潮际好麦

潮际好麦

AI赋能电商视觉革命,一站式智能商拍平台

潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。

iTerms

iTerms

企业专属的AI法律顾问

iTerms是法大大集团旗下法律子品牌,基于最先进的大语言模型(LLM)、专业的法律知识库和强大的智能体架构,帮助企业扫清合规障碍,筑牢风控防线,成为您企业专属的AI法律顾问。

SimilarWeb流量提升

SimilarWeb流量提升

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

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

Sora2视频免费生成

Sora2视频免费生成

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

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

下拉加载更多