7.16 Java Client - UpdateRequest example

Hi, I'm struggling to understand how to do an UpdateRequest with the latest java client.

For example, this:

        client.update(new UpdateRequest.Builder<>()
                .index(index)
                .id(id)
                .doc(document)
                .build());

Won't compile, error:

Cannot resolve method 'update(co.elastic.clients.elasticsearch.core.UpdateRequest<java.lang.Object,java.lang.Object>)'

Can I do partial document updates using the IndexRequest instead?

An example for how to do a script in an UpdateRequest would be really great as well.

Hoping someone can point me in the right direction!

Cheers

Trying this for scripted update:

        client().update(new UpdateRequest.Builder<>()
                .index(index)
                .id(id)
                .lang("painless")
                .script(new Script.Builder()
                        .inline(new InlineScript.Builder()
                                .source("ctx._source.status = '"+ status +"'")
                                .build())
                        .build())
                .build());

but nothing compiles, so I don't know what's supposed to work. :person_shrugging:

Thanks for the feedback @ndtreviv. The update API requires an additional Class parameter.

The reason for this is the source parameter that allows retrieving the modified document. In your case you're not requesting it, so we can use the Void class.

Assuming the class of document is SomeDoc:

client.update(new UpdateRequest.Builder<Void, SomeDoc>()
    .index(index)
    .id(id)
    .doc(document)
    .build(),
    Void.class // <-- additional parameter
);

You can also write it in a more compact form as:

client.update(b -> b
    .index(index)
    .id(id)
    .doc(appData),
    Void.class
);

and similarly for the script update:

client.update(u -> u
    .index(index)
    .id(id)
    .lang("painless")
    .script(s -> s
        .inline(i -> i
            .source("ctx._source.status = '"+ status +"'")
        )
    ),
    Void.class
);

Hope this helps. We're currently improving the docs, a section on the update request will be added there.

1 Like

Thank you! I'm getting the hang of it now :sweat_smile:

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.