Skip to content

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

Log times of ES queries (#3300)

Olga Bulat209045a320da
diff --git a/api/api/controllers/elasticsearch/helpers.py b/api/api/controllers/elasticsearch/helpers.py
new file mode 100644
index 000000000..28a9c1cb2
--- /dev/null
+++ b/api/api/controllers/elasticsearch/helpers.py
@@ -0,0 +1,57 @@
+from __future__ import annotations
+
+import functools
+import logging as log
+import pprint
+import time
+
+from django.conf import settings
+
+from elasticsearch import BadRequestError, NotFoundError
+
+
+def log_timing_info(func):
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ start_time = time.time()
+
+ # Call the original function
+ result = func(*args, **kwargs)
+
+ response_time_in_ms = int((time.time() - start_time) * 1000)
+ if hasattr(result, "took"):
+ es_time_in_ms = result.took
+ else:
+ es_time_in_ms = result["took"]
+ log.info(
+ {
+ "response_time": response_time_in_ms,
+ "es_time": es_time_in_ms,
+ "search_query": kwargs.get("search_query"),
+ }
+ )
+
+ return result
+
+ return wrapper
+
+
+@log_timing_info
+def get_es_response(s, search_query=None):
+ if settings.VERBOSE_ES_RESPONSE:
+ log.info(pprint.pprint(s.to_dict()))
+
+ try:
+ search_response = s.execute()
+
+ if settings.VERBOSE_ES_RESPONSE:
+ log.info(pprint.pprint(search_response.to_dict()))
+ except (BadRequestError, NotFoundError) as e:
+ raise ValueError(e)
+
+ return search_response
+
+
+@log_timing_info
+def get_raw_es_response(index, body, search_query=None, **kwargs):
+ return settings.ES.search(index=index, body=body, **kwargs)
diff --git a/api/api/controllers/search_controller.py b/api/api/controllers/search_controller.py
index a9bf0b926..a08e2da3f 100644
--- a/api/api/controllers/search_controller.py
+++ b/api/api/controllers/search_controller.py
@@ -1,7 +1,6 @@
from __future__ import annotations
import logging as log
-import pprint
from itertools import accumulate
from math import ceil
from typing import Literal
@@ -9,7 +8,7 @@ from typing import Literal
from django.conf import settings
from django.core.cache import cache
-from elasticsearch.exceptions import BadRequestError, NotFoundError
+from elasticsearch.exceptions import NotFoundError
from elasticsearch_dsl import Q, Search
from elasticsearch_dsl.query import EMPTY_QUERY, Match, SimpleQueryString, Term
from elasticsearch_dsl.response import Hit, Response
@@ -17,6 +16,7 @@ from elasticsearch_dsl.response import Hit, Response
import api.models as models
from api.constants.media_types import OriginIndex
from api.constants.sorting import INDEXED_ON
+from api.controllers.elasticsearch.helpers import get_es_response, get_raw_es_response
from api.serializers import media_serializers
from api.utils import tallies
from api.utils.check_dead_links import check_dead_links
@@ -223,7 +223,7 @@ def _post_process_results(
end = search_results.hits.total.value
s = s[start:end]
- search_response = s.execute()
+ search_response = get_es_response(s, "postprocess_search")
return _post_process_results(
s, start, end, page_size, search_response, filter_dead
@@ -448,16 +448,7 @@ def search(
# Paginate
start, end = _get_query_slice(s, page_size, page, filter_dead)
s = s[start:end]
- try:
- if settings.VERBOSE_ES_RESPONSE:
- log.info(pprint.pprint(s.to_dict()))
-
- search_response = s.execute()
-
- if settings.VERBOSE_ES_RESPONSE:
- log.info(pprint.pprint(search_response.to_dict()))
- except (BadRequestError, NotFoundError) as e:
- raise ValueError(e)
+ search_response = get_es_response(s, "search")
results = _post_process_results(
s, start, end, page_size, search_response, filter_dead
@@ -554,7 +545,7 @@ def related_media(uuid: str, index: str, filter_dead: bool) -> list[Hit]:
start, end = _get_query_slice(s, page_size, page, filter_dead)
s = s[start:end]
- response = s.execute()
+ response = get_es_response(s, "related_media")
results = _post_process_results(s, start, end, page_size, response, filter_dead)
return results or []
@@ -577,21 +568,26 @@ def get_sources(index):
if type(sources) == list or cache_fetch_failed:
# Invalidate old provider format.
cache.delete(key=source_cache_name)
- if not sources:
+ if not sources or sources:
# Don't increase `size` without reading this issue first:
# https://github.com/elastic/elasticsearch/issues/18838
size = 100
- aggs = {
- "unique_sources": {
- "terms": {
- "field": "source",
- "size": size,
- "order": {"_key": "desc"},
+ body = {
+ "size": 0,
+ "aggs": {
+ "unique_sources": {
+ "terms": {
+ "field": "source",
+ "size": size,
+ "order": {"_key": "desc"},
+ }
}
- }
+ },
}
try:
- results = settings.ES.search(index=index, aggs=aggs, request_cache=True)
+ results = get_raw_es_response(
+ index=index, body=body, search_query="sources", request_cache=True
+ )
buckets = results["aggregations"]["unique_sources"]["buckets"]
except NotFoundError:
buckets = [{"key": "none_found", "doc_count": 0}]
diff --git a/api/api/utils/search_context.py b/api/api/utils/search_context.py
index d733df801..4c26811d0 100644
--- a/api/api/utils/search_context.py
+++ b/api/api/utils/search_context.py
@@ -6,6 +6,7 @@ from django.conf import settings
from elasticsearch_dsl import Q, Search
from api.constants.media_types import OriginIndex
+from api.controllers.elasticsearch.helpers import get_es_response
@dataclass
@@ -41,9 +42,10 @@ class SearchContext:
# The default query size is 10, so we need to slice the query
# to change the size to be big enough to encompass all the
# results.
- results_in_filtered_index = filtered_index_search[
- : len(all_result_identifiers)
- ].execute()
+ filtered_index_slice = filtered_index_search[: len(all_result_identifiers)]
+ results_in_filtered_index = get_es_response(
+ filtered_index_slice, "filtered_index_context"
+ )
filtered_index_identifiers = {
result.identifier for result in results_in_filtered_index
}