-1

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!

1
  • if you did create the entity object, would there be any nullable fields? You could use a tool for building the entity object. I would use chatgpt. but there are other json to POJO tools available as well. You would want as many of the fields as should exist in the entity to be present in the json. Then, some of the types are likely strings and should be Longs. Commented Jul 17, 2024 at 16:58

1 Answer 1

0

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.