# Algolia Search API Client for Ruby
[Algolia Search](https://www.algolia.com) is a hosted full-text, numerical, and faceted search engine capable of delivering realtime results from the first keystroke.
Our Ruby client lets you easily use the [Algolia Search API](https://www.algolia.com/doc/rest) from your backend. It wraps the [Algolia Search REST API](https://www.algolia.com/doc/rest).
[![Build Status](https://travis-ci.org/algolia/algoliasearch-client-ruby.svg?branch=master)](https://travis-ci.org/algolia/algoliasearch-client-ruby) [![Gem Version](https://badge.fury.io/rb/algoliasearch.svg)](http://badge.fury.io/rb/algoliasearch) [![Code Climate](https://codeclimate.com/github/algolia/algoliasearch-client-ruby.svg)](https://codeclimate.com/github/algolia/algoliasearch-client-ruby) [![Coverage Status](https://coveralls.io/repos/algolia/algoliasearch-client-ruby/badge.png)](https://coveralls.io/r/algolia/algoliasearch-client-ruby)
Table of Contents
-----------------
**Getting Started**
1. [Setup](#setup)
1. [Quick Start](#quick-start)
1. [Guides & Tutorials](#guides-tutorials)
**Commands Reference**
1. [Add a new object](#add-a-new-object-to-the-index)
1. [Update an object](#update-an-existing-object-in-the-index)
1. [Search](#search)
1. [Multiple queries](#multiple-queries)
1. [Get an object](#get-an-object)
1. [Delete an object](#delete-an-object)
1. [Delete by query](#delete-by-query)
1. [Index settings](#index-settings)
1. [List indices](#list-indices)
1. [Delete an index](#delete-an-index)
1. [Clear an index](#clear-an-index)
1. [Wait indexing](#wait-indexing)
1. [Batch writes](#batch-writes)
1. [Security / User API Keys](#security--user-api-keys)
1. [Copy or rename an index](#copy-or-rename-an-index)
1. [Backup / Retrieve all index content](#backup--retrieve-of-all-index-content)
1. [Logs](#logs)
1. [Mock](#mock)
Setup
============
To setup your project, follow these steps:
1. Install AlgoliaSearch using gem install algoliasearch
.
2. Initialize the client with your ApplicationID and API-Key. You can find all of them on [your Algolia account](http://www.algolia.com/users/edit).
```ruby
require 'rubygems'
require 'algoliasearch'
Algolia.init :application_id => "YourApplicationID",
:api_key => "YourAPIKey"
```
### Ruby on Rails
If you're a Ruby on Rails user; you're probably looking for the [algoliasearch-rails](https://github.com/algolia/algoliasearch-rails) gem.
Quick Start
-------------
In 30 seconds, this quick start tutorial will show you how to index and search objects.
Without any prior configuration, you can start indexing [500 contacts](https://github.com/algolia/algoliasearch-client-csharp/blob/master/contacts.json) in the ```contacts``` index using the following code:
```ruby
index = Algolia::Index.new("contacts")
batch = JSON.parse(File.read("contacts.json"))
index.add_objects(batch)
```
You can now search for contacts using firstname, lastname, company, etc. (even with typos):
```ruby
# search by firstname
puts index.search('jimmie').to_json
# search a firstname with typo
puts index.search('jimie').to_json
# search for a company
puts index.search('california paint').to_json
# search for a firstname & company
puts index.search('jimmie paint').to_json
```
Settings can be customized to tune the search behavior. For example, you can add a custom sort by number of followers to the already great built-in relevance:
```ruby
index.set_settings({"customRanking" => ["desc(followers)"]})
```
You can also configure the list of attributes you want to index by order of importance (first = most important):
```ruby
index.set_settings({"attributesToIndex" => ["lastname", "firstname", "company",
"email", "city", "address"]})
```
Since the engine is designed to suggest results as you type, you'll generally search by prefix. In this case the order of attributes is very important to decide which hit is the best:
```ruby
puts index.search('or').to_json
puts index.search('jim').to_json
```
**Note:** If you are building a web application, you may be more interested in using our [JavaScript client](https://github.com/algolia/algoliasearch-client-js) to perform queries. It brings two benefits:
* Your users get a better response time by not going through your servers
* It will offload unnecessary tasks from your servers
```html
```
Guides & Tutorials
================
Check our [online guides](https://www.algolia.com/doc):
* [Data Formatting](https://www.algolia.com/doc/indexing/formatting-your-data)
* [Import and Synchronize data](https://www.algolia.com/doc/indexing/import-synchronize-data/ruby)
* [Autocomplete](https://www.algolia.com/doc/search/auto-complete)
* [Instant search page](https://www.algolia.com/doc/search/instant-search)
* [Filtering and Faceting](https://www.algolia.com/doc/search/filtering-faceting)
* [Sorting](https://www.algolia.com/doc/relevance/sorting)
* [Ranking Formula](https://www.algolia.com/doc/relevance/ranking)
* [Typo-Tolerance](https://www.algolia.com/doc/relevance/typo-tolerance)
* [Geo-Search](https://www.algolia.com/doc/geo-search/geo-search-overview)
* [Security](https://www.algolia.com/doc/security/best-security-practices)
* [API-Keys](https://www.algolia.com/doc/security/api-keys)
* [REST API](https://www.algolia.com/doc/rest)
Add a new object to the Index
==================
Each entry in an index has a unique identifier called `objectID`. There are two ways to add en entry to the index:
1. Using automatic `objectID` assignment. You will be able to access it in the answer.
2. Supplying your own `objectID`.
You don't need to explicitly create an index, it will be automatically created the first time you add an object.
Objects are schema less so you don't need any configuration to start indexing. If you wish to configure things, the settings section provides details about advanced settings.
Example with automatic `objectID` assignment:
```ruby
res = index.add_object({"firstname" => "Jimmie",
"lastname" => "Barninger"})
puts "ObjectID=" + res["objectID"]
```
Example with manual `objectID` assignment:
```ruby
res = index.add_object({"firstname" => "Jimmie",
"lastname" => "Barninger"}, "myID")
puts "ObjectID=" + res["objectID"]
```
Update an existing object in the Index
==================
You have three options when updating an existing object:
1. Replace all its attributes.
2. Replace only some attributes.
3. Apply an operation to some attributes.
Example on how to replace all attributes of an existing object:
```ruby
index.save_object({"firstname" => "Jimmie",
"lastname" => "Barninger",
"city" => "New York",
"objectID" => "myID"})
```
You have many ways to update an object's attributes:
1. Set the attribute value
2. Add a string or number element to an array
3. Remove an element from an array
4. Add a string or number element to an array if it doesn't exist
5. Increment an attribute
6. Decrement an attribute
Example to update only the city attribute of an existing object:
```ruby
index.partial_update_object({"city" => "San Francisco",
"objectID" => "myID"})
```
Example to add a tag:
```ruby
index.partial_update_object({"_tags" => {"value" => "MyTag", "_operation" => "Add"},
"objectID" => "myID"})
```
Example to remove a tag:
```ruby
index.partial_update_object({"_tags" => {"value" => "MyTag", "_operation" => "Remove"},
"objectID" => "myID"})
```
Example to add a tag if it doesn't exist:
```ruby
index.partial_update_object({"_tags" => {"value" => "MyTag", "_operation" => "AddUnique"},
"objectID" => "myID"})
```
Example to increment a numeric value:
```ruby
index.partial_update_object({"price" => {"value" => 42, "_operation" => "Increment"},
"objectID" => "myID"})
```
Note: Here we are incrementing the value by `42`. To increment just by one, put
`value:1`.
Example to decrement a numeric value:
```ruby
index.partial_update_object({"price" => {"value" => 42, "_operation" => "Decrement"},
"objectID" => "myID"})
```
Note: Here we are decrementing the value by `42`. To decrement just by one, put
`value:1`.
Search
==================
**Notes:** If you are building a web application, you may be more interested in using our [JavaScript client](https://github.com/algolia/algoliasearch-client-js) to perform queries. It brings two benefits:
* Your users get a better response time by not going through your servers
* It will offload unnecessary tasks from your servers.
To perform a search, you only need to initialize the index and perform a call to the search function.
The search query allows only to retrieve 1000 hits, if you need to retrieve more than 1000 hits for seo, you can use [Backup / Retrieve all index content](#backup--retrieve-of-all-index-content)
```ruby
index = Algolia::Index.new("contacts")
res = index.search("query string")
res = index.search("query string", { "attributesToRetrieve" => "firstname,lastname", "hitsPerPage" => 20})
```
The server response will look like:
```json
{
"hits": [
{
"firstname": "Jimmie",
"lastname": "Barninger",
"objectID": "433",
"_highlightResult": {
"firstname": {
"value": "Jimmie",
"matchLevel": "partial"
},
"lastname": {
"value": "Barninger",
"matchLevel": "none"
},
"company": {
"value": "California Paint & Wlpaper Str",
"matchLevel": "partial"
}
}
}
],
"page": 0,
"nbHits": 1,
"nbPages": 1,
"hitsPerPage": 20,
"processingTimeMS": 1,
"query": "jimmie paint",
"params": "query=jimmie+paint&attributesToRetrieve=firstname,lastname&hitsPerPage=50"
}
```
You can use the following optional arguments:
## Full Text Search Parameters
query |
The instant search query string, used to set the string you want to search in your index. If no query parameter is set, the textual search will match with all the objects. |
queryType |
Selects how the query words are interpreted. It can be one of the following values:
|
removeWordsIfNoResults |
This option is used to select a strategy in order to avoid having an empty result page. There are three different options:
|
minWordSizefor1Typo |
The minimum number of characters in a query word to accept one typo in this word. |
minWordSizefor2Typos |
The minimum number of characters in a query word to accept two typos in this word. |
typoTolerance |
This option allows you to control the number of typos allowed in the result set:
|
allowTyposOnNumericTokens |
If set to false, disables typo tolerance on numeric tokens (numbers). Defaults to true. |
ignorePlural |
If set to true, plural won't be considered as a typo. For example, car and cars, or foot and feet will be considered as equivalent. Defaults to false. |
disableTypoToleranceOnAttributes |
List of attributes on which you want to disable typo tolerance (must be a subset of the |
restrictSearchableAttributes |
List of attributes you want to use for textual search (must be a subset of the |
removeStopWords |
Remove the stop words from query before executing it. Defaults to false. Contains a list of stop words from 41 languages (Arabic, Armenian, Basque, Bengali, Brazilian, Bulgarian, Catalan, Chinese, Czech, Danish, Dutch, English, Finnish, French, Galician, German, Greek, Hindi, Hungarian, Indonesian, Irish, Italian, Japanese, Korean, Kurdish, Latvian, Lithuanian, Marathi, Norwegian, Persian, Polish, Portugese, Romanian, Russian, Slovak, Spanish, Swedish, Thai, Turkish, Ukranian, Urdu). In most use-cases, we don't recommend enabling this option. |
advancedSyntax |
Enables the advanced query syntax. Defaults to 0 (false).
|
analytics |
If set to false, this query will not be taken into account in the analytics feature. Defaults to true. |
synonyms |
If set to false, this query will not use synonyms defined in the configuration. Defaults to true. |
replaceSynonymsInHighlight |
If set to false, words matched via synonym expansion will not be replaced by the matched synonym in the highlight results. Defaults to true. |
optionalWords |
A string that contains the comma separated list of words that should be considered as optional when found in the query. |
page |
Pagination parameter used to select the page to retrieve. |
hitsPerPage |
Pagination parameter used to select the number of hits per page. Defaults to 20. |
aroundLatLng |
Search for entries around a given latitude/longitude (specified as two floats separated by a comma). By default the maximum distance is automatically guessed based on the density of the area but you can specify it manually in meters with the aroundRadius parameter. The precision for ranking can be set with aroundPrecision parameter. For example, if you set aroundPrecision=100, the distances will be considered by ranges of 100m, for example all distances 0 and 100m will be considered as identical for the "geo" ranking parameter. At indexing, you should specify geoloc of an object with the _geoloc attribute (in the form |
aroundLatLngViaIP |
Search for entries around a given latitude/longitude automatically computed from user IP address. You can specify the maximum distance in meters with the At indexing, you should specify the geo location of an object with the |
insideBoundingBox |
Search entries inside a given area defined by the two extreme points of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng). |
insidePolygon |
Search entries inside a given area defined by a set of points (defined by a minimum of 6 floats: p1Lat,p1Lng,p2Lat,p2Lng,p3Lat,p3Long). |
attributesToRetrieve |
A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer. Attributes are separated with a comma (for example |
attributesToHighlight |
A string that contains the list of attributes you want to highlight according to the query. Attributes are separated by commas. You can also use a string array encoding (for example
|
attributesToSnippet |
A string that contains the list of attributes to snippet alongside the number of words to return (syntax is You can also use a string array encoding (Example: |
getRankingInfo |
If set to 1, the result hits will contain ranking information in the |
highlightPreTag |
Specify the string that is inserted before the highlighted parts in the query result (defaults to |
highlightPostTag |
Specify the string that is inserted after the highlighted parts in the query result (defaults to |
snippetEllipsisText |
String used as an ellipsis indicator when a snippet is truncated (defaults to empty). |
numericFilters |
A string that contains the comma separated list of numeric filters you want to apply. The filter syntax is |
tagFilters |
Filter the query by a set of tags. You can AND tags by separating them with commas. To OR tags, you must add parentheses. For example, At indexing, tags should be added in the _tags attribute of objects. For example |
facetFilters |
Filter the query with a list of facets. Facets are separated by commas and is encoded as |
facets |
List of object attributes that you want to use for faceting. For each of the declared attributes, you'll be able to retrieve a list of the most relevant facet values, and their associated count for the current query. Attributes are separated by a comma. For example, |
maxValuesPerFacet |
Limit the number of facet values returned for each facet. For example, |
filters |
Filter the query with numeric, facet or/and tag filters. The syntax is a SQL like syntax, you can use the OR and AND keywords. The syntax for the underlying numeric, facet and tag filters is the same than in the other filters:
The list of keywords is:
|
distinct |
If set to 1, enables the distinct feature, disabled by default, if the |
attributesToIndex |
The list of attributes you want index (i.e. to make searchable). If set to null, all textual and numerical attributes of your objects are indexed. Make sure you updated this setting to get optimal results. This parameter has two important uses:
|
attributesForFaceting |
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 |
The name of the attribute used for the |
ranking |
Controls the way results are sorted. We have nine available criteria:
|
customRanking |
Lets you specify part of the ranking. The syntax of this condition is an array of strings containing attributes prefixed by the asc (ascending order) or desc (descending order) operator. For example, To get a full description of how the Custom Ranking works, you can have a look at our Ranking guide. |
queryType |
Select how the query words are interpreted. It can be one of the following values:
|
separatorsToIndex |
Specify the separators (punctuation characters) to index. By default, separators are not indexed. Use |
slaves |
The list of indices on which you want to replicate all write operations. In order to get response times in milliseconds, we pre-compute part of the ranking during indexing. If you want to use different ranking configurations depending of the use case, you need to create one index per ranking configuration. This option enables you to perform write operations only on this index and automatically update slave indices with the same operations. |
unretrievableAttributes |
The list of attributes that cannot be retrieved at query time. This feature allows you to have attributes that are used for indexing and/or ranking but cannot be retrieved. Defaults to null. Warning: for testing purposes, this setting is ignored when you're using the ADMIN API Key. |
allowCompressionOfIntegerArray |
Allows compression of big integer arrays. In data-intensive use-cases, we recommended enabling this feature and then storing the list of user IDs or rights as an integer array. When enabled, the integer array is reordered to reach a better compression ratio. Defaults to false. |
synonyms |
For example, you may want to retrieve the black ipad record when your users are searching for dark ipad, even if the word dark is not part of the record. To do this, you need to configure black as a synonym of dark. For example, |
placeholders |
This is an advanced use-case to define a token substitutable by a list of words without having the original token searchable. It is defined by a hash associating placeholders to lists of substitutable words. For example,
|
disableTypoToleranceOnWords |
Specify a list of words on which automatic typo tolerance will be disabled. |
disableTypoToleranceOnAttributes |
List of attributes on which you want to disable typo tolerance (must be a subset of the |
altCorrections |
Specify alternative corrections that you want to consider. Each alternative correction is described by an object containing three attributes:
For example |
minWordSizefor1Typo |
The minimum number of characters needed to accept one typo (default = 4). |
minWordSizefor2Typos |
The minimum number of characters needed to accept two typos (default = 8). |
hitsPerPage |
The number of hits per page (default = 10). |
attributesToRetrieve |
Default list of attributes to retrieve in objects. If set to null, all attributes are retrieved. |
attributesToHighlight |
Default list of attributes to highlight. If set to null, all indexed attributes are highlighted. |
attributesToSnippet |
Default list of attributes to snippet alongside the number of words to return (syntax is |
highlightPreTag |
Specify the string that is inserted before the highlighted parts in the query result (defaults to |
highlightPostTag |
Specify the string that is inserted after the highlighted parts in the query result (defaults to |
optionalWords |
Specify a list of words that should be considered optional when found in the query. |
allowTyposOnNumericTokens |
If set to false, disable typo-tolerance on numeric tokens (=numbers) in the query word. For example the query |
ignorePlurals |
If set to true, singular/plural forms won’t be considered as typos (for example car/cars and foot/feet will be considered as equivalent). Defaults to false. |
advancedSyntax |
Enable the advanced query syntax. Defaults to 0 (false).
|
replaceSynonymsInHighlight |
If set to false, words matched via synonyms expansion will not be replaced by the matched synonym in the highlighted result. Defaults to true. |
maxValuesPerFacet |
Limit the number of facet values returned for each facet. For example: |
distinct |
Enable the distinct feature (disabled by default) if the To get a full understanding of how |
typoTolerance |
This setting has four different options:
|
removeStopWords |
Remove stop words from query before executing it. Defaults to false. Contains stop words for 41 languages (Arabic, Armenian, Basque, Bengali, Brazilian, Bulgarian, Catalan, Chinese, Czech, Danish, Dutch, English, Finnish, French, Galician, German, Greek, Hindi, Hungarian, Indonesian, Irish, Italian, Japanese, Korean, Kurdish, Latvian, Lithuanian, Marathi, Norwegian, Persian, Polish, Portugese, Romanian, Russian, Slovak, Spanish, Swedish, Thai, Turkish, Ukranian, Urdu) |
validity |
Add a validity period. The key will be valid for a specific period of time (in seconds). |
maxQueriesPerIPPerHour |
Specify the maximum number of API calls allowed from an IP address per hour. Each time an API call is performed with this key, a check is performed. If the IP at the source of the call did more than this number of calls in the last hour, a 403 code is returned. Defaults to 0 (no rate limit). This parameter can be used to protect you from attempts at retrieving your entire index contents by massively querying the index. Note: If you are sending the query through your servers, you must use the |
maxHitsPerQuery |
Specify the maximum number of hits this API key can retrieve in one call. Defaults to 0 (unlimited). This parameter can be used to protect you from attempts at retrieving your entire index contents by massively querying the index. |
indexes |
Specify the list of targeted indices. You can target all indices starting with a prefix or ending with a suffix using the '*' character. For example, "dev_*" matches all indices starting with "dev_" and "*_dev" matches all indices ending with "_dev". Defaults to all indices if empty or blank. |
referers |
Specify the list of referers. You can target all referers starting with a prefix or ending with a suffix using the '*' character. For example, "algolia.com/*" matches all referers starting with "algolia.com/" and "*.algolia.com" matches all referers ending with ".algolia.com". Defaults to all referers if empty or blank. |
queryParameters |
Specify the list of query parameters. You can force the query parameters for a query using the url string format (param1=X¶m2=Y...). |
description |
Specify a description to describe where the key is used. |
offset |
Specify the first entry to retrieve (0-based, 0 is the most recent log entry). Defaults to 0. |
length |
Specify the maximum number of entries to retrieve starting at the offset. Defaults to 10. Maximum allowed value: 1,000. |
onlyErrors |
Retrieve only logs with an HTTP code different than 200 or 201. (deprecated) |
type |
Specify the type of logs to retrieve:
|