Elastic.Document.API (Elastic v3.7.0) View Source
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, index: nil, text: []
end
You may also specify the index at query/insertion as the last (optional) argument to
all Document functions. You will receive warnings if @es_index is undefined in
the using module, but you may either ignore these or specify @es_index "N/A"
or other
unused value if a default index does not make sense for your collection, such as permission based
partitioning, or per-company partitioning in a SaaS application.
Index
Then you can index a new Answer
by doing:
Answer.index(1, %{text: "This is an answer"})
or
Answer.index(1, %{text: "This is an answer"}, "explicit_named_index")
if not using default index behavior. All examples below may also be modified the same way if using an explicit index.
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, index: "answer", 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, index: "answer", 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)