Reading documents by idedit

Elasticsearch is all about search, but you may also want to access documents directly, knowing their identifier. The "get" request is meant for this.

See the Elasticsearch API documentation for a full explanation of get requests.

Reading a domain objectedit

The example below reads the document with identifier bk-1 from the products index.

The get request has two parameters:

  • the first parameter is the actual request, built below with the fluent DSL
  • the second parameter is the class we want the document’s JSON to be mapped to.
GetResponse<Product> response = esClient.get(g -> g

if (response.found()) {
    Product product = response.source();"Product name " + product.getName());
} else { ("Product not found");

The get request, with the index name and identifier.

The target class, here Product.

Reading raw JSONedit

When your index contains semi-structured data or if you don’t have a domain object definition, you can also read the document as raw JSON data.

Raw JSON data is just another class that you can use as the result type for the get request. In the example below we use Jackson’s ObjectNode. We could also have used any JSON representation that can be deserialized by the JSON mapper associated to the ElasticsearchClient.

GetResponse<ObjectNode> response = esClient.get(g -> g

if (response.found()) {
    ObjectNode json = response.source();
    String name = json.get("name").asText();"Product name " + name);
} else {"Product not found");

The target class is a raw JSON object.

The source code for the examples above can be found in the Java API Client tests.