javaelasticsearchquery-builderreindexelasticsearch-high-level-restclient

Reindex selected _source fields using Rest high level client in java


I want to re_index only selected fields from my document in elasticsearch using Rest High level client.

I know the elasticsearch query to achieve that but I don't know it's equivalent query using rest client.

Following is the elasticsearch query which I am trying to implement using rest client -

{
  "body" : {
     "source" : {
        "index" : "my source index name",
        "_source" : "id, name, rollNo"
     },
     "dest" : {
        "index" : "my destination index name"
     }
  }
}

To write its equivalent query using rest client in java, I have used the following code -

ReindexRequest reindexRequest = new ReindexRequest();
reindexRequest.setSourceIndices("source index name").setDestIndex("destination index name");
reindexRequest.setDocTypes("id", "name", "rollNo", "_doc");
client.reindex(reindexRequest,RequestOptions.DEFAULT);

But the above code is not working as expected. It's re_indexing all the fields of my document. I want only selective 3 fields to be re_indexed from each doc.


Solution

  • You need to use below code as setDocTypes is not used for source filtering.

    As there is no direct method available for setting source filter so you need to change underlying search request suing below code.

    ReindexRequest reindexRequest = new ReindexRequest();
    reindexRequest.setSourceIndices("source index name").setDestIndex("destination index name");
    reindexRequest.setDocTypes("_doc");
    
    String[] include=new String[] {"id", "name", "rollNo"};
    String[] exclude=new String[] {"test"};
    reindexRequest.getSearchRequest().source().fetchSource(include, exclude);
    
    client.reindex(reindexRequest,RequestOptions.DEFAULT);