Class: AlgoliaSearch::IndexSettings

Inherits:
Object
  • Object
show all
Defined in:
lib/algoliasearch-rails.rb

Constant Summary collapse

DEFAULT_BATCH_SIZE =
1000
OPTIONS =

AlgoliaSearch settings

[
  # Attributes
  :searchableAttributes, :attributesForFaceting, :unretrievableAttributes, :attributesToRetrieve,
  # Ranking
  :ranking, :customRanking, :relevancyStrictness, # Replicas are handled via `add_replica`
  # Faceting
  :maxValuesPerFacet, :sortFacetValuesBy,
  # Highlighting / Snippeting
  :attributesToHighlight, :attributesToSnippet, :highlightPreTag, :highlightPostTag,
  :snippetEllipsisText, :restrictHighlightAndSnippetArrays,
  # Pagination
  :hitsPerPage, :paginationLimitedTo,
  # Typo
  :minWordSizefor1Typo, :minWordSizefor2Typos, :typoTolerance, :allowTyposOnNumericTokens,
  :disableTypoToleranceOnAttributes, :disableTypoToleranceOnWords, :separatorsToIndex,
  # Language
  :ignorePlurals, :removeStopWords, :camelCaseAttributes, :decompoundedAttributes,
  :keepDiacriticsOnCharacters, :queryLanguages, :indexLanguages,
  # Query Rules
  :enableRules,
  # Query Strategy
  :queryType, :removeWordsIfNoResults, :advancedSyntax, :optionalWords,
  :disablePrefixOnAttributes, :disableExactOnAttributes, :exactOnSingleWordQuery, :alternativesAsExact,
  # Performance
  :numericAttributesForFiltering, :allowCompressionOfIntegerArray,
  # Advanced
  :attributeForDistinct, :distinct, :replaceSynonymsInHighlight, :minProximity, :responseFields,
  :maxFacetHits,

  # Rails-specific
  :synonyms, :placeholders, :altCorrections,
]

Instance Method Summary collapse

Constructor Details

#initialize(options, &block) ⇒ IndexSettings

Returns a new instance of IndexSettings.



91
92
93
94
# File 'lib/algoliasearch-rails.rb', line 91

def initialize(options, &block)
  @options = options
  instance_exec(&block) if block_given?
end

Instance Method Details

#add_attribute(*names, &block) ⇒ Object Also known as: add_attributes

Raises:

  • (ArgumentError)


110
111
112
113
114
115
116
117
# File 'lib/algoliasearch-rails.rb', line 110

def add_attribute(*names, &block)
  raise ArgumentError.new('Cannot pass multiple attribute names if block given') if block_given? and names.length > 1
  raise ArgumentError.new('Cannot specify additional attributes on a replica index') if @options[:replica]
  @additional_attributes ||= {}
  names.each do |name|
    @additional_attributes[name.to_s] = block_given? ? Proc.new { |o| o.instance_eval(&block) } : Proc.new { |o| o.send(name) }
  end
end

#add_index(index_name, options = {}, &block) ⇒ Object

Raises:

  • (ArgumentError)


271
272
273
274
275
276
277
278
# File 'lib/algoliasearch-rails.rb', line 271

def add_index(index_name, options = {}, &block)
  raise ArgumentError.new('Cannot specify additional index on a replica index') if @options[:replica]
  raise ArgumentError.new('No block given') if !block_given?
  raise ArgumentError.new('Options auto_index and auto_remove cannot be set on nested indexes') if options[:auto_index] || options[:auto_remove]
  @additional_indexes ||= {}
  options[:index_name] = index_name
  @additional_indexes[options] = IndexSettings.new(options, &block)
end

#add_replica(index_name, options = {}, &block) ⇒ Object

Raises:

  • (ArgumentError)


280
281
282
283
284
# File 'lib/algoliasearch-rails.rb', line 280

def add_replica(index_name, options = {}, &block)
  raise ArgumentError.new('Cannot specify additional replicas on a replica index') if @options[:replica]
  raise ArgumentError.new('No block given') if !block_given?
  add_index(index_name, options.merge({ :replica => true, :primary_settings => self }), &block)
end

#additional_indexesObject



286
287
288
# File 'lib/algoliasearch-rails.rb', line 286

def additional_indexes
  @additional_indexes || {}
end

#attribute(*names, &block) ⇒ Object Also known as: attributes

Raises:

  • (ArgumentError)


100
101
102
103
104
105
106
107
# File 'lib/algoliasearch-rails.rb', line 100

def attribute(*names, &block)
  raise ArgumentError.new('Cannot pass multiple attribute names if block given') if block_given? and names.length > 1
  raise ArgumentError.new('Cannot specify additional attributes on a replica index') if @options[:replica]
  @attributes ||= {}
  names.flatten.each do |name|
    @attributes[name.to_s] = block_given? ? Proc.new { |o| o.instance_eval(&block) } : Proc.new { |o| o.send(name) }
  end
end

#attributes_to_hash(attributes, object) ⇒ Object



149
150
151
152
153
154
155
# File 'lib/algoliasearch-rails.rb', line 149

def attributes_to_hash(attributes, object)
  if attributes
    Hash[attributes.map { |name, value| [name.to_s, value.call(object) ] }]
  else
    {}
  end
end

#encode_attributes(v) ⇒ Object



201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/algoliasearch-rails.rb', line 201

def encode_attributes(v)
  case v
  when String
    v.dup.force_encoding('utf-8')
  when Hash
    v.each { |key, value| v[key] = encode_attributes(value) }
  when Array
    v.map { |x| encode_attributes(x) }
  else
    v
  end
end

