Class: Algolia::Index

Inherits:
Object
  • Object
show all
Defined in:
lib/algolia/index.rb

Defined Under Namespace

Classes: IndexBrowser

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, client = nil) ⇒ Index

Returns a new instance of Index.



9
10
11
12
# File 'lib/algolia/index.rb', line 9

def initialize(name, client = nil)
  self.name = name
  self.client = client || Algolia.client
end

Instance Attribute Details

#clientObject

Returns the value of attribute client.



7
8
9
# File 'lib/algolia/index.rb', line 7

def client
  @client
end

#nameObject

Returns the value of attribute name.



7
8
9
# File 'lib/algolia/index.rb', line 7

def name
  @name
end

Class Method Details

.all(request_options = {}) ⇒ Object

Alias of Algolia.list_indexes

Parameters:

  • request_options (defaults to: {})

    contains extra parameters to send with your query



925
926
927
# File 'lib/algolia/index.rb', line 925

def Index.all(request_options = {})
  Algolia.list_indexes(request_options)
end

.get_object_position(objects, object_id) ⇒ Integer

Retrieve the given object position in a set of results.

Parameters:

  • objects (Array)

    the result set to browse

  • object_id (String)

    the object to look for

Returns:

  • (Integer)

    position of the object, or -1 if it’s not in the array



332
333
334
# File 'lib/algolia/index.rb', line 332

def self.get_object_position(objects, object_id)
  objects['hits'].find_index { |hit| hit['objectID'] == object_id } || -1
end

Instance Method Details

#add_api_key(object, validity = 0, max_queries_per_IP_per_hour = 0, max_hits_per_query = 0, request_options = {}) ⇒ Object Also known as: add_user_key

Create a new user key

@param object can be two different parameters:
      The list of parameters for this key. Defined by a Hash that can
      contains the following values:
        - acl: array of string
        - validity: int
        - referers: array of string
        - description: string
        - maxHitsPerQuery: integer
        - queryParameters: string
        - maxQueriesPerIPPerHour: integer
      Or the list of ACL for this key. Defined by an array of String that
      can contains the following values:
        - search: allow to search (https and http)
        - addObject: allows to add/update an object in the index (https only)
        - deleteObject : allows to delete an existing object (https only)
        - deleteIndex : allows to delete index content (https only)
        - settings : allows to get index settings (https only)
        - editSettings : allows to change index settings (https only)
@param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key)
@param max_queries_per_IP_per_hour the maximum number of API calls allowed from an IP address per hour (0 means unlimited)
@param max_hits_per_query the maximum number of hits this API key can retrieve in one call (0 means unlimited)
@param request_options contains extra parameters to send with your query


 # Deprecated: Please use ‘client.add_api_key` instead



733
734
735
736
737
738
739
740
741
742
743
744
745
# File 'lib/algolia/index.rb', line 733

def add_api_key(object, validity = 0, max_queries_per_IP_per_hour = 0, max_hits_per_query = 0, request_options = {})
  if object.instance_of?(Array)
    params = { :acl => object }
  else
    params = object
  end

  params['validity'] = validity.to_i if validity != 0
  params['maxHitsPerQuery'] = max_hits_per_query.to_i if max_hits_per_query != 0
  params['maxQueriesPerIPPerHour'] = max_queries_per_IP_per_hour.to_i if max_queries_per_IP_per_hour != 0

  client.post(Protocol.index_keys_uri(name), params.to_json, :write, request_options)
end

#add_object(object, objectID = nil, request_options = {}) ⇒ Object

Add an object in this index

Parameters:

  • object

    the object to add to the index. The object is represented by an associative array

  • objectID (optional) (defaults to: nil)

    an objectID you want to attribute to this object (if the attribute already exist the old object will be overridden)

  • request_options (defaults to: {})

    contains extra parameters to send with your query



49
50
51
52
53
54
55
56
# File 'lib/algolia/index.rb', line 49

def add_object(object, objectID = nil, request_options = {})
  check_object(object)
  if objectID.nil? || objectID.to_s.empty?
    client.post(Protocol.index_uri(name), object.to_json, :write, request_options)
  else
    client.put(Protocol.object_uri(name, objectID), object.to_json, :write, request_options)
  end
end

#add_object!(object, objectID = nil, request_options = {}) ⇒ Object

Add an object in this index and wait end of indexing

Parameters:

  • object

    the object to add to the index. The object is represented by an associative array

  • objectID (optional) (defaults to: nil)

    an objectID you want to attribute to this object (if the attribute already exist the old object will be overridden)

  • Request

    options object. Contains extra URL parameters or headers



67
68
69
70
71
# File 'lib/algolia/index.rb', line 67

