View Source Algolia (algolia v0.11.0)

Elixir implementation of Algolia Search API.

You can interact with Algolia's API by creating a new client using new/1, and then using the other functions in this modules to make requests with that client.

Summary

Types

A client to use to communicate with Algolia.

The name of an Algolia index.

Generic options that can be passed to any API function.

Functions

Adds an object to an index, or replaces an existing one.

Adds or replaces multiple objects in an index.

Browses a single index.

Clears all objects from an index.

Removes all objects matching a filter.

Deletes a single object by its object ID.

Deletes multiple objects by object ID.

Gets the logs of the latest search and indexing operations.

Retrieves a single object from an index by ID.

Gets the settings of a index.

Performs multiple search queries in a single request.

Creates a new Algolia client.

Pushes events to the Insights API.

Saves a single object, replacing it if it already exists.

Saves multiple objects, replacing any that already exist.

Searches a single index.

Waits on the task created by a previous request.

Waits for a task for an index to complete.

Types

@type client() :: Tesla.Client.t()

A client to use to communicate with Algolia.

All API functions require a client to be able to make requests.

@type index() :: String.t()

The name of an Algolia index.

@type multi_strategy() :: nil | :stop_if_enough_matches
@type request_option() :: {:headers, Tesla.Env.headers()}

Generic options that can be passed to any API function.

@type result(resp) :: {:ok, resp} | {:error, any()}

Functions

Link to this function

add_object(client, index, object, opts \\ [])

View Source
@spec add_object(client(), index(), map(), [
  {:id_attribute, atom() | String.t()} | request_option()
]) ::
  result(map())

Adds an object to an index, or replaces an existing one.

If the object does not have an :objectID or "objectID" key, then Algolia will automatically generate one and add it to the object.

The :id_attribute option can be used to set the :objectID key based on an existing key already on the object.

Examples

# add an object with automatically generated object ID
Algolia.add_object(client, "my_index", %{
  kind: "fruit",
  color: "red",
  name: "apple"
})

# add or replace an object based on the object ID
Algolia.add_object(client, "my_index", %{
  objectID: "123",
  kind: "fruit",
  color: "red",
  name: "apple"
})

# set the object ID based on another attribute
Algolia.add_object(client, "my_index", %{
  kind: "fruit",
  color: "red",
  name: "apple"
}, id_attribute: :name)
# resulting objectID is "apple"

Options

  • :id_attribute - key to use as the :objectID of the object. If set, the saved object will have both :objectID and this key set to the same value.
  • :headers - list of additional HTTP headers to include in the request.
Link to this function

add_objects(client, index, objects, opts \\ [])

View Source
@spec add_objects(client(), index(), [map()], [
  {:id_attribute, atom() | String.t()} | request_option()
]) ::
  result(map())

Adds or replaces multiple objects in an index.

If any objects do not have an :objectID or "objectID" key, then Algolia will automatically generate one and add it to the object.

The :id_attribute option can be used to set the :objectID key based on an existing key already on the object.

Examples

# with automatically assigned object IDs
Algolia.add_objects(client, "my_index", [
  %{name: "apple"},
  %{name: "banana"},
  %{name: "pear"}
])

# adding or replacing objects based on object ID
Algolia.add_objects(client, "my_index", [
  %{objectID: "fruit1", name: "apple"},
  %{objectID: "fruit2", name: "banana"},
  %{objectID: "fruit3", name: "pear"}
])

# use the `:name` as the object IDs
Algolia.add_objects(client, "my_index", [
  %{name: "apple"},
  %{name: "banana"},
  %{name: "pear"}
], id_attribute: :name)

Options

  • :id_attribute - key to use as the :objectID of the objects. If set, the saved objects will have both :objectID and this key set to the same value.
  • :headers - list of additional HTTP headers to include in the request.
Link to this function

browse(client, index, opts \\ [])

View Source
@spec browse(client(), index(), [request_option() | {atom(), any()}]) :: result(map())

