From 2c1f44241fc0806072bef744c5c3d6ad8b6d6f5e Mon Sep 17 00:00:00 2001 From: Jai2305 Date: Mon, 15 Jul 2024 22:31:22 +0530 Subject: [PATCH] Added json.md - Serialization part Signed-off-by: Jai2305 --- CHANGELOG.md | 1 + guides/json.md | 59 +++++++++++++++++++ .../samples/json/SerializationBasics.java | 48 +++++++++++++++ 3 files changed, 108 insertions(+) create mode 100644 guides/json.md create mode 100644 samples/src/main/java/org/opensearch/client/samples/json/SerializationBasics.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 8001738fdf..fc4e0ace1a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ This section is for maintaining a changelog for all breaking changes for the cli - Document HTTP/2 support ([#330](https://github.com/opensearch-project/opensearch-java/pull/330)) - Add support for phase_took & search_pipeline request params ([#1036](https://github.com/opensearch-project/opensearch-java/pull/1036)) - Add an interface PlainJsonSerializable inherit from JsonpSerializable with a default method streamlining serialization ([#1064](https://github.com/opensearch-project/opensearch-java/pull/1064)) +- Add a new file json.md in guides and SerializationBasics in samples/json ([#1083](https://github.com/opensearch-project/opensearch-java/pull/1083)) ### Dependencies diff --git a/guides/json.md b/guides/json.md new file mode 100644 index 0000000000..504e8e2d88 --- /dev/null +++ b/guides/json.md @@ -0,0 +1,59 @@ +- [Working with Json](#working-with-json) + - [Serialization](#serialization) + - [Using toJsonString method](#using-tojsonstring-method) + - [Manual serialization](#manually-serialize-by-providing-mapper-and-generator) + + +# Working with Json + +OpenSearch Java client seamlessly integrate with JSON providing serialization and deserialization capability. + +## Serialization + +For demonstration let's consider an instance of `SearchRequest`. + +```java +public static void main(final String[] args) { + SearchRequest searchRequest = SearchRequest.of( + request -> request.index("index1", "index2") + .aggregations(Collections.emptyMap()) + .terminateAfter(5L) + .query(q -> q.match(t -> t.field("name").query(FieldValue.of("OpenSearch")))) + ); +} + +``` +### Using toJsonString method +For classes implementing `PlainJsonSerializable`, which extends `JsonpSerializable`, a default `toJsonString` method is provided. +This implementation uses `jakarta.json.spi.JsonProvider` SPI to discover the available JSON provider instance +from the classpath and to create a new mapper. The `JsonpUtils` utility class streamlines this serialization process. +The following code example demonstrates how to use the `toJsonString` method to serialize objects: + +```java +String requestString = searchRequest.toJsonString(); +``` + + +### Manually serialize by providing mapper and generator +For classes implementing the `JsonpSerializable` interface, a serialize method is provided, which takes a mapper and a generator +as arguments and returns the JSON string representation of the instance. + +The following sample code demonstrates how to serialize an instance of a Java class: + +```java +private String toJson(JsonpSerializable object) { + try (StringWriter writer = new StringWriter()) { + JsonbJsonpMapper mapper = new JsonbJsonpMapper(); + try (JsonGenerator generator = mapper.jsonProvider().createGenerator(writer)) { + serialize(generator, mapper); + } + return writer.toString(); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } +} + +``` + + + diff --git a/samples/src/main/java/org/opensearch/client/samples/json/SerializationBasics.java b/samples/src/main/java/org/opensearch/client/samples/json/SerializationBasics.java new file mode 100644 index 0000000000..c4cbd36f00 --- /dev/null +++ b/samples/src/main/java/org/opensearch/client/samples/json/SerializationBasics.java @@ -0,0 +1,48 @@ +package org.opensearch.client.samples.json; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.opensearch.client.opensearch.OpenSearchClient; +import org.opensearch.client.opensearch.indices.PutIndexTemplateRequest; +import org.opensearch.client.opensearch.indices.PutIndexTemplateResponse; +import org.opensearch.client.samples.SampleClient; +import org.opensearch.client.samples.Search; +import java.util.List; + + +public class SerializationBasics { + + private static final Logger LOGGER = LogManager.getLogger(Search.class); + + private static OpenSearchClient client; + + public static void main(String[] args) { + try { + client = SampleClient.create(); + + var version = client.info().version(); + LOGGER.info("Server: {}@{}.", version.distribution(), version.number()); + + final var indexTemplateName = "my-index"; + final var indexSettingsComponentTemplate = "index-settings"; + final var indexMappingsComponentTemplate = "index-mappings"; + + // Create Index Template Request for index 'my-index'. + PutIndexTemplateRequest putIndexTemplateRequest = PutIndexTemplateRequest.of( + it -> it.name(indexTemplateName) + .indexPatterns("my-index-*") + .composedOf(List.of(indexSettingsComponentTemplate, indexMappingsComponentTemplate)) + ); + + LOGGER.info("Creating index template {}.", indexTemplateName); + + // Use toJsonString method to log Request and Response string. + LOGGER.debug("Index Template Request: {}.", putIndexTemplateRequest.toJsonString()); + PutIndexTemplateResponse response = client.indices().putIndexTemplate(putIndexTemplateRequest); + LOGGER.info("Index Template Response: {}.", response.toJsonString()); + + } catch (Exception e) { + LOGGER.error("Exception occurred.", e); + } + } +} \ No newline at end of file