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

.allObject

Alias of Algolia.list_indexes



680
681
682
# File 'lib/algolia/index.rb', line 680

def Index.all
  Algolia.list_indexes
end

Instance Method Details

#add_api_key(obj, validity = 0, maxQueriesPerIPPerHour = 0, maxHitsPerQuery = 0) ⇒ Object Also known as: add_user_key

Create a new user key

@param obj can be two different parameters:
      The list of parameters for this key. Defined by a NSDictionary 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 NSString 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 maxQueriesPerIPPerHour the maximum number of API calls allowed from an IP address per hour (0 means unlimited)
@param maxHitsPerQuery  the maximum number of hits this API key can retrieve in one call (0 means unlimited)


492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
# File 'lib/algolia/index.rb', line 492

def add_api_key(obj, validity = 0, maxQueriesPerIPPerHour = 0, maxHitsPerQuery = 0)
  if obj.instance_of? Array
    params = {
      :acl => obj
    }
  else
    params = obj
  end
  if validity != 0
    params["validity"] = validity.to_i
  end
  if maxQueriesPerIPPerHour != 0
    params["maxQueriesPerIPPerHour"] = maxQueriesPerIPPerHour.to_i
  end
  if maxHitsPerQuery != 0
    params["maxHitsPerQuery"] = maxHitsPerQuery.to_i
  end
  client.post(Protocol.index_keys_uri(name), params.to_json)
end

#add_object(obj, objectID = nil) ⇒ Object

Add an object in this index

Parameters:

  • obj

    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)



38
39
40
41
42
43
44
45
# File 'lib/algolia/index.rb', line 38

def add_object(obj, objectID = nil)
  check_object obj
  if objectID.nil? || objectID.to_s.empty?
    client.post(Protocol.index_uri(name), obj.to_json)
  else
    client.put(Protocol.object_uri(name, objectID), obj.to_json)
  end
end

#add_object!(obj, objectID = nil) ⇒ Object

Add an object in this index and wait end of indexing

Parameters:

  • obj

    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)



53
54
55
56
57
# File 'lib/algolia/index.rb', line 53

def add_object!(obj, objectID = nil)
  res = add_object(obj, objectID)
  wait_task(res["taskID"])
  return res
end

#add_objects(objs) ⇒ Object

Add several objects in this index

Parameters:

  • objs

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



63
64
65
# File 'lib/algolia/index.rb', line 63

def add_objects(objs)
  batch build_batch('addObject', objs, false)
end

#add_objects!(obj) ⇒ Object

Add several objects in this index and wait end of indexing

Parameters:

  • objs

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



71
72
73
74
75
# File 'lib/algolia/index.rb', line 71

def add_objects!(obj)
  res = add_objects(obj)
  wait_task(res["taskID"])
  return res
end

#batch(request) ⇒ Object

Send a batch request



564
565
566
# File 'lib/algolia/index.rb', line 564

def batch(request)
  client.post(Protocol.batch_uri(name), request.to_json, :batch)
end

#batch!(request) ⇒ Object

Send a batch request and wait the end of the indexing



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

def batch!(request)
  res = batch(request)
  wait_task(res['taskID'])
  res
end

#batch_synonyms(synonyms, forward_to_replicas = false, replace_existing_synonyms = false) ⇒ 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



768
769
770
# File 'lib/algolia/index.rb', line 768

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

#batch_synonyms!(synonyms, forward_to_replicas = false, replace_existing_synonyms = false) ⇒ 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



777
778
779
780
781
# File 'lib/algolia/index.rb', line 777

def batch_synonyms!(synonyms, forward_to_replicas = false, replace_existing_synonyms = false)
  res = batch_synonyms(synonyms, forward_to_replicas, replace_existing_synonyms)
  wait_task(res["taskID"])
  return res
end

#browse(pageOrQueryParameters = nil, hitsPerPage = nil, &block) ⇒ Object

Browse all index content

@DEPRECATED:

Parameters:

  • pageOrQueryParameters (defaults to: nil)

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

  • pageOrQueryParameters (defaults to: nil)

    Pagination parameter used to select the page to retrieve.

  • hitsPerPage:

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



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/algolia/index.rb', line 178

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

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

