Restaurant Search Repository

In this lesson, we'll enhance our RestaurantRepository interface with search capabilities, allowing users to find restaurants based on various criteria such as cuisine type, rating, and location.

Adding Basic Search Methods

Spring Data Elasticsearch makes it easy to create search methods by following a specific naming convention.

Let's start by adding methods for searching by rating:

@Repository public interface RestaurantRepository extends ElasticsearchRepository<Restaurant, String> { // Search by minimum rating Page<Restaurant> findByAverageRatingGreaterThanEqual(Float minRating, Pageable pageable); }

Advanced Search with Custom Queries

For more complex searches, we need to use custom Elasticsearch queries using the @Query annotation.

Here's how we implement fuzzy search for restaurant names or cuisine types:

@Repository public interface RestaurantRepository extends ElasticsearchRepository<Restaurant, String> { // ... @Query("{" + " \"bool\": {" + " \"must\": [" + " {\"range\": {\"averageRating\": {\"gte\": ?1}}}" + " ]," + " \"should\": [" + " {\"fuzzy\": {\"name\": {\"value\": \"?0\", \"fuzziness\": \"AUTO\"}}}," + " {\"fuzzy\": {\"cuisineType\": {\"value\": \"?0\", \"fuzziness\": \"AUTO\"}}}" + " ]," + " \"minimum_should_match\": 1" + " }" + "}" + "}") Page<Restaurant> findByQueryAndMinRating(String query, Float minRating, Pageable pageable); }

Location-based search requires specialized Elasticsearch queries to handle geographical calculations:

@Repository public interface RestaurantRepository extends ElasticsearchRepository<Restaurant, String> { //... @Query("{" + " \"bool\": {" + " \"must\": [" + " {\"geo_distance\": {" + " \"distance\": \"?2km\"," + " \"geoLocation\": {" + " \"lat\": ?0," + " \"lon\": ?1" + " }" + " }}" + " ]" + " }" + "}") Page<Restaurant> findByLocationNear( Float latitude, Float longitude, Float radiusKm, Pageable pageable);

Summary

  • Implemented basic search methods using Spring Data Elasticsearch naming conventions
  • Implemented fuzzy search using the @Query annotation
  • Created a location-based search method using Elasticsearch geo queries
© 2026 Devtiro Ltd. All rights reserved