Elasticsearch Java API cannot ignore null or empty values

Viewed 37

I am using the new-to-me Spring Elasticsearch API which no longer supports Jackson serialization. I'm in the process of updating all my entities, but have run into an issue where I can no longer ignore properties that have a null or empty value when serializing.

Can someone help point me to some documentation for the new Java API that mimics the Jackson @JsonInclude(Include.NonNull, Include.NonEmpty) annotation, which ONLY includes the property when its value is NOT null and NOT empty.

I've looked all over the web, but I cannot find any hints as to how this can be accomplished.

Any links or insight is greatly appreciated.

1 Answers

Here's one way to solve the issue I describe above:

Foo Entity

public class Foo {
    @Id
    private String id;

    @Nullable
    @Field(type = FieldType.Object)
    private Map<String, Object> map1;

    @Nullable
    @Field(type = FieldType.Object)
    private Map<String, Object> map2;

       // getter and setter
}

Code to populate Foo

var foo = new Foo();
foo.setId("42");
foo.setMap1(null);
foo.setMap2(new LinkedHashMap<>());
operations.save(foo);

The following gets sent to Elastic

{"_class":"com.package.to.Foo","id":"42","map2":{}}

A BeforeConvertCallback class that turns initialized, but empty, values to null preventing them from being sent to elastic.

@Component
public class FooBeforeConvertCallback implements BeforeConvertCallback<Foo> {

    @Override
    public Foo onBeforeConvert(Foo foo, IndexCoordinates indexCoordinates) {


        if (CollectionUtils.isEmpty(foo.getMap1())) {
            foo.setMap1(null);
        }

        if (CollectionUtils.isEmpty(foo.getMap2())) {
            foo.setMap2(null);
        }
        return foo;
    }
}

This solution will ONLY work for the entity Foo.

Related