문서 • 커뮤니티 포럼 • 스택 오버플로 • 버그 신고 • FAQ • 지원
이 gem을 사용하면 Algolia Search API를 즐겨 사용하는 ORM에 쉽게 통합할 수 있습니다. 이는 algoliasearch-client-ruby gem을 기반으로 합니다. 레일스 6.x 및 7.x가 지원됩니다.
autocomplete.js
기반 자동 완성 및 InstantSearch.js
기반 즉시 검색 결과 페이지(algoliasearch-rails-example)를 제공하는 샘플 Ruby on Rails 애플리케이션에 관심이 있으실 것입니다.
Algolia 웹사이트에서 전체 참조 자료를 찾을 수 있습니다.
설정
용법
옵션
objectID
지수
테스트
문제 해결
gem install algoliasearch-rails
Gemfile
에 gem을 추가하세요.
gem "algoliasearch-rails"
그리고 다음을 실행하세요:
bundle install
APPLICATION_ID
및 API_KEY
설정하려면 새 파일 config/initializers/algoliasearch.rb
생성하세요.
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의 일부입니다. JavaScript 매니페스트 어딘가에 algolia/v3/algoliasearch.min
필요합니다. 예를 들어 Rails 3.1 이상을 사용하는 경우 application.js
에 필요합니다.
//= 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
방법의 두 번째 인수로 검색 매개변수를 지정하여 검색 시 동적으로 지정할 수 있습니다.
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 }
검색 매개변수로 지정하여 결과 집합을 San Jose 주변 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
Delayed_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
기본적으로 인덱스 이름은 "연락처"와 같은 클래스 이름이 됩니다. 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 Search의 실제 단어 구성 예입니다.
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 이미지를 사용할 수 있습니다. 자세한 내용은 전용 가이드를 확인하세요.