Reading documents by id
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 theElasticsearch API documentation for a full explanation of get requests.
The example below reads the document with identifierbk-1 from theproducts index.
Theget 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 .index("products") .id("bk-1"), Product.class);if (response.found()) { Product product = response.source(); logger.info("Product name " + product.getName());} else { logger.info ("Product not found");}- The get request, with the index name and identifier.
- The target class, here
Product.
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’sObjectNode. We could also have used any JSON representation that can be deserialized by the JSON mapper associated to theElasticsearchClient.
GetResponse<ObjectNode> response = esClient.get(g -> g .index("products") .id("bk-1"), ObjectNode.class);if (response.found()) { ObjectNode json = response.source(); String name = json.get("name").asText(); logger.info("Product name " + name);} else { logger.info("Product not found");}- The target class is a raw JSON object.
The source code for the examples above can be found in theJava API Client tests.