Browses a single index.

Browsing is similar to searching, but it skips ranking results and allows fetching more objects.

Example

Algolia.browse(client, "my_index", filters: "color:red AND kind:fruit")

Options

Any of Algolia's supported search parameters can be passed as options, with the exception of :distinct which is not supported when browsing.

Additional options

  • :headers - list of additional HTTP headers to include in the request.
Link to this function

clear_index(client, index, opts \\ [])

View Source
@spec clear_index(client(), index(), [request_option()]) :: result(map())

Clears all objects from an index.

Options

  • :headers - list of additional HTTP headers to include in the request.
Link to this function

copy_index(client, src_index, dst_index, opts \\ [])

View Source
@spec copy_index(client(), index(), index(), [request_option()]) :: result(map())

Copies an index to a new one.

Options

  • :headers - list of additional HTTP headers to include in the request.
Link to this function

delete_by(client, index, opts)

View Source
@spec delete_by(client(), index(), [{atom(), any()} | request_option()]) ::
  result(map())

Removes all objects matching a filter.

Examples

iex> Algolia.delete_by(client, "index", filters: ["score < 30"])
{:ok,
  %{"indexName" => "index",
    "taskId" => 42,
    "deletedAt" => "2018-10-30T15:33:13.556Z"}}

Options

Allowed filter parameters:

  • filters
  • facetFilters
  • numericFilters
  • aroundLatLng and aroundRadius (these two need to be used together)
  • insideBoundingBox
  • insidePolygon

They have the same meaning as when used for a query (such as with search/4 or browse/3). At least one type of filter is required.

Additional options

  • :headers - list of additional HTTP headers to include in the request.
Link to this function

delete_index(client, index, opts \\ [])

View Source
@spec delete_index(client(), index(), [request_option()]) :: result(map())

Deletes an index.

Options

  • :headers - list of additional HTTP headers to include in the request.
Link to this function

delete_object(client, index, object_id, opts \\ [])

View Source
@spec delete_object(client(), index(), String.t(), [request_option()]) ::
  result(map())

Deletes a single object by its object ID.

Options

  • :headers - list of additional HTTP headers to include in the request.
Link to this function

delete_objects(client, index, object_ids, opts \\ [])

View Source
@spec delete_objects(client(), index(), [String.t()], [request_option()]) ::
  result(map())

Deletes multiple objects by object ID.

Options

  • :headers - list of additional HTTP headers to include in the request.
Link to this function

get_logs(client, opts \\ [])

View Source
@spec get_logs(
  client(),
  [
    {:indexName, index()}
    | {:length, integer()}
    | {:offset, integer()}
    | {:type, :all | :query | :build | :error}
    | request_option()
  ]
) :: result(map())

Gets the logs of the latest search and indexing operations.

Options

  • :indexName - index for which log entries should be retrieved. When omitted, log entries are retrieved across all indices.
  • :length - maximum number of entries to retrieve. Maximum allowed value: 1000.
  • :offset - first entry to retrieve (zero-based). Log entries are sorted by decreasing date, therefore 0 designates the most recent log entry.
  • :type - type of log to retrieve: :all, :query, :build or :error. Defaults to :all.
  • :headers - list of additional HTTP headers to include in the request.
Link to this function

get_object(client, index, object_id, opts \\ [])

View Source
@spec get_object(client(), index(), String.t(), [request_option()]) :: result(map())

Retrieves a single object from an index by ID.

Example

Algolia.get_object(client, "my_index", "123")

Options

  • :headers - list of additional HTTP headers to include in the request.
Link to this function

get_settings(client, index, opts \\ [])

View Source
@spec get_settings(client(), index(), [request_option()]) :: result(map())

Gets the settings of a index.

Example

