Search code examples
javaspringelasticsearchspring-dataspring-data-elasticsearch

How to map List of nested objects in Spring data elasticsearch


How to map Nested objects in Spring data elasticsearch

I have object 1 having list of object 2. How to efficiently map this so that querying back elasticsearch is easy ? I want to retrieve object 2 based on ID.

@Document(indexName = xxx, type = xxx)
public class Object1 {
    private List<Obj2> lstObj2;
} 

public class Obj2 {

    private Long id;
}

Solution

  • Use nested Object like this:

    @Document(indexName = xxx, type = xxx)
    public class Object1 {
    
      @Field(type = FieldType.Nested)
      private List<Obj2> lstObj2;
    } 
    
    public class Obj2 {
      private Long id;
    }
    

    As per your requirement it seems that you can use inner Object as well. Use inner object like this.

    @Field(type = FieldType.Object)
    private List<Obj2> lstObj2;