diff --git a/backend/app/services/search.py b/backend/app/services/search.py index 406ecf1..caf4f5a 100644 --- a/backend/app/services/search.py +++ b/backend/app/services/search.py @@ -102,12 +102,16 @@ async def hybrid_search( # If no text query, fall back to recent photos if not q: - stmt = select(Photo.id).order_by(Photo.created_at.desc()) if tag_ids: from app.models.tags import photo_tags - stmt = stmt.join(photo_tags, Photo.id == photo_tags.c.photo_id).where( + # Subquery to get distinct photo_ids matching the tag filter + sub = select(photo_tags.c.photo_id).where( photo_tags.c.tag_id.in_(tag_ids) - ).distinct() + ).distinct().subquery() + stmt = select(Photo.id).join(sub, Photo.id == sub.c.photo_id) + else: + stmt = select(Photo.id) + stmt = stmt.order_by(Photo.added_at.desc()) if date_from: stmt = stmt.where(Photo.taken_at >= date_from) if date_to: