refactor/es_integration #246

Merged
tischer merged 5 commits from refactor/es_integration into dev 2026-07-26 13:09:48 +02:00
3 changed files with 104 additions and 120 deletions
+5
View File
@@ -12,6 +12,11 @@ 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
# Debugging: Log the duration of every Elasticsearch request
PRINT_ES_TIMINGS=true
# Sentence Transformers Configuration
SENTENCE_TRANSFORMERS_MODEL_NAME=intfloat/multilingual-e5-base
+2
View File
@@ -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))
@@ -1,5 +1,6 @@
import json
import logging
import time
from typing import Any, Dict, AsyncIterator, List, Optional, Tuple
import httpx
@@ -110,6 +111,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):
@@ -125,6 +130,63 @@ 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()
start = time.perf_counter()
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()
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
async def search(
index: ESIndex | List[ESIndex] | str | List[str],
query: Optional[Dict] = None,
@@ -175,10 +237,6 @@ async def search(
elif len(clusters) == 1:
cluster = clusters.pop()
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:
@@ -210,61 +268,34 @@ 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)}"
)
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)
else:
index_str = str(index)
try:
response = await client.post(
f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=headers
)
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)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
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,
)
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)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
client = get_client()
try:
response = await client.request(
"DELETE",
f"{elasticsearch_url}/_pit",
json={"id": pit_id},
headers=headers,
)
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,13 +311,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)
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
try:
client = get_client()
while True:
payload: Dict[str, Any] = {
"size": page_size,
@@ -299,14 +326,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
)
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", [])
@@ -338,23 +358,13 @@ async def get(
if isinstance(index, ESIndex):
cluster = _index_to_cluster(index) or cluster
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
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
)
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(
@@ -363,20 +373,11 @@ async def update(
doc: Dict[str, Any],
cluster: ESCluster = ESCluster.NES,
) -> Dict[str, Any]:
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
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,
)
response.raise_for_status()
return response.json()
except Exception as exc:
raise _wrap_exception(exc) from exc
return response.json()
async def index_doc(
@@ -385,20 +386,11 @@ async def index_doc(
document: Dict[str, Any],
cluster: ESCluster = ESCluster.NES,
) -> Dict[str, Any]:
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
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,
)
response.raise_for_status()
return response.json()
except Exception as exc:
raise _wrap_exception(exc) from exc
return response.json()
async def count(
@@ -431,24 +423,15 @@ async def count(
if len(clusters) == 1:
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)
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
)
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(
@@ -473,9 +456,6 @@ async def msearch(
if c is not None:
cluster = c
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/x-ndjson"}
lines = []
for idx, body in searches:
if isinstance(idx, list):
@@ -488,16 +468,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,
)
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", [])