7

I'm using Spring Data ElasticSearch to perform CRUD operations. By default, when a POJO annotated with @Document gets written to an ElasticSearch index, the index field names are the same as the POJO's Java property names. How can I configure the index field names to be different ? For example, with this Document POJO:

@Document(indexName = "areas", type = "area")
public class Area {

    @Id
    private String id;
    private String countyName;
    private String postOfficeName;
    private String stateName;

how can I configure this so that the index field in ElasticSearch gets serialized as county_name instead of countyName ?

Fabien Coppens
  • 273
  • 4
  • 12
  • 1
    I have found sort of a workaround by adding Jackson's @JsonProperty("county_name") in the @Document annotated POJO, but that has the downside of losing the power of Spring Data's DSL findBy... operations since they rely on the camelCased Java property names. – Fabien Coppens Mar 04 '15 at 20:10
  • More detail on the use of the `@JspnProperty` is discussed in http://stackoverflow.com/questions/33537229/spring-elastic-search-custom-field-names – Javaru Jan 05 '16 at 18:03

2 Answers2

1

As Spring-data-elasticsearch uses fasterxml module to convert POJOs to json document, you could simply use,

@JsonProperty("country_name")
private String countryName

To achieve a different field name in the elasticsearch index.

  • this is a pure strategy, when you want it to use the same DTO/POJO with the rest response, where you need exactly the field names you use in the POJO. no way to produce the json with diffeerent field names for the rest response and elasticsearch request – Eljah Aug 12 '19 at 16:30
  • Not helping in my case! note: I use `createIndex=false` – Ram Aug 29 '19 at 13:20
-2

I think that you have to use properties of @Field annotation, I'm almost sure of this. Please See here.

As from documentation:

@Field: Applied at the field level and defines properties of the field, most of the attributes map to the respective Elasticsearch Mapping definitions (the following list is not complete, check the annotation Javadoc for a complete reference):

name: The name of the field as it will be represented in the Elasticsearch document, if not set, the Java field name is used.

type: the field type, can be one of Text, Keyword, Long, Integer, Short, Byte, Double, Float, Half_Float, Scaled_Float, Date, Date_Nanos, Boolean, Binary, Integer_Range, Float_Range, Long_Range, Double_Range, Date_Range, Ip_Range, Object, Nested, Ip, TokenCount, Percolator, Flattened, Search_As_You_Type. See Elasticsearch Mapping Types

format and pattern definitions for the Date type. format must be defined for date types.

store: Flag wether the original field value should be store in Elasticsearch, default value is false.

analyzer, searchAnalyzer, normalizer for specifying custom custom analyzers and normalizer.

andPat
  • 4,153
  • 7
  • 24
  • 36