Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us
Notesclub

Search from Algolia

livebooks/algolia/algolia_search.livemd

Search from Algolia

Mix.install([
  {:algoliax, "~> 0.7"},
  {:req, "~> 0.3"},
  {:kino, "~> 0.12"}
])

Set credentials

application_id = Kino.Input.text("Application ID")
application_id
|> Kino.Input.read()
|> then(&System.put_env("ALGOLIA_APPLICATION_ID", &1))
api_key = Kino.Input.password("API Key")
api_key
|> Kino.Input.read()
|> then(&System.put_env("ALGOLIA_API_KEY", &1))

Get Index settings

configuration =
  "https://raw.githubusercontent.com/algolia/datasets/master/ecommerce-federated/products_configuration.json"
  |> Req.get!()
  |> then(&Jason.decode!(&1.body))
settings =
  configuration["settings"]
  |> Enum.into([], fn {key, value} ->
    {
      key |> Inflex.underscore() |> String.to_atom(),
      value
    }
  end)

Define module

defmodule Products do
  use Algoliax.Indexer,
    index_name: :products,
    algolia: settings
end

Search

{:ok, %Algoliax.Response{response: response}} = Products.search("Shirt")

response
{
  response["hitsPerPage"],
  response["nbHits"],
  response["nbPages"],
  response["page"]
}
{:ok, %Algoliax.Response{response: response}} = Products.search("Shirt", %{page: 1})

response["page"]
{:ok, %Algoliax.Response{response: response}} = Products.search("Shirt", %{hits_per_page: 100})

response["nbPages"]
response["hits"]
|> List.first()
|> Kino.Tree.new()
response["hits"]
|> List.first()
|> Map.get("_highlightResult")
response["hits"]
|> Enum.filter(&(&1["_snippetResult"]["description"]["value"] != ""))
|> List.first()
|> Map.get("_snippetResult")