Elastic v2.2.1 Elastic.Document.API

The Document API provides some helpers for interacting with documents.

The Document API extracts away a lot of the repetition of querying / indexing of a particular index. Here’s an example:

defmodule Answer do
  @es_type "answer"
  @es_index "answer"
  use Elastic.Document.API

  defstruct id: nil, text: []
end

Index

Then you can index a new Answer by doing:

Answer.index(1, %{text: "This is an answer"})

Searching

The whole point of Elastic Search is to search for things, and there’s a function for that:

Answer.search(%{
  query: %{
    match: %{text: "answer"}
  },
})

The query syntax is exactly like the JSON you’ve come to know and love from using Elastic Search, except it’s Elixir maps.

This will return a list of Answer structs.

[
  %Answer{id: 1, text: "This is an answer"},
  ...
]

If you want the raw search result, use `raw_search` instead:

Answer.raw_search(%{ query: %{

match: %{text: "answer"}

}, })


This will return the raw result, without the wrapping of the structs:

{:ok, 200, [ %{“_id” => “1”, “_index” => “answer”,

 "_source" => %{"text" => "This is an answer"}, "_type" => "answer", "_version" => 1,
 "found" => true}

} … ] }


## Counting

Counting works the same as searching, but instead of returning all the hits,
it'll return a number.

Answer.count(%{ query: %{

match: %{text: "answer"}

}, })


## Get

And you can get that answer with:

Answer.get(1)


This will return an Answer struct:

%Answer{id: 1, text: “This is an answer”}


## Raw Get

If you want the raw result, use `raw_get` instead:

Answer.raw_get(1)


This returns the raw data from Elastic Search, without the wrapping of the struct:

{:ok, 200, %{“_id” => “1”, “_index” => “answer”, “_source” => %{“text” => “This is an answer”}, “_type” => “answer”, “_version” => 1, “found” => true} } }


## Updating

You can update the answer by using `update` (or `index`, since `update` is just an "alias")

Answer.update(1, %{text: “This is an answer”})


## Deleting

Deleting a document from the index is as easy as:

Answer.delete(1)