From 4940c189c978a587b939597638146b64fbd5a7a7 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Tue, 16 Jul 2024 15:44:05 +0000 Subject: [PATCH] Added json.md - Serialization part (#1083) Signed-off-by: Jai2305 (cherry picked from commit c40e4862901332122476adf8a329a7d3f7cbab18) Signed-off-by: github-actions[bot] --- CHANGELOG.md | 2 +- USER_GUIDE.md | 1 + guides/json.md | 53 ++++++++++++++++++ .../samples/json/SerializationBasics.java | 55 +++++++++++++++++++ 4 files changed, 110 insertions(+), 1 deletion(-) 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 12e37f102b..b0782ad0c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) ## [Unreleased 2.x] ### Added - 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 an interface PlainJsonSerializable with a default method for serialization to Json ([#1064](https://github.com/opensearch-project/opensearch-java/pull/1064)) ### Dependencies - Bumps `io.github.classgraph:classgraph` from 4.8.173 to 4.8.174 diff --git a/USER_GUIDE.md b/USER_GUIDE.md index 4092aed151..ef014d3f20 100644 --- a/USER_GUIDE.md +++ b/USER_GUIDE.md @@ -190,6 +190,7 @@ You can find a working sample of the above code in [IndexingBasics.java](./sampl - [Point-in-Time APIs](./guides/point_in_time.md) - [Search](./guides/search.md) - [Generic Client](./guides/generic.md) +- [Json](./guides/json.md) ## Plugins diff --git a/guides/json.md b/guides/json.md new file mode 100644 index 0000000000..3f4acd42c8 --- /dev/null +++ b/guides/json.md @@ -0,0 +1,53 @@ +- [Working With JSON](#working-with-json) + - [Serialization](#serialization) + - [Using toJsonString](#using-tojsonstring) + - [Manual Serialization](#manual-serialization) + + +# Working With JSON + +OpenSearch Java client seamlessly integrates with JSON, providing serialization and deserialization capability. + +## Serialization + +For demonstration let's consider an instance of `SearchRequest`. + +```java + +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 +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(); +``` + + +### Manual Serialization +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); + } +} +``` \ No newline at end of file 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..effae43f80 --- /dev/null +++ b/samples/src/main/java/org/opensearch/client/samples/json/SerializationBasics.java @@ -0,0 +1,55 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + */ + +package org.opensearch.client.samples.json; + +import java.util.List; +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; + +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); + } + } +}