I am trying to store entities containing (only) a json String in ElasticSearch, but want the fields in the json document to be stored individually in Elastic and NOT as a single String.
I am using the ElasticsearchRepository
public interface MyRepository extends ElasticsearchRepository<MyEntity, Long>
And have set up my entity as follows:
@NoArgsConstructor
@Getter
@Setter
@Document(indexName = "my-index")
public class MyEntity
{
@Id
private Long key;
private String json;
}
If the json object were simple, I could re-create all fields in the entity and map to those fields. Example:
json = "{"key":"123", "name":"Bob", "age":30, ...}"
And in MyEntity:
public class MyEntity
{
@Id
private Long key;
private String name;
private String age;
// And so on ...
}
I know this would work, but the real json strings contain hundreds of (nested) fields, which is why I do not want to have to re-create all of these in the entity class.
Can I achieve the same result without having to write out all the fields and still using repository.save()
?
This related question is from 2015. The solution passes a json file to 'setSource(jsonDoc)', but it does not look like the entities being saved contain any json.
Many thanks for your help!
You can use the @Field(type = FieldType.Object) annotation to store JSON documents in Elasticsearch with fields indexed individually and without having to recreate all the fields in your entity class. Try this approach;
@NoArgsConstructor
@Getter
@Setter
@Document(indexName = "my-index")
public class MyEntity {
@Id
private Long key;
@Field(type = FieldType.Object)
private Map<String, Object> json;
}