Updating index mapping using java client

I’m trying to update index mapping using java client.

The mapping is stored in mapping.json file.
I’m trying to create PutMappingRequest.
Is there an easy way to load json file into request, it doesn’t seem easy to use Builder for it so I decided to use org.opensearch.client.opensearch.indices.PutMappingRequest#_DESERIALIZER

    public static void main(String[] args) {
        String mapping = """
                {
                  "dynamic": false,
                  "properties": {
                    "Title": {
                      "type": "keyword",
                      "fields": {
                        "analyzed": {
                          "type": "text"
                        }
                      }
                    }
                  }
                }
                """;

        RestClient restClient = RestClient.builder(HttpHost.create("http://localhost:9200")).build();
        OpenSearchClient openSearchClient = new OpenSearchClient(
                new RestClientTransport(
                        restClient,
                        new JacksonJsonpMapper()
                )
        );

        JsonpMapper mapper = openSearchClient._transport().jsonpMapper();
        jakarta.json.stream.JsonParser parser = mapper.jsonProvider().createParser(new StringReader(mapping));



        PutMappingRequest putMappingRequest = PutMappingRequest._DESERIALIZER.deserialize(
                        parser, mapper
                );
        System.out.println(putMappingRequest);
    }

It throws this exception:

Exception in thread "main" org.opensearch.client.util.MissingRequiredPropertyException: Missing required property 'PutMappingRequest.index'
	at org.opensearch.client.util.ApiTypeHelper.requireNonNull(ApiTypeHelper.java:89)
	at org.opensearch.client.util.ApiTypeHelper.unmodifiableRequired(ApiTypeHelper.java:154)
	at org.opensearch.client.opensearch.indices.PutMappingRequest.<init>(PutMappingRequest.java:137)
	at org.opensearch.client.opensearch.indices.PutMappingRequest$Builder.build(PutMappingRequest.java:868)
	at org.opensearch.client.opensearch.indices.PutMappingRequest$Builder.build(PutMappingRequest.java:440)
	at org.opensearch.client.json.ObjectBuilderDeserializer.deserialize(ObjectBuilderDeserializer.java:92)
	at org.opensearch.client.json.DelegatingDeserializer$SameType.deserialize(DelegatingDeserializer.java:55)

It looks index field is mandatory but there is no way to set it.
How can i fix it? is there an easier way?

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.