Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Quick implementation of a Solr client in Elixir
defmodule MyApp.Search.SolrClient do
require Logger
def url, do: Application.get_env(:my_app, :solr)[:url]
def select_url(url), do: "#{url}/select"
def update_url(url), do: "#{url}/update"
def update_json_url(url), do: "#{url}/update/json/docs"
def select(params) when is_list(params) do
params = Keyword.merge([wt: "json"], params)
url()
|> select_url()
|> get(params)
end
def add(doc) do
json = Jason.encode!(doc)
url()
|> update_json_url()
|> post(json)
end
defp get(url, params) do
url
|> HTTPoison.get(json_headers(), params: params)
|> case do
{:ok, %{status_code: 200, body: body}} ->
parse_body(body)
{:ok, %{body: body}} ->
parse_non_success(body)
{:error, %{reason: reason}} ->
{:error, Atom.to_string(reason)}
end
end
defp post(url, data) do
url
|> HTTPoison.post(data, json_headers())
|> case do
{:ok, %{status_code: 200, body: body}} ->
parse_body(body)
{:ok, %{body: body}} ->
Logger.debug("ERROR BODY: #{inspect(body)}")
parse_non_success(body)
{:error, %{reason: reason}} ->
Logger.debug("ERROR REASON: #{inspect(reason)}")
{:error, Atom.to_string(reason)}
end
end
defp parse_non_success(body) do
body
|> parse_body()
|> case do
{:ok, %{"error" => %{"msg" => reason}}} ->
{:error, reason}
{:error, err} ->
{:error, err}
end
end
defp parse_body(body) do
Jason.decode(body)
end
defp json_headers, do: [{"Content-Type", "application/json"}]
@doc """
Commit changes into Solr
"""
def commit do
update_request(xml_headers(), commit_xml_body())
end
defp update_request(headers, body) do
url()
|> update_url
|> HTTPoison.post(body, headers)
end
defp commit_xml_body, do: "<commit/>"
defp xml_headers, do: [{"Content-type", "text/xml; charset=utf-8"}]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment