Search code examples
javaelasticsearchspring-data-elasticsearch

Spring ElasticSearch - How to store whole child object inside parent object?


I am trying to insert data into elasticsearch. I have Java classes like this,

@Data
public class Common {

    @Id
    private String id;
}

@Getter @Setter
public class Student extends Common {

    private String name;
    private String phone;
    private String password;
    @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "yyyy-MM-dd'T'HH:mm:ss")
    private LocalDateTime createdAt;
}

@Getter @Setter
@Document(indexName = "table")
public class Table extends Common {

    @Field(type = FieldType.Auto, includeInParent = true)
    private Student student;

    private String attends;
}

What I need is, I need to store Student data (Full Data Object) inside Table object in elasticsearch table index. I don't want to store Student separately as another index. Instead of that I need to store that data also inside that Table. I tried many ways including nested and object field types. But none of them are working. It is not storing whole student object inside the Table object. It is only inserting id of the student.

So how I can achieve that? How to store student object inside table object. Anybody can help me? Thanks in advance.


Solution

  • Define the property as @FieldType.Object:

    @Document(indexName = "table")
    public class Table extends Common {
    
        @Field(type = FieldType.Object)
        private Student student;
    
        private String attends;
    }
    

    Edit:

    I should not answer without trying it out first. The field definition is alright, you need to define getter and setter methods for the properties of the classes.