def add_object!(object, objectID = nil, request_options = {})
  res = add_object(object, objectID, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  res
end

#add_objects(objects, request_options = {}) ⇒ Object

Add several objects in this index

Parameters:

  • objects

    the array of objects to add inside the index. Each object is represented by an associative array

  • request_options (defaults to: {})

    contains extra parameters to send with your query



80
81
82
# File 'lib/algolia/index.rb', line 80

def add_objects(objects, request_options = {})
  batch(build_batch('addObject', objects, false), request_options)
end

#add_objects!(objects, request_options = {}) ⇒ Object

Add several objects in this index and wait end of indexing

Parameters:

  • objects

    the array of objects to add inside the index. Each object is represented by an associative array

  • request_options (defaults to: {})

    contains extra parameters to send with your query



91
92
93
94
95
# File 'lib/algolia/index.rb', line 91

def add_objects!(objects, request_options = {})
  res = add_objects(objects, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  res
end

#batch(request, request_options = {}) ⇒ Object

Send a batch request



799
800
801
# File 'lib/algolia/index.rb', line 799

def batch(request, request_options = {})
  client.post(Protocol.batch_uri(name), request.to_json, :batch, request_options)
end

#batch!(request, request_options = {}) ⇒ Object

Send a batch request and wait the end of the indexing



806
807
808
809
810
# File 'lib/algolia/index.rb', line 806

def batch!(request, request_options = {})
  res = batch(request, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  res
end

#batch_rules(rules, forward_to_replicas = false, clear_existing_rules = false, request_options = {}) ⇒ Object

Add/Update an array of rules

Parameters:

  • rules

    the array of rules to add/update

  • forward_to_replicas (defaults to: false)

    should we forward the delete to replica indices

  • clear_existing_rules (defaults to: false)

    should we clear the existing rules before adding the new ones

  • request_options (defaults to: {})

    contains extra parameters to send with your query



1216
1217
1218
# File 'lib/algolia/index.rb', line 1216

def batch_rules(rules, forward_to_replicas = false, clear_existing_rules = false, request_options = {})
  client.post("#{Protocol.batch_rules_uri(name)}?forwardToReplicas=#{forward_to_replicas}&clearExistingRules=#{clear_existing_rules}", rules.to_json, :batch, request_options)
end

#batch_rules!(rules, forward_to_replicas = false, clear_existing_rules = false, request_options = {}) ⇒ Object

Add/Update an array of rules and wait the end of indexing

Parameters:

  • rules

    the array of rules to add/update

  • forward_to_replicas (defaults to: false)

    should we forward the delete to replica indices

  • clear_existing_rules (defaults to: false)

    should we clear the existing rules before adding the new ones

  • request_options (defaults to: {})

    contains extra parameters to send with your query



1228
1229
1230
1231
1232
# File 'lib/algolia/index.rb', line 1228

def batch_rules!(rules, forward_to_replicas = false, clear_existing_rules = false, request_options = {})
  res = batch_rules(rules, forward_to_replicas, clear_existing_rules, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  return res
end

#batch_synonyms(synonyms, forward_to_replicas = false, replace_existing_synonyms = false, request_options = {}) ⇒ Object

Add/Update an array of synonyms

Parameters:

  • synonyms

    the array of synonyms to add/update

  • forward_to_replicas (defaults to: false)

    should we forward the delete to replica indices

  • replace_existing_synonyms (defaults to: false)

    should we replace the existing synonyms before adding the new ones

  • request_options (defaults to: {})

    contains extra parameters to send with your query



1039
1040
1041
# File 'lib/algolia/index.rb', line 1039

def batch_synonyms(synonyms, forward_to_replicas = false, replace_existing_synonyms = false, request_options = {})
  client.post("#{Protocol.batch_synonyms_uri(name)}?forwardToReplicas=#{forward_to_replicas}&replaceExistingSynonyms=#{replace_existing_synonyms}", synonyms.to_json, :batch, request_options)
end

#batch_synonyms!(synonyms, forward_to_replicas = false, replace_existing_synonyms = false, request_options = {}) ⇒ Object

Add/Update an array of synonyms and wait the end of indexing

Parameters:

  • synonyms

    the array of synonyms to add/update

  • forward_to_replicas (defaults to: false)

    should we forward the delete to replica indices

  • replace_existing_synonyms (defaults to: false)

    should we replace the existing synonyms before adding the new ones

  • request_options (defaults to: {})

    contains extra parameters to send with your query



1051
1052
1053
1054
1055
# File 'lib/algolia/index.rb', line 1051

def batch_synonyms!(synonyms, forward_to_replicas = false, replace_existing_synonyms = false, request_options = {})
  res = batch_synonyms(synonyms, forward_to_replicas, replace_existing_synonyms, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  res
end

#browse(page_or_query_parameters = nil, hits_per_page = nil, request_options = {}, &block) ⇒ Object

Browse all index content

@DEPRECATED:

Parameters:

  • queryParameters

    The hash of query parameters to use to browse To browse from a specific cursor, just add a “:cursor” parameters

  • queryParameters

    An optional second parameters hash here for backward-compatibility (which will be merged with the first)

  • request_options (defaults to: {})

    contains extra parameters to send with your query

  • page

    Pagination parameter used to select the page to retrieve.

  • hits_per_page (defaults to: nil)

    Pagination parameter used to select the number of hits per page. Defaults to 1000.



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/algolia/index.rb', line 203

def browse(page_or_query_parameters = nil, hits_per_page = nil, request_options = {}, &block)
  params = {}
  if page_or_query_parameters.is_a?(Hash)
    params.merge!(page_or_query_parameters)
  else
    params[:page] = page_or_query_parameters unless page_or_query_parameters.nil?
  end
  if hits_per_page.is_a?(Hash)
    params.merge!(hits_per_page)
  else
    params[:hitsPerPage] = hits_per_page unless hits_per_page.nil?
  end

  if block_given?
    IndexBrowser.new(client, name, params).browse(request_options, &block)
  else
    params[:page] ||= 0
    params[:hitsPerPage] ||= 1000
    client.get(Protocol.browse_uri(name, params), :read, request_options)
  end
end

#browse_from(cursor, hits_per_page = 1000, request_options = {}) ⇒ Object

Browse a single page from a specific cursor

Parameters:

  • request_options (defaults to: {})

    contains extra parameters to send with your query



230
231
232
# File 'lib/algolia/index.rb', line 230

def browse_from(cursor, hits_per_page = 1000, request_options = {})
  client.post(Protocol.browse_uri(name), { :cursor => cursor, :hitsPerPage => hits_per_page }.to_json, :read, request_options)
end

#clear(request_options = {}) ⇒ Object Also known as: clear_index

Delete the index content

Parameters:

  • request_options (defaults to: {})

    contains extra parameters to send with your query



652
653
654
# File 'lib/algolia/index.rb', line 652

def clear(request_options = {})
  client.post(Protocol.clear_uri(name), {}, :write, request_options)
end

#clear!(request_options = {}) ⇒ Object Also known as: clear_index!

Delete the index content and wait end of indexing



660
661
662
663
664
# File 'lib/algolia/index.rb', line 660

def clear!(request_options = {})
  res = clear(request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  res
end

#clear_rules(forward_to_replicas = false, request_options = {}) ⇒ Object

Clear all rules

Parameters:

  • forward_to_replicas (defaults to: false)

    should we forward the delete to replica indices

  • request_options (defaults to: {})

    contains extra parameters to send with your query



1192
1193
1194
# File 'lib/algolia/index.rb', line 1192

def clear_rules(forward_to_replicas = false, request_options = {})
  client.post("#{Protocol.clear_rules_uri(name)}?forwardToReplicas=#{forward_to_replicas}", {}, :write, request_options)
end

#clear_rules!(forward_to_replicas = false, request_options = {}) ⇒ Object

Clear all rules and wait the end of indexing

Parameters:

  • forward_to_replicas (defaults to: false)

    should we forward the delete to replica indices

  • request_options (defaults to: {})

    contains extra parameters to send with your query



1202
1203
1204
1205
1206
# File 'lib/algolia/index.rb', line 1202

def clear_rules!(forward_to_replicas = false, request_options = {})
  res = clear_rules(forward_to_replicas, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  return res
end

#clear_synonyms(forward_to_replicas = false, request_options = {}) ⇒ Object

Clear all synonyms

Parameters:

  • forward_to_replicas (defaults to: false)

    should we forward the delete to replica indices

  • request_options (defaults to: {})

    contains extra parameters to send with your query



1015
1016
1017
# File 'lib/algolia/index.rb', line 1015

def clear_synonyms(forward_to_replicas = false, request_options = {})
  client.post("#{Protocol.clear_synonyms_uri(name)}?forwardToReplicas=#{forward_to_replicas}", {}, :write, request_options)
end

#clear_synonyms!(forward_to_replicas = false, request_options = {}) ⇒ Object

Clear all synonyms and wait the end of indexing

Parameters:

  • forward_to_replicas (defaults to: false)

    should we forward the delete to replica indices

  • request_options (defaults to: {})

    contains extra parameters to send with your query



1025
1026
1027
1028
1029
# File 'lib/algolia/index.rb', line 1025

def clear_synonyms!(forward_to_replicas = false, request_options = {})
  res = clear_synonyms(forward_to_replicas, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  res
end

#delete(request_options = {}) ⇒ Object Also known as: delete_index

Delete an index

return an hash of the form { “deletedAt” => “2013-01-18T15:33:13.556Z”, “taskID” => “42” }

Parameters:

  • request_options (defaults to: {})

    contains extra parameters to send with your query



21
22
23
# File 'lib/algolia/index.rb', line 21

def delete(request_options = {})
  client.delete(Protocol.index_uri(name), :write, request_options)
end

#delete!(request_options = {}) ⇒ Object Also known as: delete_index!

Delete an index and wait until the deletion has been processed

return an hash of the form { “deletedAt” => “2013-01-18T15:33:13.556Z”, “taskID” => “42” }

Parameters:

  • request_options (defaults to: {})

    contains extra parameters to send with your query



33
34
35
36
37
# File 'lib/algolia/index.rb', line 33

def delete!(request_options = {})
  res = delete(request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  res
end

#delete_api_key(key, request_options = {}) ⇒ Object Also known as: delete_user_key

Delete an existing user key

Deprecated: Please use ‘client.delete_api_key` instead



792
793
794
# File 'lib/algolia/index.rb', line 792

def delete_api_key(key, request_options = {})
  client.delete(Protocol.index_key_uri(name, key), :write, request_options)
end

#delete_by(params, request_options = {}) ⇒ Object

Delete all objects matching a query (doesn’t work with actual text queries) This method deletes every record matching the filters provided

Parameters:

  • params

    query parameters

  • request_options (defaults to: {})

    contains extra parameters to send with your query

Raises:

  • (ArgumentError)


629
630
631
632
633
# File 'lib/algolia/index.rb', line 629

def delete_by(params, request_options = {})
  raise ArgumentError.new('params cannot be nil, use the `clear` method to wipe the entire index') if params.nil?
  params = sanitized_delete_by_query_params(params)
  client.post(Protocol.delete_by_uri(name), params.to_json, :write, request_options)
end

#delete_by!(params, request_options = {}) ⇒ Object

Delete all objects matching a query (doesn’t work with actual text queries) This method deletes every record matching the filters provided and waits for the end of indexing

Parameters:

  • params

    query parameters

  • request_options (defaults to: {})

    contains extra parameters to send with your query



641
642
643
644
645
# File 'lib/algolia/index.rb', line 641

def delete_by!(params, request_options = {})
  res = delete_by(params, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) if res
  res
end

#delete_by_query(query, params = nil, request_options = {}) ⇒ Object

Delete all objects matching a query This method retrieves all objects synchronously but deletes in batch asynchronously

Parameters:

  • query

    the query string

  • params (defaults to: nil)

    the optional query parameters

  • request_options (defaults to: {})

    contains extra parameters to send with your query

Raises:

  • (ArgumentError)


584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
# File 'lib/algolia/index.rb', line 584

def delete_by_query(query, params = nil, request_options = {})
  raise ArgumentError.new('query cannot be nil, use the `clear` method to wipe the entire index') if query.nil? && params.nil?
  params = sanitized_delete_by_query_params(params)

  params[:query] = query
  params[:hitsPerPage] = 1000
  params[:distinct] = false
  params[:attributesToRetrieve] = ['objectID']
  params[:cursor] = ''
  ids = []

  while params[:cursor] != nil
    result = browse(params, nil, request_options)

    params[:cursor] = result['cursor']

    hits = result['hits']
    break if hits.empty?

    ids += hits.map { |hit| hit['objectID'] }
  end

  delete_objects(ids, request_options)
end

#delete_by_query!(query, params = nil, request_options = {}) ⇒ Object

Delete all objects matching a query and wait end of indexing

Parameters:

  • query

    the query string

  • params (defaults to: nil)

    the optional query parameters

  • request_options (defaults to: {})

    contains extra parameters to send with your query



616
617
618
619
620
# File 'lib/algolia/index.rb', line 616

def delete_by_query!(query, params = nil, request_options = {})
  res = delete_by_query(query, params, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) if res
  res
end

#delete_object(objectID, request_options = {}) ⇒ Object

Delete an object from the index

Parameters:

  • objectID

    the unique identifier of object to delete

  • request_options (defaults to: {})

    contains extra parameters to send with your query

Raises:

  • (ArgumentError)


535
536
537
538
# File 'lib/algolia/index.rb', line 535

def delete_object(objectID, request_options = {})
  raise ArgumentError.new('objectID must not be blank') if objectID.nil? || objectID == ''
  client.delete(Protocol.object_uri(name, objectID), :write, request_options)
end

#delete_object!(objectID, request_options = {}) ⇒ Object

Delete an object from the index and wait end of indexing

Parameters:

  • objectID

    the unique identifier of object to delete

  • request_options (defaults to: {})

    contains extra parameters to send with your query



546
547
548
549
550
# File 'lib/algolia/index.rb', line 546

def delete_object!(objectID, request_options = {})
  res = delete_object(objectID, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  res
end

#delete_objects(objects, request_options = {}) ⇒ Object

Delete several objects

Parameters:

  • objects

    an array of objectIDs

  • request_options (defaults to: {})

    contains extra parameters to send with your query



558
559
560
561
# File 'lib/algolia/index.rb', line 558

def delete_objects(objects, request_options = {})
  check_array(objects)
  batch(build_batch('deleteObject', objects.map { |objectID| { :objectID => objectID } }, false), request_options)
end

#delete_objects!(objects, request_options = {}) ⇒ Object

Delete several objects and wait end of indexing

Parameters:

  • objects

    an array of objectIDs

  • request_options (defaults to: {})

    contains extra parameters to send with your query



569
570
571
572
573
# File 'lib/algolia/index.rb', line 569

def delete_objects!(objects, request_options = {})
  res = delete_objects(objects, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  res
end

#delete_rule(objectID, forward_to_replicas = false, request_options = {}) ⇒ Object

Delete a rule

Parameters:

  • objectID

    the rule objectID

  • forward_to_replicas (defaults to: false)

    should we forward the delete to replica indices

  • request_options (defaults to: {})

    contains extra parameters to send with your query



1142
1143
1144
# File 'lib/algolia/index.rb', line 1142

def delete_rule(objectID, forward_to_replicas = false, request_options = {})
  client.delete("#{Protocol.rule_uri(name, objectID)}?forwardToReplicas=#{forward_to_replicas}", :write, request_options)
end

#delete_rule!(objectID, forward_to_replicas = false, request_options = {}) ⇒ Object

Delete a rule and wait the end of indexing

Parameters:

  • objectID

    the rule objectID

  • forward_to_replicas (defaults to: false)

    should we forward the delete to replica indices

  • request_options (defaults to: {})

    contains extra parameters to send with your query



1153
1154
1155
1156
1157
# File 'lib/algolia/index.rb', line 1153

def delete_rule!(objectID, forward_to_replicas = false, request_options = {})
  res = delete_rule(objectID, forward_to_replicas, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  return res
end

#delete_synonym(objectID, forward_to_replicas = false, request_options = {}) ⇒ Object

Delete a synonym

Parameters:

  • objectID

    the synonym objectID

  • forward_to_replicas (defaults to: false)

    should we forward the delete to replica indices

  • request_options (defaults to: {})

    contains extra parameters to send with your query



966
967
968
# File 'lib/algolia/index.rb', line 966

def delete_synonym(objectID, forward_to_replicas = false, request_options = {})
  client.delete("#{Protocol.synonym_uri(name, objectID)}?forwardToReplicas=#{forward_to_replicas}", :write, request_options)
end

#delete_synonym!(objectID, forward_to_replicas = false, request_options = {}) ⇒ Object

Delete a synonym and wait the end of indexing

Parameters:

  • objectID

    the synonym objectID

  • forward_to_replicas (defaults to: false)

    should we forward the delete to replica indices

  • request_options (defaults to: {})

    contains extra parameters to send with your query



977
978
979
980
981
# File 'lib/algolia/index.rb', line 977

def delete_synonym!(objectID, forward_to_replicas = false, request_options = {})
  res = delete_synonym(objectID, forward_to_replicas, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  res
end

#existsBoolean Also known as: exists?

Check whether an index exists or not

Returns:

  • (Boolean)


1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
# File 'lib/algolia/index.rb', line 1285

def exists
  begin
    get_settings
  rescue AlgoliaProtocolError => e
    if e.code === 404
      return false
    end

    raise e
  end
  return true
end

#export_rules(hits_per_page = 100, request_options = {}, &_block) ⇒ Object

Export the full list of rules Accepts an optional block to which it will pass each rule Also returns an array with all the rules

Parameters:

  • hits_per_page (defaults to: 100)

    Amount of rules to retrieve on each internal request - Optional - Default: 100

  • request_options (defaults to: {})

    contains extra parameters to send with your query - Optional



1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
# File 'lib/algolia/index.rb', line 1265

def export_rules(hits_per_page = 100, request_options = {}, &_block)
  res = []
  page = 0
  loop do
    curr = search_rules('', { :hitsPerPage => hits_per_page, :page => page }, request_options)['hits']
    curr.each do |rule|
      res << rule
      yield rule if block_given?
    end
    break if curr.size < hits_per_page
    page += 1
  end
  res
end

#export_synonyms(hits_per_page = 100, request_options = {}, &_block) ⇒ Object

Export the full list of synonyms Accepts an optional block to which it will pass each synonym Also returns an array with all the synonyms

Parameters:

  • hits_per_page (defaults to: 100)

    Amount of synonyms to retrieve on each internal request - Optional - Default: 100

  • request_options (defaults to: {})

    contains extra parameters to send with your query - Optional



1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
# File 'lib/algolia/index.rb', line 1088

def export_synonyms(hits_per_page = 100, request_options = {}, &_block)
  res = []
  page = 0
  loop do
    curr = search_synonyms('', { :hitsPerPage => hits_per_page, :page => page }, request_options)['hits']
    curr.each do |synonym|
      res << synonym
      yield synonym if block_given?
    end
    break if curr.size < hits_per_page
    page += 1
  end
  res
end

#find_object(request_options = {}) ⇒ Hash

Find object by the given condition.

Options can be passed in request_options body:

- query (string): pass a query
- paginate (bool): choose if you want to iterate through all the

documents (true) or only the first page (false). Default is true. The function takes a block to filter the results from search query Usage example:

index.find_object({'query' => '', 'paginate' => true}) {|obj| obj.key?('company') and obj['company'] == 'Apple'}

Parameters:

  • request_options (defaults to: {})

    contains extra parameters to send with your query

Returns:

  • (Hash)

    the matching object and its position in the result set



282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/algolia/index.rb', line 282

def find_object(request_options = {})
  paginate = true
  page = 0

  query = request_options[:query] || request_options['query'] || ''
  request_options.delete(:query)
  request_options.delete('query')

  if request_options.has_key? :paginate
    paginate = request_options[:paginate]
  end

  if request_options.has_key? 'paginate'
    paginate = request_options['paginate']
  end

  request_options.delete(:paginate)
  request_options.delete('paginate')

  while true
    request_options['page'] = page
    res = search(query, request_options)

    res['hits'].each_with_index do |hit, i|
      if yield(hit)
        return {
            'object' => hit,
            'position' => i,
            'page' => page,
        }
      end
    end if block_given?

    has_next_page = page + 1 < res['nbPages']
    if !paginate || !has_next_page
      raise AlgoliaObjectNotFoundError.new('Object not found')
    end

    page += 1
  end
end

#get_api_key(key, request_options = {}) ⇒ Object Also known as: get_user_key

Get ACL of a user key

Deprecated: Please us ‘client.get_api_key` instead.



703
704
705
# File 'lib/algolia/index.rb', line 703

def get_api_key(key, request_options = {})
  client.get(Protocol.index_key_uri(name, key), :read, request_options)
end

#get_object(objectID, attributes_to_retrieve = nil, request_options = {}) ⇒ Object

Get an object from this index

Parameters:

  • objectID

    the unique identifier of the object to retrieve

  • attributes_to_retrieve (optional) (defaults to: nil)

    if set, contains the list of attributes to retrieve as an array of strings of a string separated by “,”

  • request_options (defaults to: {})

    contains extra parameters to send with your query



241
242
243
244
245
246
247
248
# File 'lib/algolia/index.rb', line 241

def get_object(objectID, attributes_to_retrieve = nil, request_options = {})
  attributes_to_retrieve = attributes_to_retrieve.join(',') if attributes_to_retrieve.is_a?(Array)
  if attributes_to_retrieve.nil?
    client.get(Protocol.object_uri(name, objectID, nil), :read, request_options)
  else
    client.get(Protocol.object_uri(name, objectID, { :attributes => attributes_to_retrieve }), :read, request_options)
  end
end

#get_objects(objectIDs, attributes_to_retrieve = nil, request_options = {}) ⇒ Object

Get a list of objects from this index

Parameters:

  • objectIDs

    the array of unique identifier of the objects to retrieve

  • attributes_to_retrieve (optional) (defaults to: nil)

    if set, contains the list of attributes to retrieve as an array of strings of a string separated by “,”

  • request_options (defaults to: {})

    contains extra parameters to send with your query



257
258
259
260
261
262
263
264
265
# File 'lib/algolia/index.rb', line 257

def get_objects(objectIDs, attributes_to_retrieve = nil, request_options = {})
  attributes_to_retrieve = attributes_to_retrieve.join(',') if attributes_to_retrieve.is_a?(Array)
  requests = objectIDs.map do |objectID|
    req = { :indexName => name, :objectID => objectID.to_s }
    req[:attributesToRetrieve] = attributes_to_retrieve unless attributes_to_retrieve.nil?
    req
  end
  client.post(Protocol.objects_uri, { :requests => requests }.to_json, :read, request_options)['results']
end

#get_rule(objectID, request_options = {}) ⇒ Object

Get a rule

Parameters:

  • objectID

    the rule objectID

  • request_options (defaults to: {})

    contains extra parameters to send with your query



1131
1132
1133
# File 'lib/algolia/index.rb', line 1131

def get_rule(objectID, request_options = {})
  client.get(Protocol.rule_uri(name, objectID), :read, request_options)
end

#get_settings(options = {}, request_options = {}) ⇒ Object

Get settings of this index



686
687
688
689
# File 'lib/algolia/index.rb', line 686

def get_settings(options = {}, request_options = {})
  options['getVersion'] = 2 if !options[:getVersion] && !options['getVersion']
  client.get(Protocol.settings_uri(name, options).to_s, :read, request_options)
end

#get_synonym(objectID, request_options = {}) ⇒ Object

Get a synonym

Parameters:

  • objectID

    the synonym objectID

  • request_options (defaults to: {})

    contains extra parameters to send with your query



955
956
957
# File 'lib/algolia/index.rb', line 955

def get_synonym(objectID, request_options = {})
  client.get(Protocol.synonym_uri(name, objectID), :read, request_options)
end

#get_task_status(taskID, request_options = {}) ⇒ Object

Check the status of a task on the server. All server task are asynchronous and you can check the status of a task with this method.

Parameters:

  • taskID

    the id of the task returned by server

  • request_options (defaults to: {})

    contains extra parameters to send with your query



343
344
345
# File 'lib/algolia/index.rb', line 343

def get_task_status(taskID, request_options = {})
  client.get_task_status(name, taskID, request_options)
end

#list_api_keys(request_options = {}) ⇒ Object Also known as: list_user_keys

List all existing user keys with their associated ACLs

Deprecated: Please us ‘client.list_api_keys` instead.



695
696
697
# File 'lib/algolia/index.rb', line 695

def list_api_keys(request_options = {})
  client.get(Protocol.index_keys_uri(name), :read, request_options)
end

#partial_update_object(object, objectID = nil, create_if_not_exits = true, request_options = {}) ⇒ Object

Update partially an object (only update attributes passed in argument)

Parameters:

  • object

    the object attributes to override

  • objectID (defaults to: nil)

    the associated objectID, if nil ‘object’ must contain an ‘objectID’ key

  • create_if_not_exits (defaults to: true)

    a boolean, if true creates the object if this one doesn’t exist

  • request_options (defaults to: {})

    contains extra parameters to send with your query



483
484
485
# File 'lib/algolia/index.rb', line 483

def partial_update_object(object, objectID = nil, create_if_not_exits = true, request_options = {})
  client.post(Protocol.partial_object_uri(name, get_objectID(object, objectID), create_if_not_exits), object.to_json, :write, request_options)
end

#partial_update_object!(object, objectID = nil, create_if_not_exits = true, request_options = {}) ⇒ Object

Update partially an object (only update attributes passed in argument) and wait indexing

Parameters:

  • object

    the attributes to override

  • objectID (defaults to: nil)

    the associated objectID, if nil ‘object’ must contain an ‘objectID’ key

  • create_if_not_exits (defaults to: true)

    a boolean, if true creates the object if this one doesn’t exist

  • request_options (defaults to: {})

    contains extra parameters to send with your query



523
524
525
526
527
# File 'lib/algolia/index.rb', line 523

def partial_update_object!(object, objectID = nil, create_if_not_exits = true, request_options = {})
  res = partial_update_object(object, objectID, create_if_not_exits, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  res
end

#partial_update_objects(objects, create_if_not_exits = true, request_options = {}) ⇒ Object

Partially override the content of several objects

Parameters:

  • objects

    an array of objects to update (each object must contains a objectID attribute)

  • create_if_not_exits (defaults to: true)

    a boolean, if true create the objects if they don’t exist

  • request_options (defaults to: {})

    contains extra parameters to send with your query



494
495
496
497
498
499
500
# File 'lib/algolia/index.rb', line 494

def partial_update_objects(objects, create_if_not_exits = true, request_options = {})
  if create_if_not_exits
    batch(build_batch('partialUpdateObject', objects, true), request_options)
  else
    batch(build_batch('partialUpdateObjectNoCreate', objects, true), request_options)
  end
end

#partial_update_objects!(objects, create_if_not_exits = true, request_options = {}) ⇒ Object

Partially override the content of several objects and wait end of indexing

Parameters:

  • objects

    an array of objects to update (each object must contains a objectID attribute)

  • create_if_not_exits (defaults to: true)

    a boolean, if true create the objects if they don’t exist

  • request_options (defaults to: {})

    contains extra parameters to send with your query



509
510
511
512
513
# File 'lib/algolia/index.rb', line 509

def partial_update_objects!(objects, create_if_not_exits = true, request_options = {})
  res = partial_update_objects(objects, create_if_not_exits, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  res
end

#replace_all_objects(objects, request_options = {}) ⇒ Object

Override the current objects by the given array of objects and wait end of indexing. Settings, synonyms and query rules are untouched. The objects are replaced without any downtime.

Parameters:

  • objects

    the array of objects to save

  • request_options (defaults to: {})

    contains extra parameters to send with your query



412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
# File 'lib/algolia/index.rb', line 412

def replace_all_objects(objects, request_options = {})
  safe = request_options[:safe] || request_options['safe'] || false
  request_options.delete(:safe)
  request_options.delete('safe')

  tmp_index = @client.init_index(@name + '_tmp_' + rand(10000000).to_s)

  responses = []

  scope = ['settings', 'synonyms', 'rules']
  res = @client.copy_index(@name, tmp_index.name, scope, request_options)
  responses << res

  if safe
    wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  end

  batch = []
  batch_size = 1000
  count = 0

  objects.each do |object|
    batch << object
    count += 1
    if count == batch_size
      res = tmp_index.add_objects(batch, request_options)
      responses << res
      batch = []
      count = 0
    end
  end

  if batch.any?
    res = tmp_index.add_objects(batch, request_options)
    responses << res
  end

  if safe
    responses.each do |res|
      tmp_index.wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
    end
  end

  res = @client.move_index(tmp_index.name, @name, request_options)
  responses << res

  if safe
    wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  end

  responses
end

#replace_all_objects!(objects, request_options = {}) ⇒ Object

Override the current objects by the given array of objects and wait end of indexing

Parameters:

  • objects

    the array of objects to save

  • request_options (defaults to: {})

    contains extra parameters to send with your query



471
472
473
# File 'lib/algolia/index.rb', line 471

def replace_all_objects!(objects, request_options = {})
  replace_all_objects(objects, request_options.merge(:safe => true))
end

#replace_all_rules(rules, request_options = {}) ⇒ Object

Replace rules in the index by the given array of rules

Parameters:

  • rules

    the array of rules to add

  • request_options (defaults to: {})

    contains extra parameters to send with your query



1240
1241
1242
1243
# File 'lib/algolia/index.rb', line 1240

def replace_all_rules(rules, request_options = {})
  forward_to_replicas = request_options[:forwardToReplicas] || request_options['forwardToReplicas'] || false
  batch_rules(rules, forward_to_replicas, true, request_options)
end

#replace_all_rules!(rules, request_options = {}) ⇒ Object

Replace rules in the index by the given array of rules and wait the end of indexing

Parameters:

  • rules

    the array of rules to add

  • request_options (defaults to: {})

    contains extra parameters to send with your query



1251
1252
1253
1254
1255
# File 'lib/algolia/index.rb', line 1251

def replace_all_rules!(rules, request_options = {})
  res = replace_all_rules(rules, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  res
end

#replace_all_synonyms(synonyms, request_options = {}) ⇒ Object

Replace synonyms in the index by the given array of synonyms

Parameters:

  • synonyms

    the array of synonyms to add

  • request_options (defaults to: {})

    contains extra parameters to send with your query



1063
1064
1065
1066
# File 'lib/algolia/index.rb', line 1063

def replace_all_synonyms(synonyms, request_options = {})
  forward_to_replicas = request_options[:forwardToReplicas] || request_options['forwardToReplicas'] || false
  batch_synonyms(synonyms, forward_to_replicas, true, request_options)
end

#replace_all_synonyms!(synonyms, request_options = {}) ⇒ Object

Replace synonyms in the index by the given array of synonyms and wait the end of indexing

Parameters:

  • synonyms

    the array of synonyms to add

  • request_options (defaults to: {})

    contains extra parameters to send with your query



1074
1075
1076
1077
1078
# File 'lib/algolia/index.rb', line 1074

def replace_all_synonyms!(synonyms, request_options = {})
  res = replace_all_synonyms(synonyms, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  res
end

#save_object(object, objectID = nil, request_options = {}) ⇒ Object

Override the content of an object

Parameters:

  • object

    the object to save

  • objectID (defaults to: nil)

    the associated objectID, if nil ‘object’ must contain an ‘objectID’ key

  • request_options (defaults to: {})

    contains extra parameters to send with your query



366
367
368
# File 'lib/algolia/index.rb', line 366

def save_object(object, objectID = nil, request_options = {})
  client.put(Protocol.object_uri(name, get_objectID(object, objectID)), object.to_json, :write, request_options)
end

#save_object!(object, objectID = nil, request_options = {}) ⇒ Object

Override the content of object and wait end of indexing

Parameters:

  • object

    the object to save

  • objectID (defaults to: nil)

    the associated objectID, if nil ‘object’ must contain an ‘objectID’ key

  • request_options (defaults to: {})

    contains extra parameters to send with your query



377
378
379
380
381
# File 'lib/algolia/index.rb', line 377

def save_object!(object, objectID = nil, request_options = {})
  res = save_object(object, objectID, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  res
end

#save_objects(objects, request_options = {}) ⇒ Object

Override the content of several objects

Parameters:

  • objects

    the array of objects to save, each object must contain an ‘objectID’ key

  • request_options (defaults to: {})

    contains extra parameters to send with your query



389
390
391
# File 'lib/algolia/index.rb', line 389

def save_objects(objects, request_options = {})
  batch(build_batch('updateObject', objects, true), request_options)
end

#save_objects!(objects, request_options = {}) ⇒ Object

Override the content of several objects and wait end of indexing

Parameters:

  • objects

    the array of objects to save, each object must contain an objectID attribute

  • request_options (defaults to: {})

    contains extra parameters to send with your query



399
400
401
402
403
# File 'lib/algolia/index.rb', line 399

def save_objects!(objects, request_options = {})
  res = save_objects(objects, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  res
end

#save_rule(objectID, rule, forward_to_replicas = false, request_options = {}) ⇒ Object

Save a rule

Parameters:

  • objectID

    the rule objectID

  • rule

    the rule

  • forward_to_replicas (defaults to: false)

    should we forward the delete to replica indices

  • request_options (defaults to: {})

    contains extra parameters to send with your query

Raises:

  • (ArgumentError)


1167
1168
1169
1170
# File 'lib/algolia/index.rb', line 1167

def save_rule(objectID, rule, forward_to_replicas = false, request_options = {})
  raise ArgumentError.new('objectID must not be blank') if objectID.nil? || objectID == ''
  client.put("#{Protocol.rule_uri(name, objectID)}?forwardToReplicas=#{forward_to_replicas}", rule.to_json, :write, request_options)
end

#save_rule!(objectID, rule, forward_to_replicas = false, request_options = {}) ⇒ Object

Save a rule and wait the end of indexing

Parameters:

  • objectID

    the rule objectID

  • rule

    the rule

  • forward_to_replicas (defaults to: false)

    should we forward the delete to replica indices

  • request_options (defaults to: {})

    contains extra parameters to send with your query



1180
1181
1182
1183
1184
# File 'lib/algolia/index.rb', line 1180

def save_rule!(objectID, rule, forward_to_replicas = false, request_options = {})
  res = save_rule(objectID, rule, forward_to_replicas, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  return res
end

#save_synonym(objectID, synonym, forward_to_replicas = false, request_options = {}) ⇒ Object

Save a synonym

Parameters:

  • objectID

    the synonym objectID

  • synonym

    the synonym

  • forward_to_replicas (defaults to: false)

    should we forward the delete to replica indices

  • request_options (defaults to: {})

    contains extra parameters to send with your query



991
992
993
# File 'lib/algolia/index.rb', line 991

def save_synonym(objectID, synonym, forward_to_replicas = false, request_options = {})
  client.put("#{Protocol.synonym_uri(name, objectID)}?forwardToReplicas=#{forward_to_replicas}", synonym.to_json, :write, request_options)
end

#save_synonym!(objectID, synonym, forward_to_replicas = false, request_options = {}) ⇒ Object

Save a synonym and wait the end of indexing

Parameters:

  • objectID

    the synonym objectID

  • synonym

    the synonym

  • forward_to_replicas (defaults to: false)

    should we forward the delete to replica indices

  • request_options (defaults to: {})

    contains extra parameters to send with your query



1003
1004
1005
1006
1007
# File 'lib/algolia/index.rb', line 1003

def save_synonym!(objectID, synonym, forward_to_replicas = false, request_options = {})
  res = save_synonym(objectID, synonym, forward_to_replicas, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  res
end

#search(query, params = {}, request_options = {}) ⇒ Object

Search inside the index

  • page: (integer) Pagination parameter used to select the page to retrieve.

    Page is zero-based and defaults to 0. Thus, to retrieve the 10th page you need to set page=9
    
  • hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20.

  • attributesToRetrieve: a string that contains the list of object attributes you want to retrieve (let you minimize the answer size). Attributes are separated with a comma (for example “name,address”). You can also use a string array encoding (for example [“name”,“address”]). By default, all attributes are retrieved. You can also use ‘*’ to retrieve all values when an attributesToRetrieve setting is specified for your index.

  • attributesToHighlight: a string that contains the list of attributes you want to highlight according to the query. Attributes are separated by a comma. You can also use a string array encoding (for example [“name”,“address”]). If an attribute has no match for the query, the raw value is returned. By default all indexed text attributes are highlighted. You can use ‘*` if you want to highlight all textual attributes. Numerical attributes are not highlighted. A matchLevel is returned for each highlighted attribute and can contain:

    - full: if all the query terms were found in the attribute,
    - partial: if only some of the query terms were found,
    - none: if none of the query terms were found.
    
  • attributesToSnippet: a string that contains the list of attributes to snippet alongside the number of words to return (syntax is ‘attributeName:nbWords`).

    Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10).
    You can also use a string array encoding (Example: attributesToSnippet: ["name:10","content:10"]). By default no snippet is computed.
    
  • minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word. Defaults to 3.

  • minWordSizefor2Typos: the minimum number of characters in a query word to accept two typos in this word. Defaults to 7.

  • getRankingInfo: if set to 1, the result hits will contain ranking information in _rankingInfo attribute.

  • aroundLatLng: search for entries around a given latitude/longitude (specified as two floats separated by a comma). For example aroundLatLng=47.316669,5.016670). You can specify the maximum distance in meters with the aroundRadius parameter (in meters) and the precision for ranking with aroundPrecision (for example if you set aroundPrecision=100, two objects that are distant of less than 100m will be considered as identical for “geo” ranking parameter). At indexing, you should specify geoloc of an object with the _geoloc attribute (in the form “lng”:2.348800})

  • insideBoundingBox: search entries inside a given area defined by the two extreme points of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng). For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201). At indexing, you should specify geoloc of an object with the _geoloc attribute (in the form “lng”:2.348800})

  • numericFilters: a string that contains the list of numeric filters you want to apply separated by a comma. The syntax of one filter is ‘attributeName` followed by `operand` followed by `value`. Supported operands are `<`, `<=`, `=`, `>` and `>=`. You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000. You can also use a string array encoding (for example numericFilters: [“price>100”,“price<1000”]).

  • tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas. To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3). You can also use a string array encoding, for example tagFilters: [“tag1”,] means tag1 AND (tag2 OR tag3). At indexing, tags should be added in the _tags** attribute of objects (for example href=""tag1","tag2"">_tags”:).

  • facetFilters: filter the query by a list of facets. Facets are separated by commas and each facet is encoded as ‘attributeName:value`. For example: `facetFilters=category:Book,author:John%20Doe`. You can also use a string array encoding (for example `[“category:Book”,“author:John%20Doe”]`).

  • facets: List of object attributes that you want to use for faceting. Attributes are separated with a comma (for example ‘“category,author”` ). You can also use a JSON string array encoding (for example [“category”,“author”]). Only attributes that have been added in attributesForFaceting index setting can be used in this parameter. You can also use `*` to perform faceting on all attributes specified in attributesForFaceting.

  • queryType: select how the query words are interpreted, it can be one of the following value:

    - prefixAll: all query words are interpreted as prefixes,
    - prefixLast: only the last word is interpreted as a prefix (default behavior),
    - prefixNone: no query word is interpreted as a prefix. This option is not recommended.
    
  • optionalWords: a string that contains the list of words that should be considered as optional when found in the query. The list of words is comma separated.

  • distinct: If set to 1, enable the distinct feature (disabled by default) if the attributeForDistinct index setting is set. This feature is similar to the SQL “distinct” keyword: when enabled in a query with the distinct=1 parameter, all hits containing a duplicate value for the attributeForDistinct attribute are removed from results. For example, if the chosen attribute is show_name and several hits have the same value for show_name, then only the best one is kept and others are removed.

Parameters:

  • query

    the full text query

  • args (optional)

    if set, contains an associative array with query parameters:

  • request_options (defaults to: {})

    contains extra parameters to send with your query



161
162
163
164
165
# File 'lib/algolia/index.rb', line 161

def search(query, params = {}, request_options = {})
  encoded_params = Hash[params.map { |k, v| [k.to_s, v.is_a?(Array) ? v.to_json : v] }]
  encoded_params[:query] = query
  client.post(Protocol.search_post_uri(name), { :params => Protocol.to_query(encoded_params) }.to_json, :search, request_options)
end

#search_disjunctive_faceting(query, disjunctive_facets, params = {}, refinements = {}, request_options = {}) ⇒ Object

Perform a search with disjunctive facets generating as many queries as number of disjunctive facets

Parameters:

  • query

    the query

  • disjunctive_facets

    the array of disjunctive facets

  • params (defaults to: {})

    a hash representing the regular query parameters

  • refinements (defaults to: {})

    a hash (“string” -> [“array”, “of”, “refined”, “values”]) representing the current refinements ex: { “my_facet1” => [“my_value1”, [“my_value2”], “my_disjunctive_facet1” => [“my_value1”, “my_value2”] }

  • request_options (defaults to: {})

    contains extra parameters to send with your query

Raises:

  • (ArgumentError)


842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
# File 'lib/algolia/index.rb', line 842

def search_disjunctive_faceting(query, disjunctive_facets, params = {}, refinements = {}, request_options = {})
  raise ArgumentError.new('Argument "disjunctive_facets" must be a String or an Array') unless disjunctive_facets.is_a?(String) || disjunctive_facets.is_a?(Array)
  raise ArgumentError.new('Argument "refinements" must be a Hash of Arrays') if !refinements.is_a?(Hash) || !refinements.select { |k, v| !v.is_a?(Array) }.empty?

  # extract disjunctive facets & associated refinements
  disjunctive_facets = disjunctive_facets.split(',') if disjunctive_facets.is_a?(String)
  disjunctive_refinements = {}
  refinements.each do |k, v|
    disjunctive_refinements[k] = v if disjunctive_facets.include?(k) || disjunctive_facets.include?(k.to_s)
  end

  # build queries
  queries = []
  ## hits + regular facets query
  filters = []
  refinements.to_a.each do |k, values|
    r = values.map { |v| "#{k}:#{v}" }
    if disjunctive_refinements[k.to_s] || disjunctive_refinements[k.to_sym]
      # disjunctive refinements are ORed
      filters << r
    else
      # regular refinements are ANDed
      filters += r
    end
  end
  queries << params.merge({ :index_name => self.name, :query => query, :facetFilters => filters })
  ## one query per disjunctive facet (use all refinements but the current one + hitsPerPage=1 + single facet)
  disjunctive_facets.each do |disjunctive_facet|
    filters = []
    refinements.each do |k, values|
      if k.to_s != disjunctive_facet.to_s
        r = values.map { |v| "#{k}:#{v}" }
        if disjunctive_refinements[k.to_s] || disjunctive_refinements[k.to_sym]
          # disjunctive refinements are ORed
          filters << r
        else
          # regular refinements are ANDed
          filters += r
        end
      end
    end
    queries << params.merge({
      :index_name => self.name,
      :query => query,
      :page => 0,
      :hitsPerPage => 1,
      :attributesToRetrieve => [],
      :attributesToHighlight => [],
      :attributesToSnippet => [],
      :facets => disjunctive_facet,
      :facetFilters => filters,
      :analytics => false
    })
  end
  answers = client.multiple_queries(queries, { :request_options => request_options })

  # aggregate answers
  ## first answer stores the hits + regular facets
  aggregated_answer = answers['results'][0]
  ## others store the disjunctive facets
  aggregated_answer['disjunctiveFacets'] = {}
  answers['results'].each_with_index do |a, i|
    next if i == 0
    a['facets'].each do |facet, values|
      ## add the facet to the disjunctive facet hash
      aggregated_answer['disjunctiveFacets'][facet] = values
      ## concatenate missing refinements
      (disjunctive_refinements[facet.to_s] || disjunctive_refinements[facet.to_sym] || []).each do |r|
        if aggregated_answer['disjunctiveFacets'][facet][r].nil?
          aggregated_answer['disjunctiveFacets'][facet][r] = 0
        end
      end
    end
  end

  aggregated_answer
end

#search_for_facet_values(facet_name, facet_query, search_parameters = {}, request_options = {}) ⇒ Object Also known as: search_facet

Search for facet values

Parameters:

  • facet_name

    Name of the facet to search. It must have been declared in the index’s`attributesForFaceting` setting with the ‘searchable()` modifier.

  • facet_query

    Text to search for in the facet’s values

  • search_parameters (defaults to: {})

    An optional query to take extra search parameters into account. These parameters apply to index objects like in a regular search query. Only facet values contained in the matched objects will be returned.

  • request_options (defaults to: {})

    contains extra parameters to send with your query



823
824
825
826
827
# File 'lib/algolia/index.rb', line 823

def search_for_facet_values(facet_name, facet_query, search_parameters = {}, request_options = {})
  params = search_parameters.clone
  params['facetQuery'] = facet_query
  client.post(Protocol.search_facet_uri(name, facet_name), params.to_json, :read, request_options)
end

#search_rules(query, params = {}, request_options = {}) ⇒ Object

Search rules

Parameters:

  • query

    the query

  • params (defaults to: {})

    an optional hash of :anchoring, :context, :page, :hitsPerPage

  • request_options (defaults to: {})

    contains extra parameters to send with your query



1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
# File 'lib/algolia/index.rb', line 1110

def search_rules(query, params = {}, request_options = {})
  anchoring = params[:anchoring]
  context = params[:context]
  page = params[:page] || params['page'] || 0
  hits_per_page = params[:hitsPerPage] || params['hitsPerPage'] || 20
  params = {
    :query => query,
    :page => page,
    :hitsPerPage => hits_per_page
  }
  params[:anchoring] = anchoring unless anchoring.nil?
  params[:context] = context unless context.nil?
  client.post(Protocol.search_rules_uri(name), params.to_json, :read, request_options)
end

#search_synonyms(query, params = {}, request_options = {}) ⇒ Object

Search synonyms

Parameters:

  • query

    the query

  • params (defaults to: {})

    an optional hash of :type, :page, :hitsPerPage

  • request_options (defaults to: {})

    contains extra parameters to send with your query



936
937
938
939
940
941
942
943
944
945
946
947
948
# File 'lib/algolia/index.rb', line 936

def search_synonyms(query, params = {}, request_options = {})
  type = params[:type] || params['type']
  type = type.join(',') if type.is_a?(Array)
  page = params[:page] || params['page'] || 0
  hits_per_page = params[:hitsPerPage] || params['hitsPerPage'] || 20
  params = {
    :query => query,
    :type => type.to_s,
    :page => page,
    :hitsPerPage => hits_per_page
  }
  client.post(Protocol.search_synonyms_uri(name), params.to_json, :read, request_options)
end

#set_settings(new_settings, options = {}, request_options = {}) ⇒ Object

Set settings for this index



670
671
672
# File 'lib/algolia/index.rb', line 670

def set_settings(new_settings, options = {}, request_options = {})
  client.put(Protocol.settings_uri(name, options), new_settings.to_json, :write, request_options)
end

#set_settings!(new_settings, options = {}, request_options = {}) ⇒ Object

Set settings for this index and wait end of indexing



677
678
679
680
681
# File 'lib/algolia/index.rb', line 677

def set_settings!(new_settings, options = {}, request_options = {})
  res = set_settings(new_settings, options, request_options)
  wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
  res
end

#update_api_key(key, object, validity = 0, max_queries_per_IP_per_hour = 0, max_hits_per_query = 0, request_options = {}) ⇒ Object Also known as: update_user_key

Deprecated: Please use ‘client.update_api_key` instead



774
775
776
777
778
779
780
781
782
783
784
785
786
# File 'lib/algolia/index.rb', line 774

def update_api_key(key, object, validity = 0, max_queries_per_IP_per_hour = 0, max_hits_per_query = 0, request_options = {})
  if object.instance_of?(Array)
    params = { :acl => object }
  else
    params = object
  end

  params['validity'] = validity.to_i if validity != 0
  params['maxHitsPerQuery'] = max_hits_per_query.to_i if max_hits_per_query != 0
  params['maxQueriesPerIPPerHour'] = max_queries_per_IP_per_hour.to_i if max_queries_per_IP_per_hour != 0

  client.put(Protocol.index_key_uri(name, key), params.to_json, :write, request_options)
end

#wait_task(taskID, time_before_retry = WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options = {}) ⇒ Object

Wait the publication of a task on the server. All server task are asynchronous and you can check with this method that the task is published.

Parameters:

  • taskID

    the id of the task returned by server

  • time_before_retry (defaults to: WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY)

    the time in milliseconds before retry (default = 100ms)

  • request_options (defaults to: {})

    contains extra parameters to send with your query



355
356
357
# File 'lib/algolia/index.rb', line 355

def wait_task(taskID, time_before_retry = WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options = {})
  client.wait_task(name, taskID, time_before_retry, request_options)
end