Ways to build Json doc in ES8 Java API client

How to build Json document In Elasticsearch 8 API client , as In older Client APIs its possible to build using XContentBuilder like

XContentBuilder builder = jsonBuilder()
        .field("firstName", "jhon")
        .field("lastname", "doe")
        .field("message", "trying out Elasticsearch")

But now in ES8 Java API Client i do not see any way to build Json doc, for example if i want to insert a "Student" into "School" index , then possible ways are

1- using direct bean as document

esClient.index(i -> i

2- using pre builded json as string (no way to build explicitly)

Reader input = new StringReader(
    "{'@timestamp': '2022-04-08T13:55:32Z', 'firstName': 'jhone', 'lastName': 'doe'}"
    .replace('\'', '"'));

IndexRequest<JsonData> request = IndexRequest.of(i -> i

3- using JsonData class

JsonpMapper jsonpMapper = esClient.jsonpMapper();
JsonData jsonData = JsonData.of(student , jsonpMapper);

esClient.index(i -> i

so is there any way to build Json using Java API Client and input as doc to index

Indeed, there is no way to programmatically build JSON in the Java API client, and this is a deliberate omission.

JsonData can hold any object that can be serialized to JSON: this can be a map, a domain object that will be serialized to JSON, etc.

The withJson method is meant to load JSON from text-based sources, like copy/pasting from the Kibana dev console. For example:

        var object = Map.ofEntries(
            Map.entry("firstName", "John"),
            Map.entry("lastName", "Doe"),
            Map.entry("message", "trying out Elasticsearch")

        esClient.index(i -> i

Hope this helps.

1 Like