#browse_from(cursor, hitsPerPage = 1000) ⇒ Object

Browse a single page from a specific cursor



203
204
205
# File 'lib/algolia/index.rb', line 203

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

#clearObject Also known as: clear_index

Delete the index content



421
422
423
# File 'lib/algolia/index.rb', line 421

def clear
  client.post(Protocol.clear_uri(name))
end

#clear!Object Also known as: clear_index!

Delete the index content and wait end of indexing



429
430
431
432
433
# File 'lib/algolia/index.rb', line 429

def clear!
  res = clear
  wait_task(res["taskID"])
  return res
end

#clear_synonyms(forward_to_replicas = false) ⇒ Object

Clear all synonyms

Parameters:

  • forward_to_replicas (defaults to: false)

    should we forward the delete to replica indices



750
751
752
# File 'lib/algolia/index.rb', line 750

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

#clear_synonyms!(forward_to_replicas = false) ⇒ 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



757
758
759
760
761
# File 'lib/algolia/index.rb', line 757

def clear_synonyms!(forward_to_replicas = false)
  res = clear_synonyms(forward_to_replicas)
  wait_task(res["taskID"])
  return res
end

#deleteObject Also known as: delete_index

Delete an index

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



17
18
19
# File 'lib/algolia/index.rb', line 17

def delete
  client.delete(Protocol.index_uri(name))
end

#delete!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” }



25
26
27
28
29
# File 'lib/algolia/index.rb', line 25

def delete!
  res = delete
  wait_task(res['taskID'])
  res
end

#delete_api_key(key) ⇒ Object Also known as: delete_user_key

Delete an existing user key



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

def delete_api_key(key)
  client.delete(Protocol.index_key_uri(name, key))
end

#delete_by_query(query, params = nil) ⇒ Object

Delete all objects matching a query

Parameters:

  • query

    the query string

  • params (defaults to: nil)

    the optional query parameters

Raises:

  • (ArgumentError)


399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
# File 'lib/algolia/index.rb', line 399

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

  params[:hitsPerPage] = 1000
  params[:attributesToRetrieve] = ['objectID']
  loop do
    res = search(query, params)
    break if res['hits'].empty?
    res = delete_objects(res['hits'].map { |h| h['objectID'] })
    wait_task res['taskID']
  end
end

#delete_object(objectID) ⇒ Object

Delete an object from the index

Parameters:

  • objectID

    the unique identifier of object to delete

Raises:

  • (ArgumentError)


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

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

#delete_object!(objectID) ⇒ Object

Delete an object from the index and wait end of indexing

Parameters:

  • objectID

    the unique identifier of object to delete



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

def delete_object!(objectID)
  res = delete_object(objectID)
  wait_task(res["taskID"])
  return res
end

#delete_objects(objs) ⇒ Object

Delete several objects

Parameters:

  • objs

    an array of objectIDs



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

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

#delete_objects!(objs) ⇒ Object

Delete several objects and wait end of indexing

Parameters:

  • objs

    an array of objectIDs



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

def delete_objects!(objs)
  res = delete_objects(objs)
  wait_task(res["taskID"])
  return res
end

#delete_synonym(objectID, forward_to_replicas = false) ⇒ Object

Delete a synonym

Parameters:

  • objectID

    the synonym objectID

  • forward_to_replicas (defaults to: false)

    should we forward the delete to replica indices



713
714
715
# File 'lib/algolia/index.rb', line 713

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

#delete_synonym!(objectID, forward_to_replicas = false) ⇒ 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



721
722
723
724
725
# File 'lib/algolia/index.rb', line 721

def delete_synonym!(objectID, forward_to_replicas = false)
  res = delete_synonym(objectID, forward_to_replicas)
  wait_task(res["taskID"])
  return res
end

#get_api_key(key) ⇒ Object Also known as: get_user_key

Get ACL of a user key



463
464
465
# File 'lib/algolia/index.rb', line 463

def get_api_key(key)
  client.get(Protocol.index_key_uri(name, key), :read)
end

#get_object(objectID, attributesToRetrieve = nil) ⇒ Object

Get an object from this index

