How do I transfer mappings from one index to another with Java Api Client

Hello, I'm currently building a Spring Java application and I use the [Elastic Java Client] (Elasticsearch Java API Client [8.5] | Elastic) (Version: 8.3.3) to communicate between my application and my elastic cluster.

I've come to notice that the client is not that well documented and I regularly encounter development roadblocks because I can't figure out how to "translate" my request that I would use in kibana to a request for the java client.

My current problem revolves around copying the mappings of one index to another one.
Since I noticed some problems using the reindex api with my data I came to the conclusion to transfer the mappings beforehand and reindex after that.

I tested it in kibana and it seemed to work. The request I want to create using the Java Client is the following:

PUT /my-index-000001/_mapping
{
  "properties": {
    "email": {
      "type": "keyword"
    }
  }
}

I'm currently getting the mappings of my source index via the Get Mapping api but the problem is I dont know how exactly I use the list of mappings to put them into the Put Mapping Request.
My mappings are in the form of a json string but how do I take a single field and convert it to a Property object that is required for request?

So how do I copy the mappings of one index to another using the Java Client without copying the data (e.g: documents)?

If anyone should ever encounter the same problem here is the solution I found:

In the elastic documentation I came across this article: Creating API objects from JSON data
The Java API Client uses a simple HTTP client under the hood so you can just create request from a json input here is an example of how I used this method to transfer the mappings of one index to another:

In the following example the variable source are my index mappings as a string in valid json format and I'm using the Gson library to get the properties part of my mappings

Gson gson = new Gson();
JsonElement jsonObj = gson.fromJson(mappings, JsonElement.class);
JsonObject properties = jsonObj.getAsJsonObject().get(source).getAsJsonObject().get("mappings").getAsJsonObject();
InputStream inputStream = new ByteArrayInputStream(properties.toString().getBytes());
PutMappingResponse response = client.indices().putMapping(p -> p.index(dest).withJson(inputStream))

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