iex> Algolia.get_settings(client, "my_index")
{:ok,
  %{"minWordSizefor1Typo" => 4,
    "minWordSizefor2Typos" => 8,
    "hitsPerPage" => 20,
    "attributesToIndex" => nil,
    "attributesToRetrieve" => nil,
    "attributesToSnippet" => nil,
    "attributesToHighlight" => nil,
    "ranking" => [
        "typo",
        "geo",
        "words",
        "proximity",
        "attribute",
        "exact",
        "custom"
    ],
    "customRanking" => nil,
    "separatorsToIndex" => "",
    "queryType" => "prefixAll"}}

Options

  • :headers - list of additional HTTP headers to include in the request.
Link to this function

list_indexes(client, opts \\ [])

View Source
@spec list_indexes(client(), [request_option()]) :: result(map())

Lists all indexes.

Options

  • :headers - list of additional HTTP headers to include in the request.
Link to this function

move_index(client, src_index, dst_index, opts \\ [])

View Source
@spec move_index(client(), index(), index(), [request_option()]) :: result(map())

Moves an index to new one.

Options

  • :headers - list of additional HTTP headers to include in the request.
Link to this function

multi(client, queries, opts \\ [])

View Source
@spec multi(client(), [map()], [{:strategy, multi_strategy()} | request_option()]) ::
  result(map())

Performs multiple search queries in a single request.

Each entry in queries should be a map with :index_name indicating which index to search, and the remaining keys corresponding to Algolia search parameters.

Examples

Algolia.multi(client, [
  %{index_name: "my_index1", query: "search query"},
  %{index_name: "my_index2", query: "another query", hitsPerPage: 3},
  %{index_name: "my_index3", query: "3rd query", tagFilters: "promotion"}
])

Options

  • :strategy - strategy to use to decide whether to continue with additional queries. Can be either :none or :stop_if_enough_matches. Defaults to :none. See Algolia's documentation for more information about the difference between these two strategies.
  • :headers - list of additional HTTP headers to include in the request.
@spec new(
  api_key: String.t(),
  application_id: String.t(),
  middleware: ([Tesla.Client.middleware()] -> [Tesla.Client.middleware()]),
  adapter: Tesla.Client.adapter()
) :: client()

Creates a new Algolia client.

A client must be passed to any function that makes a request to Algolia.

Examples

client = Algolia.new(
  api_key: "my_api_key",
  application_id: "my_application_id"
)
Algolia.search(client, "my_index", "some query")

# adding logging middleware
client = Algolia.new(
  middleware: fn middleware ->
    middleware ++ [
      {Tesla.Middleware.Logger, filter_headers: ["X-Algolia-API-Key"]}
    ]
  end
)

# set a custom adapter
client = Algolia.new(adapter: Tesla.Adapter.Mint)

Options

  • :api_key - the API key to use for Algolia. If unset, reads from the ALGOLIA_API_KEY environment variable or the :api_key key in the :algolia application config.
  • :application_id - the application ID to use for Algolia. If unset, reads from the ALGOLIA_APPLICATION_ID environment variable or the :application_id key in the :algolia application config.
  • :middleware - a function that can be used to alter the default list of Tesla middleware that will be used. The function takes the default list of middleware as an argument, so you can inject middleware as needed. Note that removing any of the default middleware might break the client.
  • :adapter - the Tesla HTTP adapter to use. Defaults to Tesla's default adapter, which is :httpc by default but can be overridden in the :tesla application config.
Link to this function

partial_update_object(client, index, object, object_id, opts \\ [upsert?: true])

View Source
@spec partial_update_object(client(), index(), map(), String.t(), [
  {:upsert?, boolean()} | request_option()
]) :: result(map())

Partially updates a single object.

Examples

Algolia.partial_update_object(client, "my_index", %{
  objectID: "1",
  name: "apple"
})

# don't create the object if it doesn't already exist
Algolia.partial_update_object(client, "my_index", %{
  id: "1",
  name: "apple"
}, upsert?: false)

Options

  • :upsert? - whether to create the record if it doesn't already exist. Defaults to true.
  • :headers - list of additional HTTP headers to include in the request.