Parameters:

  • objectID

    the unique identifier of the object to retrieve

  • attributesToRetrieve (optional) (defaults to: nil)

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



213
214
215
216
217
218
219
220
# File 'lib/algolia/index.rb', line 213

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

#get_objects(objectIDs, attributesToRetrieve = nil) ⇒ Object

Get a list of objects from this index

Parameters:

  • objectIDs

    the array of unique identifier of the objects to retrieve

  • attributesToRetrieve (optional) (defaults to: nil)

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



228
229
230
231
232
233
234
235
236
# File 'lib/algolia/index.rb', line 228

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

#get_settings(options = {}) ⇒ Object

Get settings of this index



452
453
454
455
# File 'lib/algolia/index.rb', line 452

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

#get_synonym(objectID) ⇒ Object

Get a synonym

Parameters:

  • objectID

    the synonym objectID



705
706
707
# File 'lib/algolia/index.rb', line 705

def get_synonym(objectID)
  client.get(Protocol.synonym_uri(name, objectID), :read)
end

#get_task_status(taskID) ⇒ 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



243
244
245
# File 'lib/algolia/index.rb', line 243

def get_task_status(taskID)
  client.get(Protocol.task_uri(name, taskID), :read)["status"]
end

#list_api_keysObject Also known as: list_user_keys

List all existing user keys with their associated ACLs



458
459
460
# File 'lib/algolia/index.rb', line 458

def list_api_keys
  client.get(Protocol.index_keys_uri(name), :read)
end

#partial_update_object(obj, objectID = nil, create_if_not_exits = true) ⇒ Object

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

Parameters:

  • obj

    the object attributes to override

  • objectID (defaults to: nil)

    the associated objectID, if nil ‘obj’ 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



308
309
310
# File 'lib/algolia/index.rb', line 308

def partial_update_object(obj, objectID = nil, create_if_not_exits = true)
  client.post(Protocol.partial_object_uri(name, get_objectID(obj, objectID), create_if_not_exits), obj.to_json)
end

#partial_update_object!(obj, objectID = nil, create_if_not_exits = true) ⇒ Object

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

Parameters:

  • obj

    the attributes to override

  • objectID (defaults to: nil)

    the associated objectID, if nil ‘obj’ 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



345
346
347
348
349
# File 'lib/algolia/index.rb', line 345

def partial_update_object!(obj, objectID = nil, create_if_not_exits = true)
  res = partial_update_object(obj, objectID, create_if_not_exits)
  wait_task(res["taskID"])
  return res
end

#partial_update_objects(objs, create_if_not_exits = true) ⇒ Object

Partially Override the content of several objects

Parameters:

  • objs

    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



318
319
320
321
322
323
324
# File 'lib/algolia/index.rb', line 318

def partial_update_objects(objs, create_if_not_exits = true)
  if create_if_not_exits
    batch build_batch('partialUpdateObject', objs, true)
  else
    batch build_batch('partialUpdateObjectNoCreate', objs, true)
  end
end

#partial_update_objects!(objs, create_if_not_exits = true) ⇒ Object

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

Parameters:

  • objs

    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



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

def partial_update_objects!(objs, create_if_not_exits = true)
  res = partial_update_objects(objs, create_if_not_exits)
  wait_task(res["taskID"])
  return res
end

#save_object(obj, objectID = nil) ⇒ Object

Override the content of an object

Parameters:

  • obj

    the object to save

  • objectID (defaults to: nil)

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



268
269
270
# File 'lib/algolia/index.rb', line 268

def save_object(obj, objectID = nil)
  client.put(Protocol.object_uri(name, get_objectID(obj, objectID)), obj.to_json)
end

#save_object!(obj, objectID = nil) ⇒ Object

Override the content of object and wait end of indexing

Parameters:

  • obj

    the object to save

  • objectID (defaults to: nil)

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



277
278
279
280
281
# File 'lib/algolia/index.rb', line 277

def save_object!(obj, objectID = nil)
  res = save_object(obj, objectID)
  wait_task(res["taskID"])
  return res
end

#save_objects(objs) ⇒ Object

Override the content of several objects

Parameters:

  • objs

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



