FailedShack
FailedShack

Reputation: 91

Hibernate: Retrieve distance value from spatial search

I'm trying to retrieve a list of shops within the radius of the user's current location using Hibernate Spatial. I want to provide the distance to the user along with each result without calculating the distance twice.

Hibernate's documentation suggests setting a projection to the FullTextQuery in order to include the distance in the results. However, the example provides no indication of how to retrieve said value. The example simply ends up retrieving a list of shops within the radius but not the distance to the center.

This is what my code looks like at the moment:

FullTextSession session = (FullTextSession)Search.getFullTextEntityManager(entityManager);
QueryBuilder builder = session.getSearchFactory()
        .buildQueryBuilder().forEntity(Shop.class).get();

Query query = builder.spatial()
        .onField("location")
        .within(radius, Unit.KM)
            .ofLatitude(latitude)
            .andLongitude(longitude)
        .createQuery();

FullTextQuery hibernate = session.createFullTextQuery(query)
        .setProjection(FullTextQuery.SPATIAL_DISTANCE, FullTextQuery.THIS)
        .setSpatialParameters(latitude, longitude, "location");

// TODO: build map of shops and their distance

Upvotes: 0

Views: 689

Answers (1)

yrodiere
yrodiere

Reputation: 9977

The distances are included in the query hit, in an object array, just like any other projection.

FullTextSession session = (FullTextSession)Search.getFullTextEntityManager(entityManager);
QueryBuilder builder = session.getSearchFactory()
        .buildQueryBuilder().forEntity(Shop.class).get();

Query query = builder.spatial()
        .onField("location")
        .within(radius, Unit.KM)
            .ofLatitude(latitude)
            .andLongitude(longitude)
        .createQuery();

FullTextQuery ftQuery = session.createFullTextQuery(query, Shop.class)
        .setProjection(FullTextQuery.SPATIAL_DISTANCE, FullTextQuery.THIS)
        .setSpatialParameters(latitude, longitude, "location");

List<Object[]> results = ftQuery.list();
Object[] firstResult = results.get(0);
Double distance = (Double) firstResult[0];
Shop shop = (Shop) firstResult[1];

See https://docs.jboss.org/hibernate/search/5.11/reference/en-US/html_single/#projections

Upvotes: 1

Related Questions