Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update nested field in an index of ElasticSearch with Java API

I am using Java API for CRUD operation on elasticsearch.

I have an typewith a nested field and I want to update this field.

Here is my mapping for the type:

"enduser": {
            "properties": {
                "location": {
                    "type": "nested",
                    "properties":{
                        "point":{"type":"geo_point"}
                    }
                }
            }
        }

Of course my enduser type will have other parameters.

Now I want to add this document in my nested field:

"location":{
          "name": "London",
           "point": "44.5, 5.2"
}

I was searching in documentation on how to update nested document but I couldn't find anything. For example I have in a string the previous JSON obect (let's call this string json). I tried the following code but seems to not working:

params.put("location", json);
client.prepareUpdate(index, ElasticSearchConstants.TYPE_END_USER,id).setScript("ctx._source.location = location").setScriptParams(params).execute().actionGet();

I have got a parsing error from elasticsearch. Anyone knows what I am doing wrong ?

like image 649
razafinr Avatar asked Dec 09 '22 08:12

razafinr


2 Answers

You don't need the script, just update it.

    UpdateRequestBuilder br = client.prepareUpdate("index", "enduser", "1");
    br.setDoc("{\"location\":{ \"name\": \"london\", \"point\": \"44.5,5.2\" }}".getBytes());
    br.execute();
like image 159
Alcanzar Avatar answered Dec 10 '22 20:12

Alcanzar


I tried to recreate your situation and i solved it by using an other way the .setScript method.

Your updating request now would looks like :

client.prepareUpdate(index, ElasticSearchConstants.TYPE_END_USER,id).setScript("ctx._source.location =" + json).execute().actionGet()

Hope it will help you.

like image 31
Blblblblblblbl Avatar answered Dec 10 '22 21:12

Blblblblblblbl