Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Use DB to augment ES hits for related media with required info (#3408)

Dhruv Bhanushaliadb56f128ca9
diff --git a/api/api/views/media_views.py b/api/api/views/media_views.py
index d003feec9..906e59747 100644
--- a/api/api/views/media_views.py
+++ b/api/api/views/media_views.py
@@ -105,6 +105,18 @@ class MediaViewSet(AsyncViewSetMixin, AsyncAPIView, ReadOnlyModelViewSet):
return req_serializer
def get_db_results(self, results):
+ """
+ Map ES hits to ORM model instances.
+
+ ORM instances have all necessary info needed for serializers whereas ES
+ hits only contain the subset of fields needed for indexing and search.
+ This function issues one query to the DB, using the ``identifier`` field
+ which is both unique and indexed, so it's quite performant.
+
+ :param results: the list of ES hits
+ :return: the corresponding list of ORM model instances
+ """
+
identifiers = []
hits = []
for hit in results:
@@ -267,6 +279,10 @@ class MediaViewSet(AsyncViewSetMixin, AsyncAPIView, ReadOnlyModelViewSet):
serializer_context = self.get_serializer_context()
+ serializer_class = self.get_serializer()
+ if serializer_class.needs_db:
+ results = self.get_db_results(results)
+
serializer = self.get_serializer(results, many=True, context=serializer_context)
return self.get_paginated_response(serializer.data)
diff --git a/api/test/media_integration.py b/api/test/media_integration.py
index f77ae5af0..0a4563344 100644
--- a/api/test/media_integration.py
+++ b/api/test/media_integration.py
@@ -227,6 +227,10 @@ def related(fixture):
or result["creator"] == item["creator"]
), f"{terms_set} {get_terms_set(result)}/{result['creator']}-{item['creator']}"
+ assert result["license_version"] is not None
+ assert result["attribution"] is not None
+ assert result["creator_url"] is not None
+
def sensitive_search_and_detail(media_type):
search_res = requests.get(