0

How to delete data based on condition from elastic search index using RestHighLevelClient in spring boot. for example from below example i want to delete from "companyaddress" based on condition -> "main_phone1" : "1"

"_index" : "es_52_companydetails_index",
        "_type" : "_doc",
        "_id" : "3",
        "_score" : 1.0,
        "_source" : {
          "company_id" : "3",
          "company_name" : "DEFG",
          "companyaddress" : [
            {
              "address3" : "smp1",
              "main_phone1" : "1"
            },
            {
              "address3" : "chtp2",
              "main_phone1" : "2"
            },
            {
              "address3" : "gmd",
              "main_phone1" : "3"
            },
            {
              "address3" : "tste",
              "main_phone1" : "4"
            }
          ]
        }
Dorayya
  • 11
  • 1
  • 6

2 Answers2

0

Use Update by query with Painless script.

This will perform an update on the documents specified by the query, and executes the defined Painless script on each document.

gaborsch
  • 15,408
  • 6
  • 37
  • 48
0

Below is code for delete data based on condition from elastic search index using RestHighLevelClient in spring boot

    RestHighLevelClient client = new RestHighLevelClient(
            RestClient.builder(new HttpHost("localhost", 9200, "http")));

    UpdateByQueryRequest request = new UpdateByQueryRequest("es_52_companydetails_index");
    request.setQuery(new TermQueryBuilder("companyaddress.main_phone1.keyword", "1"));

    Map<String, Object> param = new HashMap<String, Object>();

    String source = "for (int i = 0; i < ctx._source.companyaddress.length; ++i){if (ctx._source.companyaddress[i]['main_phone1'] == \"1\"){ctx._source.companyaddress.remove(i);}}";
    Script script = new Script(ScriptType.INLINE, "painless", source, param);

    request.setScript(script);
    client.updateByQuery(request, RequestOptions.DEFAULT);
    client.close();

Below is equivalent update by query rest API json:

POST es_52_companydetails_index/_update_by_query
{
  "query": {
    "term": {
      "companyaddress.main_phone1.keyword": {
        "value": "1"
      }
    }
  },
  "script": {
    "source": """
    for (int i = 0; i < ctx._source.companyaddress.length; ++i)
    {
      if (ctx._source.companyaddress[i]['main_phone1'] == "1")
      {ctx._source.companyaddress.remove(i);}
    }""",
    "lang": "painless"
  }
}
Sagar Patel
  • 4,993
  • 1
  • 8
  • 19