ドキュメント • コミュニティ フォーラム • スタック オーバーフロー • バグの報告 • FAQ • サポート
この gem を使用すると、Algolia Search API をお気に入りの ORM に簡単に統合できます。これは algoliasearch-client-ruby gem に基づいています。 Rails 6.x および 7.x がサポートされています。
autocomplete.js
ベースのオートコンプリートとInstantSearch.js
ベースのインスタント検索結果ページを提供するサンプル Ruby on Rails アプリケーション (algoliasearch-rails-example) に興味があるかもしれません。
完全なリファレンスは Algolia の Web サイトでご覧いただけます。
設定
使用法
オプション
objectID
指数
テスト
トラブルシューティング
gem install algoliasearch-rails
gem をGemfile
に追加します。
gem "algoliasearch-rails"
そして実行します:
bundle install
新しいファイルconfig/initializers/algoliasearch.rb
を作成して、 APPLICATION_ID
とAPI_KEY
設定します。
AlgoliaSearch . configuration = { application_id : 'YourApplicationID' , api_key : 'YourAPIKey' }
この宝石は、ActiveRecord、Mongoid、Sequel と互換性があります。
初期化時に次のオプションを設定することで、さまざまなタイムアウトしきい値を構成できます。
AlgoliaSearch . configuration = {
application_id : 'YourApplicationID' ,
api_key : 'YourAPIKey' ,
}
この gem は、Rails のコールバックを広範囲に利用して、インデックス作成タスクをトリガーします。 after_validation
、 before_save
、またはafter_commit
コールバックをバイパスするメソッドを使用している場合、変更のインデックスは作成されません。例: update_attribute
検証チェックを実行しません。更新時に検証を実行するには、 update_attributes
を使用します。
AlgoliaSearch
モジュールによって挿入されるすべてのメソッドには、プレフィックスalgolia_
が付けられ、まだ定義されていない場合は、関連する短縮名にエイリアスが付けられます。
Contact . algolia_reindex! # <=> Contact.reindex!
Contact . algolia_search ( "jon doe" ) # <=> Contact.search("jon doe")
次のコードは、 Contact
インデックスを作成し、 Contact
モデルに検索機能を追加します。
class Contact < ActiveRecord :: Base
include AlgoliaSearch
algoliasearch do
attributes :first_name , :last_name , :email
end
end
送信する属性を指定することも (ここでは:first_name, :last_name, :email
に制限します)、指定しないこともできます (その場合、すべての属性が送信されます)。
class Product < ActiveRecord :: Base
include AlgoliaSearch
algoliasearch do
# all attributes will be sent
end
end
add_attribute
メソッドを使用して、すべてのモデル属性と追加の属性を送信することもできます。
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
全体的なインデックスの関連性を調整できるように、インデックスを構成するさまざまな方法が提供されています。最も重要なものは、検索可能な属性とレコードの人気を反映する属性です。
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
モデルにインデックスを付けるには、クラスでreindex
呼び出すだけです。
Product . reindex
すべてのモデルにインデックスを付けるには、次のようなことを実行できます。
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 )
従来の検索実装では、検索ロジックと機能がバックエンドにある傾向があります。これは、ユーザーが検索クエリを入力し、その検索を実行し、検索結果ページにリダイレクトされるという検索エクスペリエンスで構成される場合には、当然のことです。
バックエンドで検索を実装する必要はなくなりました。実際、ほとんどの場合、ネットワークと処理の遅延が増加するため、パフォーマンスに悪影響を及ぼします。すべての検索リクエストをエンド ユーザーのブラウザ、モバイル デバイス、またはクライアントから直接発行する JavaScript API クライアントの使用を強くお勧めします。これにより、全体的な検索遅延が短縮され、同時にサーバーの負荷が軽減されます。
JS API クライアントは gem の一部です。たとえば、Rails 3.1 以降を使用している場合はapplication.js
など、JavaScript マニフェストのどこかでalgolia/v3/algoliasearch.min
を要求するだけです。
//= require algolia/v3/algoliasearch.min
次に、JavaScript コードで次のことを実行できます。
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 ) ;
} ) ;
最近 (2015 年 3 月) JavaScript クライアントの新しいバージョン (V3) をリリースしました。以前のバージョン (V2) を使用していた場合は、移行ガイドをお読みください。
注:サーバーを経由せずにエンドユーザーのブラウザから直接クエリを実行するには、JavaScript API クライアントを使用することをお勧めします。
検索すると、ORM 準拠のオブジェクトが返され、データベースから再ロードされます。全体的な待ち時間を短縮し、サーバーの負荷を軽減するために、JavaScript API クライアントを使用してクエリを実行することをお勧めします。
hits = Contact . search ( "jon doe" )
p hits
p hits . raw_answer # to get the original JSON raw answer
それぞれの ORM オブジェクトに、 highlight_result
属性が追加されます。
hits [ 0 ] . highlight_result [ 'first_name' ] [ 'value' ]
データベースからオブジェクトを再ロードせずに、API から生の JSON 応答を取得したい場合は、以下を使用できます。
json_answer = Contact . raw_search ( "jon doe" )
p json_answer
p json_answer [ 'hits' ]
p json_answer [ 'facets' ]
検索パラメーターは、モデル内のインデックスの設定を通じて静的に指定することも、 search
メソッドの 2 番目の引数として検索パラメーターを指定して検索時に動的に指定することもできます。
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 } )
JavaScript を使用してフロントエンドからすべての検索 (したがってページネーション) 操作を実行することを強くお勧めしますが、ページネーション バックエンドとして will_paginate と Kaminari の両方をサポートします。
:will_paginate
を使用するには、次のように:pagination_backend
を指定します。
AlgoliaSearch . configuration = { application_id : 'YourApplicationID' , api_key : 'YourAPIKey' , pagination_backend : :will_paginate }
その後、 search
メソッドを使用するとすぐに、返される結果はページ分割されたセットになります。
# 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
メソッドを使用してレコードにタグを追加します。
class Contact < ActiveRecord :: Base
include AlgoliaSearch
algoliasearch do
tags [ 'trusted' ]
end
end
または動的値を使用します。
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
クエリ時に、検索パラメータとして{ tagFilters: 'tagvalue' }
または{ tagFilters: ['tagvalue1', 'tagvalue2'] }
を指定して、結果セットを特定のタグに制限します。
ファセットは、検索回答の追加facets
メソッドを呼び出して取得できます。
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' ]
ファセット値を検索することもできます。
Product . search_for_facet_values ( 'category' , 'Headphones' ) # Array of {value, highlighted, count}
このメソッドは、クエリが取得できる任意のパラメータも取得できます。これにより、クエリに一致するヒットのみに検索が調整されます。
# 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
グループ化のための個別の詳細については、ここを参照してください。
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
geoloc
メソッドを使用してレコードをローカライズします。
class Contact < ActiveRecord :: Base
include AlgoliaSearch
algoliasearch do
geoloc :lat_attr , :lng_attr
end
end
クエリ時に、検索パラメーターとして{ aroundLatLng: "37.33, -121.89", aroundRadius: 50000 }
を指定して、結果セットをサンノゼ周辺 50KM に制限します。
レコードが保存されるたびに、非同期でインデックスが作成されます。一方、レコードが破棄されるたびに、そのレコードはインデックスから非同期的に削除されます。つまり、ADD/DELETE 操作を伴うネットワーク呼び出しは Algolia API に同期的に送信されますが、エンジンはその操作を非同期で処理します (そのため、直後に検索を実行すると、結果がまだ反映されていない可能性があります)。
次のオプションを設定すると、自動インデックス作成と自動削除を無効にできます。
class Contact < ActiveRecord :: Base
include AlgoliaSearch
algoliasearch auto_index : false , auto_remove : false do
attribute :first_name , :last_name , :email
end
end
without_auto_index
スコープを使用して、自動インデックス作成を一時的に無効にすることができます。これはパフォーマンス上の理由からよく使用されます。
Contact . delete_all
Contact . without_auto_index do
1 . upto ( 10000 ) { Contact . create! attributes } # inside this block, auto indexing task will not run.
end
Contact . reindex! # will use batch operations
キューを使用してこれらの操作をバックグラウンドで実行するように、自動インデックス作成および自動削除プロセスを構成できます。 ActiveJob (Rails >=4.2) キューがデフォルトで使用されますが、独自のキューメカニズムを定義できます。
class Contact < ActiveRecord :: Base
include AlgoliaSearch
algoliasearch enqueue : true do # ActiveJob will be triggered using a `algoliasearch` queue
attribute :first_name , :last_name , :email
end
end
バックグラウンドで更新と削除を実行している場合は、ジョブが実際に実行される前にレコードの削除をデータベースにコミットできます。したがって、レコードをロードしてデータベースから削除しようとすると、ActiveRecord#find は RecordNotFound で失敗します。
この場合、ActiveRecord からのレコードのロードをバイパスして、インデックスと直接通信するだけです。
class MySidekiqWorker
def perform ( id , remove )
if remove
# the record has likely already been removed from your database so we cannot
# use ActiveRecord#find to load it
index = AlgoliaSearch . client . init_index ( "index_name" )
index . delete_object ( id )
else
# the record should be present
c = Contact . find ( id )
c . index!
end
end
end
Sidekiq を使用している場合:
class Contact < ActiveRecord :: Base
include AlgoliaSearch
algoliasearch enqueue : :trigger_sidekiq_worker do
attribute :first_name , :last_name , :email
end
def self . trigger_sidekiq_worker ( record , remove )
MySidekiqWorker . perform_async ( record . id , remove )
end
end
class MySidekiqWorker
def perform ( id , remove )
if remove
# the record has likely already been removed from your database so we cannot
# use ActiveRecord#find to load it
index = AlgoliaSearch . client . init_index ( "index_name" )
index . delete_object ( id )
else
# the record should be present
c = Contact . find ( id )
c . index!
end
end
end
late_job を使用している場合:
class Contact < ActiveRecord :: Base
include AlgoliaSearch
algoliasearch enqueue : :trigger_delayed_job do
attribute :first_name , :last_name , :email
end
def self . trigger_delayed_job ( record , remove )
if remove
record . delay . remove_from_index!
else
record . delay . index!
end
end
end
次のオプションを設定することで、インデックス作成と削除を強制的に同期させることができます (その場合、Gem はwait_task
メソッドを呼び出して、メソッドが戻ったときに操作が考慮されていることを確認します): (テスト目的を除き、これはお勧めしません) )
class Contact < ActiveRecord :: Base
include AlgoliaSearch
algoliasearch synchronous : true do
attribute :first_name , :last_name , :email
end
end
デフォルトでは、インデックス名はクラス名になります (例: 「Contact」)。 index_name
オプションを使用してインデックス名をカスタマイズできます。
class Contact < ActiveRecord :: Base
include AlgoliaSearch
algoliasearch index_name : "MyCustomName" do
attribute :first_name , :last_name , :email
end
end
次のオプションを使用して、インデックス名の末尾に現在の Rails 環境を付けることができます。
class Contact < ActiveRecord :: Base
include AlgoliaSearch
algoliasearch per_environment : true do # index name will be "Contact_#{Rails.env}"
attribute :first_name , :last_name , :email
end
end
ブロックを使用して複雑な属性値を指定できます
class Contact < ActiveRecord :: Base
include AlgoliaSearch
algoliasearch do
attribute :email
attribute :full_name do
" #{ first_name } #{ last_name } "
end
add_attribute :full_name2
end
def full_name2
" #{ first_name } #{ last_name } "
end
end
注:このようなコードを使用して追加の属性を定義するとすぐに、Gem は属性が変更されたかどうかを検出できなくなります (コードは Rails の#{attribute}_changed?
メソッドを使用してそれを検出します)。その結果、属性が変更されなかった場合でも、レコードは API にプッシュされます。 _changed?
を作成することで、この動作を回避できます。方法:
class Contact < ActiveRecord :: Base
include AlgoliaSearch
algoliasearch do
attribute :email
attribute :full_name do
" #{ first_name } #{ last_name } "
end
end
def full_name_changed?
first_name_changed? || last_name_changed?
end
end
JSON 準拠のオブジェクト (配列、ハッシュ、または両方の組み合わせ) を返す追加の属性を定義するネストされたオブジェクトを簡単に埋め込むことができます。
class Profile < ActiveRecord :: Base
include AlgoliaSearch
belongs_to :user
has_many :specializations
algoliasearch do
attribute :user do
# restrict the nested "user" object to its `name` + `email`
{ name : user . name , email : user . email }
end
attribute :public_specializations do
# build an array of public specialization (include only `title` and `another_attr`)
specializations . select { | s | s . public? } . map do | s |
{ title : s . title , another_attr : s . another_attr }
end
end
end
end
ActiveRecord では、これを実現するためにtouch
とafter_touch
使用します。
# app/models/app.rb
class App < ApplicationRecord
include AlgoliaSearch
belongs_to :author , class_name : :User
after_touch :index!
algoliasearch do
attribute :title
attribute :author do
author . as_json
end
end
end
# app/models/user.rb
class User < ApplicationRecord
# If your association uses belongs_to
# - use `touch: true`
# - do not define an `after_save` hook
has_many :apps , foreign_key : :author_id
after_save { apps . each ( & :touch ) }
end
Sequel では、 touch
プラグインを使用して変更を反映できます。
# app/models/app.rb
class App < Sequel :: Model
include AlgoliaSearch
many_to_one :author , class : :User
plugin :timestamps
plugin :touch
algoliasearch do
attribute :title
attribute :author do
author . to_hash
end
end
end
# app/models/user.rb
class User < Sequel :: Model
one_to_many :apps , key : :author_id
plugin :timestamps
# Can't use the associations since it won't trigger the after_save
plugin :touch
# Define the associations that need to be touched here
# Less performant, but allows for the after_save hook to trigger
def touch_associations
apps . map ( & :touch )
end
def touch
super
touch_associations
end
end
objectID
デフォルトでは、 objectID
レコードのid
に基づきます。 :id
オプションを指定すると、この動作を変更できます (必ず uniq フィールドを使用してください)。
class UniqUser < ActiveRecord :: Base
include AlgoliaSearch
algoliasearch id : :uniq_name do
end
end
:if
または:unless
オプションを使用して、レコードにインデックスを付ける必要があるかどうかを制御する制約を追加できます。
これにより、ドキュメントごとに条件付きインデックスを作成できます。
class Post < ActiveRecord :: Base
include AlgoliaSearch
algoliasearch if : :published? , unless : :deleted? do
end
def published?
# [...]
end
def deleted?
# [...]
end
end
注:これらの制約を使用するとすぐに、DB とのインデックスの同期を維持するためにaddObjects
およびdeleteObjects
呼び出しが実行されます (ステートレス gem は、オブジェクトが制約にもう一致しなくなったのか、それとも一度も一致しなかったのかを知りません)したがって、ADD/DELETE 操作が強制的に送信されます)。 _changed?
を作成することで、この動作を回避できます。方法:
class Contact < ActiveRecord :: Base
include AlgoliaSearch
algoliasearch if : :published do
end
def published
# true or false
end
def published_changed?
# return true only if you know that the 'published' state changed
end
end
次のいずれかを使用して、レコードのサブセットにインデックスを付けることができます。
# will generate batch API calls (recommended)
MyModel . where ( 'updated_at > ?' , 10 . minutes . ago ) . reindex!
または
MyModel . index_objects MyModel . limit ( 5 )
sanitize
オプションを使用して、すべての属性をサニタイズできます。属性からすべての HTML タグが削除されます。
class User < ActiveRecord :: Base
include AlgoliaSearch
algoliasearch per_environment : true , sanitize : true do
attributes :name , :email , :company
end
end
Rails 4.2 以降を使用している場合は、 rails-html-sanitizer
にも依存する必要があります。
gem 'rails-html-sanitizer'
force_utf8_encoding
オプションを使用して、すべての属性の UTF-8 エンコーディングを強制できます。
class User < ActiveRecord :: Base
include AlgoliaSearch
algoliasearch force_utf8_encoding : true do
attributes :name , :email , :company
end
end
注:このオプションは Ruby 1.8 と互換性がありません。
raise_on_failure
オプションを使用すると、Algolia の API にアクセスしようとするときに発生する可能性のある例外を無効にできます。
class Contact < ActiveRecord :: Base
include AlgoliaSearch
# only raise exceptions in development env
algoliasearch raise_on_failure : Rails . env . development? do
attribute :first_name , :last_name , :email
end
end
実際の設定例は次のとおりです (HN 検索から)。
class Item < ActiveRecord :: Base
include AlgoliaSearch
algoliasearch per_environment : true do
# the list of attributes sent to Algolia's API
attribute :created_at , :title , :url , :author , :points , :story_text , :comment_text , :author , :num_comments , :story_id , :story_title
# integer version of the created_at datetime field, to use numerical filtering
attribute :created_at_i do
created_at . to_i
end
# `title` is more important than `{story,comment}_text`, `{story,comment}_text` more than `url`, `url` more than `author`
# btw, do not take into account position in most fields to avoid first word match boost
searchableAttributes [ 'unordered(title)' , 'unordered(story_text)' , 'unordered(comment_text)' , 'unordered(url)' , 'author' ]
# tags used for filtering
tags do
[ item_type , "author_ #{ author } " , "story_ #{ story_id } " ]
end
# use associated number of HN points to sort results (last sort criteria)
customRanking [ 'desc(points)' , 'desc(num_comments)' ]
# google+, $1.5M raises, C#: we love you
separatorsToIndex '+#$'
end
def story_text
item_type_cd != Item . comment ? text : nil
end
def story_title
comment? && story ? story . title : nil
end
def story_url
comment? && story ? story . url : nil
end
def comment_text
comment? ? text : nil
end
def comment?
item_type_cd == Item . comment
end
# [...]
end
index!
インスタンスメソッド。
c = Contact . create! ( params [ :contact ] )
c . index!
そして、 remove_from_index!
インスタンスメソッド。
c . remove_from_index!
c . destroy
gem は、すべてのオブジェクトのインデックスを再作成する 2 つの方法を提供します。
すべてのレコードのインデックスを再作成するには (削除されたオブジェクトを考慮して)、 reindex
クラス メソッドはすべてのオブジェクトを<INDEX_NAME>.tmp
という一時インデックスにインデックスし、すべてのインデックスが (アトミックに) 作成されると、一時インデックスを最後のインデックスに移動します。これは、すべてのコンテンツのインデックスを再作成する最も安全な方法です。
Contact . reindex
注: インデックス固有の API キーを使用している場合は、 <INDEX_NAME>
と<INDEX_NAME>.tmp
両方を許可していることを確認してください。
警告:この操作はインデックス全体を置き換え、フィルターされたオブジェクトのみを保持するため、モデルのスコープ/フィルター処理中にこのようなアトミックなインデックス再作成操作を使用しないでください。つまり、 MyModel.where(...).reindex
実行するのではなく、 MyModel.where(...).reindex!
(末尾に!
)!!!
すべてのオブジェクトのインデックスを所定の位置に再作成するには (一時インデックスを使用せず、したがって削除されたオブジェクトを削除せずに)、 reindex!
クラスメソッド:
Contact . reindex!
インデックスをクリアするには、 clear_index!
を使用します。クラスメソッド:
Contact . clear_index!
index
クラス メソッドを呼び出すことで、基になるindex
オブジェクトにアクセスできます。
index = Contact . index
# index.get_settings, index.partial_update_object, ...
add_replica
メソッドを使用してレプリカ インデックスを定義できます。プライマリ設定を継承させたい場合は、レプリカ ブロックでinherit: true
を使用します。
class Book < ActiveRecord :: Base
attr_protected
include AlgoliaSearch
algoliasearch per_environment : true do
searchableAttributes [ :name , :author , :editor ]
# define a replica index to search by `author` only
add_replica 'Book_by_author' , per_environment : true do
searchableAttributes [ :author ]
end
# define a replica index with custom ordering but same settings than the main block
add_replica 'Book_custom_order' , inherit : true , per_environment : true do
customRanking [ 'asc(rank)' ]
end
end
end
レプリカを使用して検索するには、次のコードを使用します。
Book . raw_search 'foo bar' , replica : 'Book_by_editor'
# or
Book . search 'foo bar' , replica : 'Book_by_editor'
複数のモデル間でインデックスを共有することは合理的です。これを実装するには、基礎となるモデルのobjectID
と競合していないことを確認する必要があります。
class Student < ActiveRecord :: Base
attr_protected
include AlgoliaSearch
algoliasearch index_name : 'people' , id : :algolia_id do
# [...]
end
private
def algolia_id
"student_ #{ id } " # ensure the teacher & student IDs are not conflicting
end
end
class Teacher < ActiveRecord :: Base
attr_protected
include AlgoliaSearch
algoliasearch index_name : 'people' , id : :algolia_id do
# [...]
end
private
def algolia_id
"teacher_ #{ id } " # ensure the teacher & student IDs are not conflicting
end
end
注:複数のモデルから単一のインデックスをターゲットにする場合は、 MyModel.reindex
決して使用せず、 MyModel.reindex!
。 reindex
メソッドは、一時インデックスを使用してアトミックな再インデックスを実行します。これを使用すると、他のレコードのインデックスは再作成されないため、結果のインデックスには現在のモデルのレコードのみが含まれます。
add_index
メソッドを使用して、複数のインデックスでレコードにインデックスを付けることができます。
class Book < ActiveRecord :: Base
attr_protected
include AlgoliaSearch
PUBLIC_INDEX_NAME = "Book_ #{ Rails . env } "
SECURED_INDEX_NAME = "SecuredBook_ #{ Rails . env } "
# store all books in index 'SECURED_INDEX_NAME'
algoliasearch index_name : SECURED_INDEX_NAME do
searchableAttributes [ :name , :author ]
# convert security to tags
tags do
[ released ? 'public' : 'private' , premium ? 'premium' : 'standard' ]
end
# store all 'public' (released and not premium) books in index 'PUBLIC_INDEX_NAME'
add_index PUBLIC_INDEX_NAME , if : :public? do
searchableAttributes [ :name , :author ]
end
end
private
def public?
released && ! premium
end
end
追加のインデックスを使用して検索するには、次のコードを使用します。
Book . raw_search 'foo bar' , index : 'Book_by_editor'
# or
Book . search 'foo bar' , index : 'Book_by_editor'
スペックを実行するには、 ALGOLIA_APPLICATION_ID
およびALGOLIA_API_KEY
環境変数を設定してください。テストではインデックスの作成と削除が行われるため、運用アカウントは使用しないでください。
すべてのインデックス作成 (追加、更新、削除操作) API 呼び出しを無効にする場合は、 disable_indexing
オプションを設定できます。
class User < ActiveRecord :: Base
include AlgoliaSearch
algoliasearch per_environment : true , disable_indexing : Rails . env . test? do
end
end
class User < ActiveRecord :: Base
include AlgoliaSearch
algoliasearch per_environment : true , disable_indexing : Proc . new { Rails . env . test? || more_complex_condition } do
end
end
問題が発生しましたか?サポートに問い合わせる前に、FAQ にアクセスして、クライアントとの最も一般的な問題や注意点に対する回答を見つけることをお勧めします。
すべての依存関係をインストールせずにこのプロジェクトに貢献したい場合は、Docker イメージを使用できます。詳細については、専用ガイドをご覧ください。