Search code examples
javaelasticsearchquerydslelasticsearch-java-api

Updating multiple documents in elasticsearch using Java. I am using Elasticsearch 2.3.2


I want to update some of my indexed data with a particular field using Java Api. I have referred this document https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-docs-update.html and created a java program. My Java program looks like this:

public class App {

  public static void main(String[] args) throws Exception {
    Client client = TransportClient.builder().build().addTransportAddress(
        new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"),
            9300));
UpdateRequest updateRequest = new UpdateRequest("pibindex", "SearchTech",
        "http://www.sea.com/bundle")
            .script(new Script("ctx._source.default_collection = \"true\""));
    client.update(updateRequest).get();
   }
}

This program is updating a single document based on a script. "pibindex" is the name of my index, "SearchTech" is the type of my index and "http://www.sea.com/bundle" is the id of my document. I would like to update multiple documents with a new field "wiki_collection":true which matches a pattern like "http://www.sea.com/bundle". I want to use wildcard query.

I am trying to implement this elasticsearch query in Java:

POST /pibindex2/_update_by_query
{
  "script": {
    "inline": "ctx._source.wiki_collection=true"
  },
      "query": {
        "wildcard": {
          "url": {
            "value": "http://www.sea.com/bundle/*"
          }
        }
      }
}

Sorry if I’m missing something obvious. Thank you.


Solution

  • You can try this way:

    import static org.elasticsearch.index.query.QueryBuilders.wildcardQuery;
    
    BulkIndexByScrollResponse r = ubqrb.source("twitter")
        .script(script)
        .filter(wilcardQuery("url", "http://www.sea.com/bundle/*"))
        .get();
    

    Although the result will depend on whether your url field is analyzed or not.