From 1810918e433c0551b808ffd67b56bee49538f937 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 26 Jul 2026 09:22:50 +0200 Subject: [PATCH 1/5] move headers to function --- .../main/inse/integrations/elasticsearch.py | 33 ++++++++----------- 1 file changed, 14 insertions(+), 19 deletions(-) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index afc08614..83532750 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -110,6 +110,10 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]: return None +def _headers(api_key: str, content_type: str = "application/json") -> Dict[str, str]: + return {"Authorization": f"ApiKey {api_key}", "Content-Type": content_type} + + def _wrap_exception(e: Exception) -> Exception: logger.exception(f"Elasticsearch raised an exception: {e}") if isinstance(e, httpx.HTTPStatusError): @@ -177,8 +181,6 @@ async def search( elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} - payload: Dict[str, Any] = {} if body is not None: @@ -221,7 +223,7 @@ async def search( try: response = await client.post( - f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=headers + f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=_headers(api_key) ) response.raise_for_status() return response.json() @@ -234,14 +236,13 @@ async def open_point_in_time( ) -> str: """Opens a point-in-time on the given index and returns its id.""" elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} client = get_client() try: response = await client.post( f"{elasticsearch_url}/{index}/_pit", params={"keep_alive": keep_alive}, - headers=headers, + headers=_headers(api_key), ) response.raise_for_status() return response.json()["id"] @@ -252,7 +253,6 @@ async def open_point_in_time( async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None: """Closes a previously opened point-in-time.""" elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} client = get_client() try: @@ -260,7 +260,7 @@ async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None: "DELETE", f"{elasticsearch_url}/_pit", json={"id": pit_id}, - headers=headers, + headers=_headers(api_key), ) response.raise_for_status() except Exception as exc: @@ -281,7 +281,6 @@ async def scan( ``index.max_result_window``, so it can stream result sets larger than 10k. """ elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} pit_id = await open_point_in_time(index, keep_alive=keep_alive, cluster=cluster) search_after: Optional[List] = None @@ -301,7 +300,7 @@ async def scan( try: response = await client.post( - f"{elasticsearch_url}/_search", json=payload, headers=headers + f"{elasticsearch_url}/_search", json=payload, headers=_headers(api_key) ) response.raise_for_status() except Exception as exc: @@ -340,7 +339,6 @@ async def get( elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} params = {} if source is not None: @@ -349,7 +347,7 @@ async def get( client = get_client() try: response = await client.get( - f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=headers + f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=_headers(api_key) ) response.raise_for_status() return response.json() @@ -364,14 +362,13 @@ async def update( cluster: ESCluster = ESCluster.NES, ) -> Dict[str, Any]: elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} client = get_client() try: response = await client.post( f"{elasticsearch_url}/{index}/_update/{doc_id}", json={"doc": doc}, - headers=headers, + headers=_headers(api_key), ) response.raise_for_status() return response.json() @@ -386,14 +383,13 @@ async def index_doc( cluster: ESCluster = ESCluster.NES, ) -> Dict[str, Any]: elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} client = get_client() try: response = await client.put( f"{elasticsearch_url}/{index}/_doc/{doc_id}", json=document, - headers=headers, + headers=_headers(api_key), ) response.raise_for_status() return response.json() @@ -432,7 +428,6 @@ async def count( cluster = clusters.pop() elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} if isinstance(index, list): index_str = ",".join(str(idx) for idx in index) @@ -443,7 +438,7 @@ async def count( client = get_client() try: response = await client.post( - f"{elasticsearch_url}/{index_str}/_count", json=payload, headers=headers + f"{elasticsearch_url}/{index_str}/_count", json=payload, headers=_headers(api_key) ) response.raise_for_status() return response.json().get("count", 0) @@ -474,7 +469,7 @@ async def msearch( cluster = c elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/x-ndjson"} + headers = _headers(api_key, content_type="application/x-ndjson") lines = [] for idx, body in searches: @@ -493,7 +488,7 @@ async def msearch( response = await client.post( f"{elasticsearch_url}/_msearch", content=ndjson_payload.encode("utf-8"), - headers=headers, + headers=_headers(api_key), ) response.raise_for_status() res_json = response.json() -- 2.56.1 From b0e4ad639eecf9b57a97405bed31d7cdec0bfe40 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 26 Jul 2026 09:34:02 +0200 Subject: [PATCH 2/5] centralize HTTP request handling --- .../main/inse/integrations/elasticsearch.py | 186 ++++++++---------- 1 file changed, 77 insertions(+), 109 deletions(-) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 83532750..250786af 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -129,6 +129,51 @@ def _wrap_exception(e: Exception) -> Exception: return ElasticsearchException(f"Unexpected Elasticsearch error: {e}") +async def _request( + method: str, + cluster: ESCluster, + path: str, + *, + json_body: Optional[Any] = None, + params: Optional[Dict[str, Any]] = None, + content: Optional[bytes] = None, + content_type: str = "application/json", +) -> httpx.Response: + """Sends an authenticated request to cluster and returns the raw response. + + Args: + method: The HTTP method (e.g. "GET", "POST", "PUT", "DELETE"). + cluster: The Elasticsearch cluster to send the request to. + path: The path appended to the cluster URL (without leading slash). + json_body: Optional JSON-serialisable request body. + params: Optional query parameters. + content: Optional raw request body (e.g. ndjson); mutually exclusive with json_body. + content_type: The Content-Type header value. + + Returns: + httpx.Response: The successful response (status already checked). + """ + + elasticsearch_url, api_key = _cluster_credentials(cluster) + client = get_client() + + try: + response = await client.request( + method, + f"{elasticsearch_url}/{path}", + json=json_body, + params=params, + content=content, + headers=_headers(api_key, content_type=content_type), + ) + + response.raise_for_status() + + return response + except Exception as exc: + raise _wrap_exception(exc) from exc + + async def search( index: ESIndex | List[ESIndex] | str | List[str], query: Optional[Dict] = None, @@ -179,8 +224,6 @@ async def search( elif len(clusters) == 1: cluster = clusters.pop() - elasticsearch_url, api_key = _cluster_credentials(cluster) - payload: Dict[str, Any] = {} if body is not None: @@ -212,59 +255,33 @@ async def search( "At least one of 'query', 'body', 'source', 'size', 'offset', 'sort', 'aggs' must be provided" ) - client = get_client() logger.debug( - f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}" + f"Sending search request to Elasticsearch cluster '{cluster}' for {index} with payload: {json.dumps(payload)}" ) + if isinstance(index, list): index_str = ",".join(str(idx) for idx in index) else: index_str = str(index) - try: - response = await client.post( - f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=_headers(api_key) - ) - response.raise_for_status() - return response.json() - except Exception as exc: - raise _wrap_exception(exc) from exc + response = await _request("POST", cluster, f"{index_str}/_search", json_body=payload) + + return response.json() async def open_point_in_time( index: str, keep_alive: str = "1m", cluster: str = "nes" ) -> str: """Opens a point-in-time on the given index and returns its id.""" - elasticsearch_url, api_key = _cluster_credentials(cluster) + response = await _request("POST", cluster, f"{index}/_pit", params={"keep_alive": keep_alive}) - client = get_client() - try: - response = await client.post( - f"{elasticsearch_url}/{index}/_pit", - params={"keep_alive": keep_alive}, - headers=_headers(api_key), - ) - response.raise_for_status() - return response.json()["id"] - except Exception as exc: - raise _wrap_exception(exc) from exc + return response.json()["id"] async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None: """Closes a previously opened point-in-time.""" - elasticsearch_url, api_key = _cluster_credentials(cluster) - client = get_client() - try: - response = await client.request( - "DELETE", - f"{elasticsearch_url}/_pit", - json={"id": pit_id}, - headers=_headers(api_key), - ) - response.raise_for_status() - except Exception as exc: - raise _wrap_exception(exc) from exc + await _request("DELETE", cluster, "_pit", json_body={"id": pit_id}) async def scan( @@ -280,12 +297,9 @@ async def scan( Unlike ``from``/``size`` pagination, this is not bounded by ``index.max_result_window``, so it can stream result sets larger than 10k. """ - elasticsearch_url, api_key = _cluster_credentials(cluster) - pit_id = await open_point_in_time(index, keep_alive=keep_alive, cluster=cluster) search_after: Optional[List] = None try: - client = get_client() while True: payload: Dict[str, Any] = { "size": page_size, @@ -298,14 +312,7 @@ async def scan( if search_after is not None: payload["search_after"] = search_after - try: - response = await client.post( - f"{elasticsearch_url}/_search", json=payload, headers=_headers(api_key) - ) - response.raise_for_status() - except Exception as exc: - raise _wrap_exception(exc) from exc - + response = await _request("POST", cluster, "_search", json_body=payload) result = response.json() hits = result.get("hits", {}).get("hits", []) @@ -337,22 +344,13 @@ async def get( if isinstance(index, ESIndex): cluster = _index_to_cluster(index) or cluster - elasticsearch_url, api_key = _cluster_credentials(cluster) - - params = {} if source is not None: params["_source_includes"] = ",".join(source) - client = get_client() - try: - response = await client.get( - f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=_headers(api_key) - ) - response.raise_for_status() - return response.json() - except Exception as exc: - raise _wrap_exception(exc) from exc + response = await _request("GET", cluster, f"{index}/_doc/{doc_id}", params=params) + + return response.json() async def update( @@ -361,19 +359,11 @@ async def update( doc: Dict[str, Any], cluster: ESCluster = ESCluster.NES, ) -> Dict[str, Any]: - elasticsearch_url, api_key = _cluster_credentials(cluster) + response = await _request( + "POST", cluster, f"{index}/_update/{doc_id}", json_body={"doc": doc} + ) - client = get_client() - try: - response = await client.post( - f"{elasticsearch_url}/{index}/_update/{doc_id}", - json={"doc": doc}, - headers=_headers(api_key), - ) - response.raise_for_status() - return response.json() - except Exception as exc: - raise _wrap_exception(exc) from exc + return response.json() async def index_doc( @@ -382,19 +372,11 @@ async def index_doc( document: Dict[str, Any], cluster: ESCluster = ESCluster.NES, ) -> Dict[str, Any]: - elasticsearch_url, api_key = _cluster_credentials(cluster) + response = await _request( + "PUT", cluster, f"{index}/_doc/{doc_id}", json_body=document + ) - client = get_client() - try: - response = await client.put( - f"{elasticsearch_url}/{index}/_doc/{doc_id}", - json=document, - headers=_headers(api_key), - ) - response.raise_for_status() - return response.json() - except Exception as exc: - raise _wrap_exception(exc) from exc + return response.json() async def count( @@ -427,23 +409,15 @@ async def count( if len(clusters) == 1: cluster = clusters.pop() - elasticsearch_url, api_key = _cluster_credentials(cluster) - if isinstance(index, list): index_str = ",".join(str(idx) for idx in index) else: index_str = str(index) payload = {"query": query} if query else {} - client = get_client() - try: - response = await client.post( - f"{elasticsearch_url}/{index_str}/_count", json=payload, headers=_headers(api_key) - ) - response.raise_for_status() - return response.json().get("count", 0) - except Exception as exc: - raise _wrap_exception(exc) from exc + response = await _request("POST", cluster, f"{index_str}/_count", json_body=payload) + + return response.json().get("count", 0) async def msearch( @@ -468,9 +442,6 @@ async def msearch( if c is not None: cluster = c - elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = _headers(api_key, content_type="application/x-ndjson") - lines = [] for idx, body in searches: if isinstance(idx, list): @@ -483,16 +454,13 @@ async def msearch( ndjson_payload = "\n".join(lines) + "\n" - client = get_client() - try: - response = await client.post( - f"{elasticsearch_url}/_msearch", - content=ndjson_payload.encode("utf-8"), - headers=_headers(api_key), - ) - response.raise_for_status() - res_json = response.json() - return res_json.get("responses", []) - except Exception as exc: - raise _wrap_exception(exc) from exc + response = await _request( + "POST", + cluster, + "_msearch", + content=ndjson_payload.encode("utf-8"), + content_type="application/x-ndjson", + ) + + return response.json().get("responses", []) -- 2.56.1 From 28726cf4c7c888572fa10ed115790944d0a83840 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 26 Jul 2026 09:43:39 +0200 Subject: [PATCH 3/5] add env value to enable logging of outgoing Elasticsearch queries --- service/src/main/inse/.env | 3 +++ service/src/main/inse/integrations/elasticsearch.py | 7 ++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/service/src/main/inse/.env b/service/src/main/inse/.env index 36f353cf..152f348d 100644 --- a/service/src/main/inse/.env +++ b/service/src/main/inse/.env @@ -12,6 +12,9 @@ ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +# Debugging: Log every outgoing Elasticsearch query (index + payload) +PRINT_ES_QUERIES=false + # Sentence Transformers Configuration SENTENCE_TRANSFORMERS_MODEL_NAME=intfloat/multilingual-e5-base diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 250786af..2f0de418 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -255,9 +255,10 @@ async def search( "At least one of 'query', 'body', 'source', 'size', 'offset', 'sort', 'aggs' must be provided" ) - logger.debug( - f"Sending search request to Elasticsearch cluster '{cluster}' for {index} with payload: {json.dumps(payload)}" - ) + if config.settings.print_es_queries: + logger.debug( + f"Sending search request to Elasticsearch cluster '{cluster}' for {index} with payload: {json.dumps(payload)}" + ) if isinstance(index, list): index_str = ",".join(str(idx) for idx in index) -- 2.56.1 From e57875d2a503c8be6b8ce547434903dfa5728a0f Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 26 Jul 2026 09:48:35 +0200 Subject: [PATCH 4/5] add logging for Elasticsearch request timings --- service/src/main/inse/.env | 2 ++ service/src/main/inse/config.py | 2 ++ service/src/main/inse/integrations/elasticsearch.py | 13 +++++++++++++ 3 files changed, 17 insertions(+) diff --git a/service/src/main/inse/.env b/service/src/main/inse/.env index 152f348d..9fedc0af 100644 --- a/service/src/main/inse/.env +++ b/service/src/main/inse/.env @@ -14,6 +14,8 @@ ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FM # Debugging: Log every outgoing Elasticsearch query (index + payload) PRINT_ES_QUERIES=false +# Debugging: Log the duration of every Elasticsearch request +PRINT_ES_TIMINGS=false # Sentence Transformers Configuration SENTENCE_TRANSFORMERS_MODEL_NAME=intfloat/multilingual-e5-base diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index aebc16c6..6075aa8b 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -69,6 +69,8 @@ class Settings(BaseSettings): elasticsearch_api_key: Optional[str] = None elasticsearch_inse_url: Optional[str] = None elasticsearch_inse_api_key: Optional[str] = None + print_es_queries: bool = False + print_es_timings: bool = False model_config = SettingsConfigDict(env_file=str(ENV_FILE)) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 2f0de418..05a81575 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -1,5 +1,6 @@ import json import logging +import time from typing import Any, Dict, AsyncIterator, List, Optional, Tuple import httpx @@ -157,6 +158,7 @@ async def _request( elasticsearch_url, api_key = _cluster_credentials(cluster) client = get_client() + start = time.perf_counter() try: response = await client.request( method, @@ -169,8 +171,19 @@ async def _request( response.raise_for_status() + if config.settings.print_es_timings: + elapsed_ms = (time.perf_counter() - start) * 1000 + logger.debug( + f"Elasticsearch request {method} {path} on cluster '{cluster}' took {elapsed_ms:.1f} ms" + ) + return response except Exception as exc: + if config.settings.print_es_timings: + elapsed_ms = (time.perf_counter() - start) * 1000 + logger.debug( + f"Elasticsearch request {method} {path} on cluster '{cluster}' failed after {elapsed_ms:.1f} ms" + ) raise _wrap_exception(exc) from exc -- 2.56.1 From 448922d907cd580ca35bc56f88d143d8dda031db Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 26 Jul 2026 12:58:38 +0200 Subject: [PATCH 5/5] enable logging of Elasticsearch request timings --- service/src/main/inse/.env | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service/src/main/inse/.env b/service/src/main/inse/.env index 9fedc0af..a49ebae6 100644 --- a/service/src/main/inse/.env +++ b/service/src/main/inse/.env @@ -15,7 +15,7 @@ ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FM # Debugging: Log every outgoing Elasticsearch query (index + payload) PRINT_ES_QUERIES=false # Debugging: Log the duration of every Elasticsearch request -PRINT_ES_TIMINGS=false +PRINT_ES_TIMINGS=true # Sentence Transformers Configuration SENTENCE_TRANSFORMERS_MODEL_NAME=intfloat/multilingual-e5-base -- 2.56.1