Using Elasticsearch Java Sdk
Starting with an empty Gradle project, the dependencies for the ElasticSearch Java SDK were added to the build.gradle file:
//build.gradle
dependencies {
implementation 'co.elastic.clients:elasticsearch-java:8.1.3'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.12.3'
implementation 'jakarta.json:jakarta.json-api:2.0.1'
}
Then, a record type for storing data is defined:
record Book(String title, String author, int publishedYear) { }
Get a reference to the ElasticSearch client object, which will be used for making any requests:
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
Create the index if it does not already exist (use dynamic mappings for now).
ExistsRequest existRequest = new ExistsRequest.Builder().index("book").build();
BooleanResponse existsResponse = client.indices().exists(existRequest);
if (existsResponse.value() == false) {
CreateIndexRequest request = new CreateIndexRequest.Builder().index("book").build();
CreateIndexResponse createIndexResponse = client.indices().create(request);
}
Insert a Book object into ElasticSearch.
Book bk1 = new Book("Who Moved My Cheese", "Spencer Johnson", 1998);
IndexResponse createResponse = client.index(i -> i
.index("book")
.id(bk1.title())
.document(bk1)
);
System.out.println("New ver: " + createResponse.version());
Fetch by ID
GetResponse<Book> retrieveResponse = client.get(g -> g
.index("book")
.id(bk1.title()),
Book.class
);
if (retrieveResponse.found()) {
Book bk2 = retrieveResponse.source();
System.out.println("Author: " + bk2.author());
} else {
System.out.println("Book not found");
}
Simple fieldName=value Search query
SearchResponse<Book> response = client.search(s -> s
.index("book")
.query(q -> q
.match(t -> t
.field("author")
.query(bk1.author())
)
),
Book.class
);
TotalHits total = response.hits().total();
boolean isExactResult = total.relation() == TotalHitsRelation.Eq;
if (isExactResult) {
System.out.println("There are " + total.value() + " results");
} else {
System.out.println("There are more than " + total.value() + " results");
}
List<Hit<Book>> hits = response.hits().hits();
for (Hit<Book> hit: hits) {
Book bk3 = hit.source();
System.out.println("Found book " + bk3.title() + ", score " + hit.score());
}
Drop the index
DeleteIndexRequest delReq = new DeleteIndexRequest.Builder().index(List.of("book")).build();
DeleteIndexResponse delResp = client.indices().delete(delReq);
Close the REST client object
restClient.close();