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



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

def Index.all
  Algolia.list_indexes
end

Instance Method Details

#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

#add_user_key(obj, validity = 0, maxQueriesPerIPPerHour = 0, maxHitsPerQuery = 0) ⇒ Object

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)


510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
# File 'lib/algolia/index.rb', line 510

def add_user_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

#batch(request) ⇒ Object

Send a batch request



582
583
584
# File 'lib/algolia/index.rb', line 582

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



587
588
589
590
591
# File 'lib/algolia/index.rb', line 587

def batch!(request)
  res = batch(request)
  wait_task(res['taskID'])
  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
# File 'lib/algolia/index.rb', line 178

def browse(pageOrQueryParameters = nil, hitsPerPage = nil, &block)
  if block_given?
    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
    IndexBrowser.new(client, name, params).browse(&block)
  else
    pageOrQueryParameters ||= 0
    hitsPerPage ||= 1000
    client.get(Protocol.browse_uri(name, {:page => pageOrQueryParameters, :hitsPerPage => hitsPerPage}), :read)
  end
end

#browse_from(cursor, hitsPerPage = 1000) ⇒ Object

Browse a single page from a specific cursor



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

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



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

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



408
409
410
411
412
# File 'lib/algolia/index.rb', line 408

def clear!
  res = clear
  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_by_query(query, params = {}) ⇒ Object

Delete all objects matching a query

Parameters:

  • query

    the query string

  • params (defaults to: {})

    the optional query parameters



380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
# File 'lib/algolia/index.rb', line 380

def delete_by_query(query, 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



338
339
340
# File 'lib/algolia/index.rb', line 338

def delete_object(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



347
348
349
350
351
# File 'lib/algolia/index.rb', line 347

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



358
359
360
361
# File 'lib/algolia/index.rb', line 358

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



368
369
370
371
372
# File 'lib/algolia/index.rb', line 368

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

#delete_user_key(key) ⇒ Object

Delete an existing user key



577
578
579
# File 'lib/algolia/index.rb', line 577

def delete_user_key(key)
  client.delete(Protocol.index_key_uri(name, key))
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 a string separated by “,”



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

def get_object(objectID, attributesToRetrieve = nil)
  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) ⇒ Object

Get a list of objects from this index

Parameters:

  • objectIDs

    the array of unique identifier of the objects to retrieve



225
226
227
# File 'lib/algolia/index.rb', line 225

def get_objects(objectIDs)
  client.post(Protocol.objects_uri, { :requests => objectIDs.map { |objectID| { :indexName => name, :objectID => objectID } } }.to_json, :read)['results']
end

#get_settingsObject

Get settings of this index



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

def get_settings
  client.get(Protocol.settings_uri(name), :read)
end

#get_user_key(key) ⇒ Object

Get ACL of a user key



481
482
483
# File 'lib/algolia/index.rb', line 481

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

#list_user_keysObject

List all existing user keys with their associated ACLs



476
477
478
# File 'lib/algolia/index.rb', line 476

def list_user_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



290
291
292
# File 'lib/algolia/index.rb', line 290

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



327
328
329
330
331
# File 'lib/algolia/index.rb', line 327

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



300
301
302
303
304
305
306
# File 'lib/algolia/index.rb', line 300

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



314
315
316
317
318
# File 'lib/algolia/index.rb', line 314

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



250
251
252
# File 'lib/algolia/index.rb', line 250

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



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

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



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

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



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

def save_objects!(objs)
  res = save_objects(objs)
  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)


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
676
# File 'lib/algolia/index.rb', line 600

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

#set_settings(new_settings) ⇒ Object

Set settings for this index

  • minWordSizefor1Typo: (integer) the minimum number of characters to accept one typo (default = 3).

  • minWordSizefor2Typos: (integer) the minimum number of characters to accept two typos (default = 7).

  • hitsPerPage: (integer) the number of hits per page (default = 10).

  • attributesToRetrieve: (array of strings) default list of attributes to retrieve in objects. If set to null, all attributes are retrieved.

  • attributesToHighlight: (array of strings) default list of attributes to highlight. If set to null, all indexed attributes are highlighted.

  • attributesToSnippet**: (array of strings) default list of attributes to snippet alongside the number of words to return (syntax is attributeName:nbWords). By default no snippet is computed. If set to null, no snippet is computed.

  • attributesToIndex: (array of strings) the list of fields you want to index. If set to null, all textual and numerical attributes of your objects are indexed, but you should update it to get optimal results. This parameter has two important uses:

    - Limit the attributes to index: For example if you store a binary image in base64, you want to store it and be able to
      retrieve it but you don't want to search in the base64 string.
    - Control part of the ranking*: (see the ranking parameter for full explanation) Matches in attributes at the beginning of
      the list will be considered more important than matches in attributes further down the list.
      In one attribute, matching text at the beginning of the attribute will be considered more important than text after, you can disable
      this behavior if you add your attribute inside `unordered(AttributeName)`, for example attributesToIndex: ["title", "unordered(text)"].
    
  • attributesForFaceting: (array of strings) The list of fields you want to use for faceting. All strings in the attribute selected for faceting are extracted and added as a facet. If set to null, no attribute is used for faceting.

  • attributeForDistinct: (string) The attribute name used for the Distinct feature. This feature is similar to the SQL “distinct” keyword: when enabled in query with the distinct=1 parameter, all hits containing a duplicate value for this 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.

  • ranking: (array of strings) controls the way results are sorted. We have six available criteria:

    - typo: sort according to number of typos,
    - geo: sort according to decreassing distance when performing a geo-location based search,
    - proximity: sort according to the proximity of query words in hits,
    - attribute: sort according to the order of attributes defined by attributesToIndex,
    - exact:
        - if the user query contains one word: sort objects having an attribute that is exactly the query word before others.
          For example if you search for the "V" TV show, you want to find it with the "V" query and avoid to have all popular TV
          show starting by the v letter before it.
        - if the user query contains multiple words: sort according to the number of words that matched exactly (and not as a prefix).
    - custom: sort according to a user defined formula set in **customRanking** attribute.
    

    The standard order is [“typo”, “geo”, “proximity”, “attribute”, “exact”, “custom”]

  • customRanking: (array of strings) lets you specify part of the ranking. The syntax of this condition is an array of strings containing attributes prefixed by asc (ascending order) or desc (descending order) operator. For example ‘“customRanking” => [“desc(population)”, “asc(name)”]`

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

  • highlightPreTag: (string) Specify the string that is inserted before the highlighted parts in the query result (default to “<em>”).

  • highlightPostTag: (string) Specify the string that is inserted after the highlighted parts in the query result (default to “</em>”).

  • optionalWords: (array of strings) Specify a list of words that should be considered as optional when found in the query.

Parameters:

  • settigns

    the settings object that can contains :



466
467
468
# File 'lib/algolia/index.rb', line 466

def set_settings(new_settings)
  client.put(Protocol.settings_uri(name), new_settings.to_json)
end

#update_user_key(key, obj, validity = 0, maxQueriesPerIPPerHour = 0, maxHitsPerQuery = 0) ⇒ Object

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)


555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
# File 'lib/algolia/index.rb', line 555

def update_user_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)



235
236
237
238
239
240
241
242
243
# File 'lib/algolia/index.rb', line 235

def wait_task(taskID, timeBeforeRetry = 100)
  loop do
    status = client.get(Protocol.task_uri(name, taskID), :read)["status"]
    if status == "published"
      return
    end
    sleep(timeBeforeRetry.to_f / 1000)
  end
end