Rose
Rose

Reputation: 1498

How to remove field from document which matches a pattern in elasticsearch using Java?

I have crawled few documents and created an index in elasticsearch. I am using sense to query:

This is my query in elasticsearch:

POST /index/_update_by_query
{
  "script": {
    "inline": "ctx._source.remove(\"home\")"
  },
  "query": {
        "wildcard": {
          "url": {
            "value": "http://search.com/*"
    }
  }
}

}

This is my Java program:

 Client client = TransportClient.builder().addPlugin(ReindexPlugin.class)
        .build().addTransportAddress(new InetSocketTransportAddress(
            InetAddress.getByName("127.0.0.1"), 9300));

    UpdateByQueryRequestBuilder ubqrb = UpdateByQueryAction.INSTANCE
        .newRequestBuilder(client);

    Script script1 = new Script("ctx._source.remove" +FieldName);

    BulkIndexByScrollResponse r = ubqrb.source("index").script(script1)
        .filter(wildcardQuery("url", patternvalue)).get();

FieldName(where home is saved as a string) is the name of the field which I want to remove from my documents. patternvalue is where pattern "http://search.com/*" is stored. When I run this Java program, it doesn't remove home field from my documents. It adds a new field in my documents called remove. I might be missing something. Any help would be appreciated

Upvotes: 2

Views: 1271

Answers (1)

Rodrigo
Rodrigo

Reputation: 67

If FieldName is the string home, then the expression "ctx._source.remove" +FieldName will be equal to "ctx._source.removehome" which is not the correct script. The correct code for that line is:

Script script1 = new Script("ctx._source.remove(\"" + FieldName + "\")");

This way the script will be:

ctx._source.remove("home")

That is the same as you wrote in json in:

"inline": "ctx._source.remove(\"home\")"

(\" in that json is just a " escaped in the json syntax)

Upvotes: 0

Related Questions