Skip to content

Commit a9f7ab0

Browse files
committed
Add GET /api/movies/genres endpoint to Java Spring and Python FastAPI backends
- Java: Added getDistinctGenres() to MovieService interface and MovieServiceImpl - Java: Added /genres endpoint to MovieControllerImpl using mongoTemplate.findDistinct() - Python: Added /genres endpoint to movies.py router using collection.distinct() - Both implementations filter null/empty values and sort alphabetically - Returns success response with count of distinct genres
1 parent 14d030f commit a9f7ab0

4 files changed

Lines changed: 86 additions & 2 deletions

File tree

mflix/server/java-spring/src/main/java/com/mongodb/samplemflix/controller/MovieControllerImpl.java

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,26 @@ public ResponseEntity<SuccessResponse<List<Movie>>> getAllMovies(
109109

110110
return ResponseEntity.ok(response);
111111
}
112-
112+
113+
@Operation(
114+
summary = "Get all distinct genres",
115+
description = "Retrieve a list of all unique genre values from the movies collection. " +
116+
"Demonstrates the distinct() operation. Returns genres sorted alphabetically."
117+
)
118+
@GetMapping("/genres")
119+
public ResponseEntity<SuccessResponse<List<String>>> getDistinctGenres() {
120+
List<String> genres = movieService.getDistinctGenres();
121+
122+
SuccessResponse<List<String>> response = SuccessResponse.<List<String>>builder()
123+
.success(true)
124+
.message("Found " + genres.size() + " distinct genres")
125+
.data(genres)
126+
.timestamp(Instant.now().toString())
127+
.build();
128+
129+
return ResponseEntity.ok(response);
130+
}
131+
113132
@Operation(
114133
summary = "Get a single movie by ID",
115134
description = "Retrieve a single movie by its MongoDB ObjectId."

mflix/server/java-spring/src/main/java/com/mongodb/samplemflix/service/MovieService.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,14 @@ public interface MovieService {
2121

2222
List<Movie> getAllMovies(MovieSearchQuery query);
2323

24+
/**
25+
* Gets all distinct genre values from the movies collection.
26+
* Demonstrates the distinct() operation.
27+
*
28+
* @return List of unique genre strings, sorted alphabetically
29+
*/
30+
List<String> getDistinctGenres();
31+
2432
Movie getMovieById(String id);
2533

2634
Movie createMovie(CreateMovieRequest request);

mflix/server/java-spring/src/main/java/com/mongodb/samplemflix/service/MovieServiceImpl.java

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,25 @@ public List<Movie> getAllMovies(MovieSearchQuery query) {
8585

8686
return mongoTemplate.find(mongoQuery, Movie.class);
8787
}
88-
88+
89+
@Override
90+
public List<String> getDistinctGenres() {
91+
// Use MongoTemplate's findDistinct to get all unique values from the genres array field
92+
// MongoDB automatically flattens array fields when using distinct()
93+
List<String> genres = mongoTemplate.findDistinct(
94+
new Query(),
95+
Movie.Fields.GENRES,
96+
Movie.class,
97+
String.class
98+
);
99+
100+
// Filter out null/empty values and sort alphabetically
101+
return genres.stream()
102+
.filter(genre -> genre != null && !genre.isEmpty())
103+
.sorted(String::compareTo)
104+
.collect(Collectors.toList());
105+
}
106+
89107
@Override
90108
public Movie getMovieById(String id) {
91109
if (!ObjectId.isValid(id)) {

mflix/server/python-fastapi/src/routers/movies.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@
3232
Search movies using MongoDB Vector Search to enable semantic search capabilities over
3333
the plot field.
3434
35+
- GET /api/movies/genres :
36+
Retrieve all distinct genre values from the movies collection.
37+
Demonstrates the distinct() operation.
38+
3539
- GET /api/movies/{id} :
3640
Retrieve a single movie by its ID.
3741
@@ -427,6 +431,41 @@ async def vector_search_movies(
427431
detail=f"Error performing vector search: {str(e)}"
428432
)
429433

434+
"""
435+
GET /api/movies/genres
436+
437+
Retrieve all distinct genre values from the movies collection.
438+
Demonstrates the distinct() operation.
439+
440+
Returns:
441+
SuccessResponse[List[str]]: A response object containing the list of unique genres, sorted alphabetically.
442+
"""
443+
444+
@router.get("/genres",
445+
response_model=SuccessResponse[List[str]],
446+
status_code=200,
447+
summary="Retrieve all distinct genres from the movies collection.")
448+
async def get_distinct_genres():
449+
movies_collection = get_collection("movies")
450+
451+
try:
452+
# Use distinct() to get all unique values from the genres array field
453+
# MongoDB automatically flattens array fields when using distinct()
454+
genres = await movies_collection.distinct("genres")
455+
except Exception as e:
456+
raise HTTPException(
457+
status_code=500,
458+
detail=f"Database error occurred: {str(e)}"
459+
)
460+
461+
# Filter out null/empty values and sort alphabetically
462+
valid_genres = sorted([
463+
genre for genre in genres
464+
if isinstance(genre, str) and len(genre) > 0
465+
])
466+
467+
return create_success_response(valid_genres, f"Found {len(valid_genres)} distinct genres")
468+
430469
"""
431470
GET /api/movies/{id}
432471
Retrieve a single movie by its ID.

0 commit comments

Comments
 (0)