287
288
289
# File 'lib/algolia/index.rb', line 287

def save_objects(objs)
  batch build_batch('updateObject', objs, true)
end

#save_objects!(objs) ⇒ Object

Override the content of several objects and wait end of indexing

Parameters:

  • objs

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



295
296
297
298
299
# File 'lib/algolia/index.rb', line 295

def save_objects!(objs)
  res = save_objects(objs)
  wait_task(res["taskID"])
  return res
end

#save_synonym(objectID, synonym, forward_to_replicas = false) ⇒ 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



732
733
734
# File 'lib/algolia/index.rb', line 732

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

#save_synonym!(objectID, synonym, forward_to_replicas = false) ⇒ 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



741
742
743
744
745
# File 'lib/algolia/index.rb', line 741

def save_synonym!(objectID, synonym, forward_to_replicas = false)
  res = save_synonym(objectID, synonym, forward_to_replicas)
  wait_task(res["taskID"])
  return res
end

#search(query, params = {}) ⇒ 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:



138
139
140
141
142
# File 'lib/algolia/index.rb', line 138

def search(query, params = {})
  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)
end

#search_disjunctive_faceting(query, disjunctive_facets, params = {}, refinements = {}) ⇒ 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”] }

Raises:

  • (ArgumentError)


599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
# File 'lib/algolia/index.rb', line 599

def search_disjunctive_faceting(query, disjunctive_facets, params = {}, refinements = {})
  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)

  # 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, text, query = {}) ⇒ Object Also known as: search_facet

Search for facet values

Parameters:

  • facet

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

  • text

    Text to search for in the facet’s values

  • query (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.



583
584
585
586
587
# File 'lib/algolia/index.rb', line 583

def search_for_facet_values(facet, text, query = {})
  params = query.clone
  params['facetQuery'] = text
  client.post(Protocol.search_facet_uri(name, facet), params.to_json)
end

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

Search synonyms

Parameters:

  • query

    the query

  • params (defaults to: {})

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



688
689
690
691
692
693
694
695
696
697
698
699
700
# File 'lib/algolia/index.rb', line 688

def search_synonyms(query, params = {})
  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)
end

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

Set settings for this index



439
440
441
# File 'lib/algolia/index.rb', line 439

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

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

Set settings for this index and wait end of indexing



445
446
447
448
449
# File 'lib/algolia/index.rb', line 445

def set_settings!(new_settings, options = {})
  res = set_settings(new_settings, options)
  wait_task(res["taskID"])
  return res
end

#update_api_key(key, obj, validity = 0, maxQueriesPerIPPerHour = 0, maxHitsPerQuery = 0) ⇒ Object Also known as: update_user_key

Update a user key

@param obj can be two different parameters:
      The list of parameters for this key. Defined by a NSDictionary 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 NSString 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 maxQueriesPerIPPerHour the maximum number of API calls allowed from an IP address per hour (0 means unlimited)
@param maxHitsPerQuery  the maximum number of hits this API key can retrieve in one call (0 means unlimited)


537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
# File 'lib/algolia/index.rb', line 537

def update_api_key(key, obj, validity = 0, maxQueriesPerIPPerHour = 0, maxHitsPerQuery = 0)
  if obj.instance_of? Array
    params = {
      :acl => obj
    }
  else
    params = obj
  end
  if validity != 0
    params["validity"] = validity.to_i
  end
  if maxQueriesPerIPPerHour != 0
    params["maxQueriesPerIPPerHour"] = maxQueriesPerIPPerHour.to_i
  end
  if maxHitsPerQuery != 0
    params["maxHitsPerQuery"] = maxHitsPerQuery.to_i
  end
  client.put(Protocol.index_key_uri(name, key), params.to_json)
end

#wait_task(taskID, timeBeforeRetry = 100) ⇒ 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

  • timeBeforeRetry (defaults to: 100)

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



253
254
255
256
257
258
259
260
261
# File 'lib/algolia/index.rb', line 253

def wait_task(taskID, timeBeforeRetry = 100)
  loop do
    status = get_task_status(taskID)
    if status == "published"
      return
    end
    sleep(timeBeforeRetry.to_f / 1000)
  end
end