Link to this function

partial_update_objects(client, index, objects, opts \\ [upsert?: true, id_attribute: :objectID])

View Source
@spec partial_update_objects(client(), index(), [map()], [
  {:upsert?, boolean()}
  | {:id_attribute, atom() | String.t()}
  | request_option()
]) :: result(map())

Partially updates multiple objects.

Examples

Algolia.partial_update_objects(client, "my_index", [
  %{objectID: "1", name: "apple"},
  %{objectID: "2", name: "orange"}
])

# don't create objects if they don't already exist,
# and use `:id` for the object ID
Algolia.partial_update_objects(client, "my_index", [
  %{id: "1", name: "apple"},
  %{id: "2", name: "orange"}
], upsert?: false, id_attribute: :id)

Options

  • :upsert? - whether to create any records that don't already exist. Defaults to true.
  • :id_attribute - key to use as the :objectID of the objects.
  • :headers - list of additional HTTP headers to include in the request.
Link to this function

push_events(client, events, opts \\ [])

View Source
@spec push_events(client(), [map()], [request_option()]) :: result(map())

Pushes events to the Insights API.

See Algolia's documentation for the send events endpoint for more information on the fields that events should include.

Examples

Algolia.push_events(client, [
  %{
    "eventType" => "click",
    "eventName" => "Product Clicked",
    "index" => "products",
    "userToken" => "user-123456",
    "objectIDs" => ["9780545139700", "9780439784542"],
    "queryID" => "43b15df305339e827f0ac0bdc5ebcaa7",
    "positions" => [7, 6]
  }
])

Options

  • :headers - list of additional HTTP headers to include in the request.
Link to this function

save_object(client, index, object, opts \\ [])

View Source
@spec save_object(client(), index(), map(), [
  {:id_attribute, atom() | String.t()} | request_option()
]) ::
  result(map())

Saves a single object, replacing it if it already exists.

Unlike add_object/4, the object must already have an object ID. The :id_attribute option can still be used to set an object ID based on another attribute.

Examples

# add or replace an object based on the object ID
Algolia.save_object(client, "my_index", %{
  objectID: "123",
  kind: "fruit",
  color: "red",
  name: "apple"
})

# pass the object ID as its own argument
Algolia.save_object(client, "my_index", %{
  kind: "fruit",
  color: "red",
  name: "apple"
}, "123")

# set the object ID based on another attribute
Algolia.save_object(client, "my_index", %{
  kind: "fruit",
  color: "red",
  name: "apple"
}, id_attribute: :name)
# resulting objectID is "apple"

Options

  • :id_attribute - key to use as the :objectID of the object. If set, the saved object will have both :objectID and this key set to the same value.
  • :headers - list of additional HTTP headers to include in the request.
Link to this function

save_objects(client, index, objects, opts \\ [id_attribute: :objectID])

View Source
@spec save_objects(client(), index(), [map()], [
  {:id_attribute, atom() | String.t()} | request_option()
]) ::
  result(map())

Saves multiple objects, replacing any that already exist.

Unlike add_objects/4, the objects must already have object IDs. The :id_attribute option can still be used to set the object IDs based on another attribute.

Examples

Algolia.save_objects(client, "my_index", [
  %{objectID: "1", name: "apple"},
  %{objectID: "2", name: "orange"}
])

# use `:id` for the object ID
Algolia.save_objects(client, "my_index", [
  %{id: "1", name: "apple"},
  %{id: "2", name: "orange"}
], id_attribute: :id)

Options

  • :id_attribute - key to use as the :objectID of the objects.
  • :headers - list of additional HTTP headers to include in the request.
Link to this function

search(client, index, query, opts \\ [])

View Source
@spec search(client(), index(), String.t(), [{atom(), any()} | request_option()]) ::
  result(map())

Searches a single index.

Examples

# basic search
Algolia.search(client, "my_index", "some query")

