Reading documents by id
editReading documents by id
editElasticsearch 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 object
editThe 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 .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"); }
Reading raw JSON
editWhen 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 .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 source code for the examples above can be found in the Java API Client tests.