#geoloc(lat_attr = nil, lng_attr = nil, &block) ⇒ Object

Raises:

  • (ArgumentError)


214
215
216
217
218
219
# File 'lib/algoliasearch-rails.rb', line 214

def geoloc(lat_attr = nil, lng_attr = nil, &block)
  raise ArgumentError.new('Cannot specify additional attributes on a replica index') if @options[:replica]
  add_attribute :_geoloc do |o|
    block_given? ? o.instance_eval(&block) : { :lat => o.send(lat_attr).to_f, :lng => o.send(lng_attr).to_f }
  end
end

#get_attribute_names(object) ⇒ Object



145
146
147
# File 'lib/algoliasearch-rails.rb', line 145

def get_attribute_names(object)
  get_attributes(object).keys
end

#get_attributes(object) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/algoliasearch-rails.rb', line 157

def get_attributes(object)
  # If a serializer is set, we ignore attributes
  # everything should be done via the serializer
  if not @serializer.nil?
    attributes = @serializer.new(object).attributes
  else
    if @attributes.nil? || @attributes.length == 0
      # no `attribute ...` have been configured, use the default attributes of the model
      attributes = get_default_attributes(object)
    else
      # at least 1 `attribute ...` has been configured, therefore use ONLY the one configured
      if is_active_record?(object)
        object.class.unscoped do
          attributes = attributes_to_hash(@attributes, object)
        end
      else
        attributes = attributes_to_hash(@attributes, object)
      end
    end
  end

  attributes.merge!(attributes_to_hash(@additional_attributes, object)) if @additional_attributes
  attributes = sanitize_attributes(attributes, Rails::Html::FullSanitizer.new) if @options[:sanitize]

  if @options[:force_utf8_encoding] && Object.const_defined?(:RUBY_VERSION) && RUBY_VERSION.to_f > 1.8
    attributes = encode_attributes(attributes)
  end

  attributes
end

#get_default_attributes(object) ⇒ Object



132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/algoliasearch-rails.rb', line 132

def get_default_attributes(object)
  if is_mongoid?(object)
    # work-around mongoid 2.4's unscoped method, not accepting a block
    object.attributes
  elsif is_sequel?(object)
    object.to_hash
  else
    object.class.unscoped do
      object.attributes
    end
  end
end

#get_setting(name) ⇒ Object



229
230
231
# File 'lib/algoliasearch-rails.rb', line 229

def get_setting(name)
  instance_variable_get("@#{name}")
end

#is_active_record?(object) ⇒ Boolean

Returns:

  • (Boolean)


128
129
130
# File 'lib/algoliasearch-rails.rb', line 128

def is_active_record?(object)
  !is_mongoid?(object) && !is_sequel?(object)
end

#is_mongoid?(object) ⇒ Boolean

Returns:

  • (Boolean)


120
121
122
# File 'lib/algoliasearch-rails.rb', line 120

def is_mongoid?(object)
  defined?(::Mongoid::Document) && object.class.include?(::Mongoid::Document)
end

#is_sequel?(object) ⇒ Boolean

Returns:

  • (Boolean)


124
125
126
# File 'lib/algoliasearch-rails.rb', line 124

def is_sequel?(object)
  defined?(::Sequel) && defined?(::Sequel::Model) && object.class < ::Sequel::Model
end

#sanitize_attributes(v, sanitizer) ⇒ Object



188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/algoliasearch-rails.rb', line 188

def sanitize_attributes(v, sanitizer)
  case v
  when String
    sanitizer.sanitize(v)
  when Hash
    v.each { |key, value| v[key] = sanitize_attributes(value, sanitizer) }
  when Array
    v.map { |x| sanitize_attributes(x, sanitizer) }
  else
    v
  end
end

#setting_name(name) ⇒ Object



263
264
265
266
267
268
269
# File 'lib/algoliasearch-rails.rb', line 263

def setting_name(name)
  name.to_s.gsub(/::/, '/').
      gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
      gsub(/([a-z\d])([A-Z])/,'\1_\2').
      tr("-", "_").
      downcase
end

#tags(*args, &block) ⇒ Object

Raises:

  • (ArgumentError)


221
222
223
224
225
226
227
# File 'lib/algoliasearch-rails.rb', line 221

def tags(*args, &block)
  raise ArgumentError.new('Cannot specify additional attributes on a replica index') if @options[:replica]
  add_attribute :_tags do |o|
    v = block_given? ? o.instance_eval(&block) : args
    v.is_a?(Array) ? v : [v]
  end
end

#to_hashObject



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/algoliasearch-rails.rb', line 243

def to_hash
  settings = {}
  OPTIONS.each do |k|
    v = get_setting(k)
    settings[setting_name(k)] = v if !v.nil?
  end

  if !@options[:replica]
    settings[:replicas] = additional_indexes.select { |opts, s| opts[:replica] }.map do |opts, s|
      name = opts[:index_name]
      name = "#{name}_#{Rails.env.to_s}" if opts[:per_environment]
      name = "virtual(#{name})" if opts[:virtual]
      name
    end
    settings.delete(:replicas) if settings[:replicas].empty?
  end

  settings
end

#to_settingsObject



233
234
235
236
237
238
239
240
241
# File 'lib/algoliasearch-rails.rb', line 233

def to_settings
  settings = to_hash

  # Remove the synonyms setting since those need to be set separately
  settings.delete(:synonyms)
  settings.delete("synonyms")

  Algolia::Search::IndexSettings.new(settings)
end

#use_serializer(serializer) ⇒ Object



96
97
98
# File 'lib/algoliasearch-rails.rb', line 96

def use_serializer(serializer)
  @serializer = serializer
end