# with search parameters
Algolia.search(client, "my_index", "some query",
  attributesToRetrieve: "firstname",
  hitsPerPage: 20
)

Options

Any of Algolia's supported search parameters can be passed as options.

Additional options

  • :headers - list of additional HTTP headers to include in the request.
Link to this function

search_for_facet_values(client, index, facet, text, opts \\ [])

View Source
@spec search_for_facet_values(client(), index(), String.t(), String.t(), [
  request_option() | {atom(), any()}
]) :: result(map())

Searches for facet values.

Enables you to search through the values of a facet attribute, selecting only a subset of those values that meet a given criteria.

For a facet attribute to be searchable, it must have been declared in the attributesForFaceting index setting with the searchable modifier.

Facet-searching only affects facet values. It does not impact the underlying index search.

Examples

iex> Algolia.search_for_facet_values("species", "phylum", "dophyta")
{:ok,
  %{"exhaustiveFacetsCount" => false,
    "facetHits" => [
      %{
        "count" => 9000,
        "highlighted" => "Pteri<em>dophyta</em>",
        "value" => "Pteridophyta"
      },
      %{
        "count" => 7000,
        "highlighted" => "Rho<em>dophyta</em>",
        "value" => "Rhodophyta"
      },
      %{
        "count" => 150,
        "highlighted" => "Cyca<em>dophyta</em>",
        "value" => "Cycadophyta"
      }
    ],
    "processingTimeMS" => 42}}

Options

Many of Algolia's supported search parameters can be passed as options to filter the objects that are matched.

Additional options

  • :sortFacetValuesBy - control how facets are sorted. Either "count" (by count, descending) or "alpha" (by value alphabetically, ascending). Defaults to "count".
  • :maxFacetHits - maximum number of hits to return. Defaults to 10. Cannot exceed 100.
  • :headers - list of additional HTTP headers to include in the request.
Link to this function

set_settings(client, index, settings, opts \\ [])

View Source
@spec set_settings(client(), index(), map(), [request_option()]) :: result(map())

Sets the settings of a index.

Example

iex> Algolia.set_settings(client, "my_index", %{hitsPerPage: 20})
{:ok,
  %{"updatedAt" => "2013-08-21T13:20:18.960Z",
    "taskID" => 10210332.
    "indexName" => "my_index"}}

Options

  • :headers - list of additional HTTP headers to include in the request.
Link to this function

wait(response, client, opts \\ [])

View Source
@spec wait(result(map()), client(), [{:retry_delay, integer()} | request_option()]) ::
  :ok | {:error, any()}

Waits on the task created by a previous request.

This is a convenient variation of wait_task/4 that accepts a response from another API function. You can pipe another API function into wait/3 to only return the response once the task is completed.

Examples

client
|> Algolia.save_object("my_index", %{id: "123"}, id_attribute: :id)
|> Algolia.wait(client)

client
|> Algolia.save_objects("my_index", [
  %{id: "123"},
  %{id: "234"}
], id_attribute: :id)
|> Algolia.wait(client, retry_delay: 2_000)

Options

  • :retry_delay - number of milliseconds to wait before each request to Algolia to check for task completion. Defaults to 1_000, or one second.
  • :headers - list of additional HTTP headers to include in the request.
Link to this function

wait_task(client, index, task_id, opts \\ [])

View Source
@spec wait_task(client(), index(), String.t(), [
  {:retry_delay, integer()} | request_option()
]) ::
  :ok | {:error, any()}

Waits for a task for an index to complete.

Returns :ok when the task is completed.

Example

{:ok, %{"taskID" => task_id, "indexName" => index}} =
  Algolia.save_object(client, %{id: "123"}, id_attribute: :id)

Algolia.wait_task(client, index, task_id)

See wait/3 for a convenient shortcut using piping.

Options

  • :retry_delay - number of milliseconds to wait before each request to Algolia to check for task completion. Defaults to 1_000, or one second.
  • :headers - list of additional HTTP headers to include in the request.