Spring Data Elastic Search: How to ignore mapping of hashset field

Viewed 706

I have two documents User & Activity, Both of them are indexed and I want to search user by firstName and lastName

User

@org.springframework.data.elasticsearch.annotations.Document(indexName = "user")
@Entity
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Field(type = FieldType.Text, fielddata = true)
    private String firstName;

    @Field(type = FieldType.Text, fielddata = true)
    private String lastName;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    @Field(type = FieldType.Nested)
    private Set<Activity> activities = new HashSet<>();
} 

Activity

@org.springframework.data.elasticsearch.annotations.Document(indexName = "activity")
@Entity
public class Activity implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Field(type = FieldType.Text, fielddata = true)
    private String name;

    @ManyToOne
    @JsonIgnore
    @EqualsAndHashCode.Exclude
    private User user;
} 

but I'm always getting this exception as follows

Caused by: com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) failed to map source through reference user["Activity"]->java.util.HashSet[0]

I'm using generated app with Jhipster 6.7.0 with Spring Data Elastic 3.2.7 and ES6.8.6
I'm really stuck for two weeks, I need to do my search without annotating "activities" field with @JsonIgnore I have many documents in my project that provide HashSet fields and I'm new to elastic so any optimized approach about how to ignore or map this kind of fields is very helpful.

1 Answers

Try adding

@JsonIgnoreProperties(ignoreUnknown = true)

at the top of you pojo. Like this:

    @org.springframework.data.elasticsearch.annotations.Document(indexName = "activity")
@Entity
@JsonIgnoreProperties(ignoreUnknown = true)
public class Activity implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Field(type = FieldType.Text, fielddata = true)
    private String name;

    @ManyToOne
    @JsonIgnore
    @EqualsAndHashCode.Exclude
    private User user;
} 

Edit: The @JsonIgnoreProperties(ignoreUnknown = true) would be over User pojo. Because you want to ignore Activity instantiation in the User Pojo. Also do not instantiate the Set as new HashSet. Hope this helps!

Related