Recently I was working on a Project which involved Spring Data Elasticsearch and needed to use geo_point type field in the Elasticsearch index for speedier location based searches. Spring Data Elasticsearch provides a data type by the name GeoPoint to achieve this and an annotation named @GeoPointField to mark such fields.
@Document(indexName = "properties", replicas = 0, refreshInterval = "-1")
public class Property implements Serializable {
...
@GeoPointField
private GeoPoint location;
...
But sadly for me creating a repository out for the above @Document and saving objects was keep on converting the GeoPoint field to a plain map of latitude and longitude but not as a geo_point field.
"location": {
"properties": {
"latitude": {
"type": "string"
},
"longitude": {
"type": "string"
}
}
}
This results in following error while querying using Geo Distance Query.
QueryParsingException failed to find geo_point field
After some research I finally found out that in such cases we would need to manually create the index before calling Repository.save.
In a service or any other initializer class you need to do the following;
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
@PostConstruct
public void init() {
IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(Property.class);
indexOperations.putMapping(indexOperations.createMapping());
indexOperations.refresh();
}
This fixes the issue and creates the location field with type geo_point as expected.