multids 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
multids/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """multids package"""
2
+
3
+ __all__ = ["interfaces", "connectors", "ai"]
4
+ __version__ = "0.1.0"
5
+
6
+ from . import interfaces # re-exported for convenience
multids/ai.py ADDED
@@ -0,0 +1,18 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Dict, Protocol
4
+
5
+
6
+ class AIClientInterface(Protocol):
7
+ async def generate(self, prompt: str, **kwargs: Any) -> Dict[str, Any]:
8
+ """Generate a response for the given prompt."""
9
+
10
+
11
+ class OpenAIClient:
12
+ def __init__(self, client):
13
+ # client: an `openai` async-compatible client or wrapper
14
+ self._client = client
15
+
16
+ async def generate(self, prompt: str, **kwargs: Any) -> Dict[str, Any]:
17
+ # Implementation will depend on the chosen AI provider.
18
+ return await self._client.create(prompt=prompt, **kwargs)
@@ -0,0 +1,24 @@
1
+ """
2
+ Connector subpackage exports.
3
+
4
+ Avoid importing heavy optional dependencies at package import time. Import
5
+ individual connector modules directly (e.g. `from multids.connectors.opensearch import OpenSearchConnector`) or
6
+ access them via importlib when needed.
7
+ """
8
+
9
+ from .athena import AthenaConnector
10
+ from .local import LocalConnector
11
+ from .mssql import MSSQLConnector
12
+ from .opensearch import OpenSearchConnector
13
+ from .s3 import S3Connector
14
+ from .sql import MySQLConnector, SQLConnectorBase
15
+
16
+ __all__ = [
17
+ "S3Connector",
18
+ "LocalConnector",
19
+ "SQLConnectorBase",
20
+ "MySQLConnector",
21
+ "OpenSearchConnector",
22
+ "AthenaConnector",
23
+ "MSSQLConnector",
24
+ ]
@@ -0,0 +1,199 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from contextlib import AsyncExitStack
5
+ from typing import Any, AsyncIterator, Dict, List, Optional
6
+
7
+ from ..interfaces import Connector
8
+
9
+
10
+ class AthenaError(Exception):
11
+ pass
12
+
13
+
14
+ class AthenaConnector(Connector):
15
+ """
16
+ Async helper for running Athena queries and streaming results.
17
+
18
+ Minimal, pragmatic implementation that uses `aioboto3` when available.
19
+ Features:
20
+ - start_query: start an Athena query and return execution id
21
+ - wait_query: poll for completion with timeout
22
+ - get_results: paginate `get_query_results` and yield rows as dicts
23
+ - query_stream: convenience to run a SQL and stream results
24
+
25
+ Notes:
26
+ - Reuse the connector instance to reuse the underlying boto3 session/client.
27
+ - Always implementation `close()` when done (or usage as context manager if we added one,
28
+ but explicit close is fine).
29
+ """
30
+
31
+ def __init__(
32
+ self,
33
+ region_name: Optional[str] = None,
34
+ workgroup: Optional[str] = None,
35
+ poll_interval: float = 1.0,
36
+ max_wait: float = 300.0,
37
+ ):
38
+ self.region_name = region_name
39
+ self.workgroup = workgroup
40
+ self.poll_interval = poll_interval
41
+ self.max_wait = max_wait
42
+ self._session: Optional[Any] = None
43
+ self._client: Optional[Any] = None
44
+ self._exit_stack: Optional[Any] = None
45
+
46
+ try:
47
+ import aioboto3
48
+
49
+ self._aioboto3 = aioboto3
50
+ except Exception as e:
51
+ self._aioboto3 = None
52
+ raise AthenaError("aioboto3 is required for AthenaConnector") from e
53
+
54
+ async def _get_client(self):
55
+ """Get or create the cached aioboto3 client."""
56
+ if self._client is not None:
57
+ return self._client
58
+
59
+ if self._aioboto3 is None:
60
+ raise AthenaError("aioboto3 is required for AthenaConnector")
61
+
62
+ self._session = self._aioboto3.Session()
63
+ self._exit_stack = AsyncExitStack() # type: ignore
64
+ # Enter the client context and keep it open until close() is called
65
+ client_cm = self._session.client("athena", region_name=self.region_name)
66
+ self._client = await self._exit_stack.enter_async_context(client_cm)
67
+ return self._client
68
+
69
+ async def close(self) -> None:
70
+ """Close the underlying client and session."""
71
+ if self._exit_stack:
72
+ await self._exit_stack.aclose()
73
+ self._exit_stack = None
74
+ self._client = None
75
+ self._session = None
76
+
77
+ async def ping(self) -> bool:
78
+ """Check connectivity by listing workgroups (lightweight)."""
79
+ try:
80
+ client = await self._get_client()
81
+ await client.list_work_groups(MaxResults=1)
82
+ return True
83
+ except Exception:
84
+ return False
85
+
86
+ async def start_query(
87
+ self,
88
+ sql: str,
89
+ database: Optional[str] = None,
90
+ output_location: Optional[str] = None,
91
+ encryption_configuration: Optional[Dict] = None,
92
+ ) -> str:
93
+ """Start an Athena query execution and return the execution id."""
94
+ client = await self._get_client()
95
+ params: Dict[str, Any] = {"QueryString": sql}
96
+ if database:
97
+ params["QueryExecutionContext"] = {"Database": database}
98
+ cfg = {}
99
+ if output_location:
100
+ cfg["OutputLocation"] = output_location
101
+ if encryption_configuration:
102
+ cfg["EncryptionConfiguration"] = encryption_configuration
103
+ if cfg:
104
+ params["ResultConfiguration"] = cfg
105
+ if self.workgroup:
106
+ params["WorkGroup"] = self.workgroup
107
+
108
+ resp = await client.start_query_execution(**params)
109
+ return resp["QueryExecutionId"]
110
+
111
+ async def wait_query(self, query_execution_id: str, timeout: Optional[float] = None) -> Dict[str, Any]:
112
+ """Poll Athena until the query reaches a terminal state."""
113
+ timeout = timeout if timeout is not None else self.max_wait
114
+ client = await self._get_client()
115
+ elapsed = 0.0
116
+ while True:
117
+ resp = await client.get_query_execution(QueryExecutionId=query_execution_id)
118
+ state = resp.get("QueryExecution", {}).get("Status", {}).get("State")
119
+ if state in ("SUCCEEDED", "FAILED", "CANCELLED"):
120
+ return resp
121
+ if elapsed >= timeout:
122
+ # attempt to stop the query
123
+ try:
124
+ await client.stop_query_execution(QueryExecutionId=query_execution_id)
125
+ except Exception:
126
+ pass
127
+ raise asyncio.TimeoutError(f"Query {query_execution_id} timed out after {timeout}s")
128
+ await asyncio.sleep(self.poll_interval)
129
+ elapsed += self.poll_interval
130
+
131
+ async def get_results(self, query_execution_id: str) -> AsyncIterator[Dict[str, Any]]:
132
+ """Yield rows from `get_query_results` as dictionaries keyed by column name."""
133
+ client = await self._get_client()
134
+ paginator_token = None
135
+ columns: List[str] = []
136
+ while True:
137
+ if paginator_token:
138
+ resp = await client.get_query_results(QueryExecutionId=query_execution_id, NextToken=paginator_token)
139
+ else:
140
+ resp = await client.get_query_results(QueryExecutionId=query_execution_id)
141
+
142
+ result_set = resp.get("ResultSet", {})
143
+ metadata = result_set.get("ResultSetMetadata", {})
144
+ col_info = metadata.get("ColumnInfo", [])
145
+ if not columns and col_info:
146
+ columns = [cinfo.get("Name") for cinfo in col_info]
147
+
148
+ rows = result_set.get("Rows", [])
149
+ # skip header row if present
150
+ first_row_data = rows[0].get("Data", []) if rows else []
151
+ header_detected = (
152
+ bool(columns)
153
+ and bool(first_row_data)
154
+ and all("VarCharValue" in cell for cell in first_row_data)
155
+ and first_row_data[0].get("VarCharValue") == columns[0]
156
+ )
157
+ start = 1 if header_detected else 0
158
+ for r in rows[start:]:
159
+ data = r.get("Data", [])
160
+ values = [d.get("VarCharValue") for d in data]
161
+ if columns:
162
+ yield dict(zip(columns, values))
163
+ else:
164
+ yield {str(i): v for i, v in enumerate(values)}
165
+
166
+ paginator_token = resp.get("NextToken")
167
+ if not paginator_token:
168
+ break
169
+
170
+ async def query_stream(self, sql: str, database: Optional[str] = None) -> AsyncIterator[Dict[str, Any]]:
171
+ """Convenience: run SQL and stream results."""
172
+ qid = await self.start_query(sql, database=database)
173
+ exec_resp = await self.wait_query(qid)
174
+ state = exec_resp.get("QueryExecution", {}).get("Status", {}).get("State")
175
+ if state != "SUCCEEDED":
176
+ reason = exec_resp.get("QueryExecution", {}).get("Status", {}).get("StateChangeReason")
177
+ raise AthenaError(f"Query failed: {reason}")
178
+ async for row in self._aiter_results(qid):
179
+ yield row
180
+
181
+ async def _aiter_results(self, qid: str) -> AsyncIterator[Dict[str, Any]]:
182
+ async for r in self.get_results(qid):
183
+ yield r
184
+
185
+ async def fetch_all(self, sql: str, database: Optional[str] = None) -> List[Dict[str, Any]]:
186
+ rows = []
187
+ async for r in self.query_stream(sql, database=database):
188
+ rows.append(r)
189
+ return rows
190
+
191
+ async def to_pandas(self, sql: str, database: Optional[str] = None):
192
+ try:
193
+ import pandas as pd # type: ignore
194
+
195
+ except Exception as e: # pragma: no cover - optional
196
+ raise AthenaError("pandas is required for to_pandas()") from e
197
+
198
+ rows = await self.fetch_all(sql, database=database)
199
+ return pd.DataFrame(rows)
@@ -0,0 +1,42 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from typing import Any, AsyncIterator
5
+
6
+ import aiofiles
7
+
8
+ from ..interfaces import Connector, Readable, Writable
9
+
10
+
11
+ class LocalConnector(Connector, Readable, Writable):
12
+ async def read(self, path: str) -> AsyncIterator[bytes]:
13
+ async with aiofiles.open(path, "rb") as f:
14
+ while True:
15
+ chunk = await f.read(64 * 1024)
16
+ if not chunk:
17
+ break
18
+ yield chunk
19
+
20
+ async def write(self, stream: AsyncIterator[bytes], path: str) -> None:
21
+ async with aiofiles.open(path, "wb") as f:
22
+ async for chunk in stream:
23
+ await f.write(chunk)
24
+
25
+ async def read_json(self, path: str) -> Any:
26
+ """Read a JSON file and return the parsed object."""
27
+ async with aiofiles.open(path, "r", encoding="utf-8") as f:
28
+ content = await f.read()
29
+ return json.loads(content)
30
+
31
+ async def write_json(self, data: Any, path: str, indent: int = 2) -> None:
32
+ """Write an object as JSON to a file."""
33
+ async with aiofiles.open(path, "w", encoding="utf-8") as f:
34
+ content = json.dumps(data, indent=indent, ensure_ascii=False)
35
+ await f.write(content)
36
+
37
+ async def close(self) -> None:
38
+ return
39
+
40
+ async def ping(self) -> bool:
41
+ """Check if the filesystem is accessible (always True)."""
42
+ return True
@@ -0,0 +1,132 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from typing import Any, AsyncIterator, Dict, List, Optional, Sequence
5
+
6
+ from ..interfaces import Connector
7
+
8
+
9
+ class MSSQLConnector(Connector):
10
+ """
11
+ Async SQL Server connector using aioodbc.
12
+
13
+ Notes:
14
+ - Requires an ODBC driver for SQL Server on the host (e.g. Microsoft ODBC Driver for SQL Server).
15
+ - Install `aioodbc` as an extra (e.g. `pip install multids[sqlserver]`).
16
+ """
17
+
18
+ def __init__(
19
+ self,
20
+ dsn: Optional[str] = None,
21
+ user: Optional[str] = None,
22
+ password: Optional[str] = None,
23
+ host: Optional[str] = None,
24
+ port: Optional[int] = None,
25
+ database: Optional[str] = None,
26
+ loop: Optional[asyncio.AbstractEventLoop] = None,
27
+ ):
28
+ self._dsn = dsn
29
+ self._user = user
30
+ self._password = password
31
+ self._host = host
32
+ self._port = port
33
+ self._database = database
34
+ self._loop = loop
35
+ self._pool = None
36
+
37
+ # lazy import
38
+ try:
39
+ import aioodbc as _aioodbc
40
+
41
+ self._aioodbc = _aioodbc
42
+ except Exception:
43
+ self._aioodbc = None
44
+
45
+ async def connect_pool(self, minsize: int = 1, maxsize: int = 10) -> None:
46
+ if self._aioodbc is None:
47
+ raise RuntimeError("aioodbc is not installed; install aioodbc to use MSSQLConnector")
48
+
49
+ conn_str = self._dsn
50
+ if conn_str is None:
51
+ # build a simple DSN if not provided
52
+ parts = []
53
+ if self._host:
54
+ parts.append(f"Server={self._host}")
55
+ if self._port:
56
+ parts.append(f"Port={self._port}")
57
+ if self._database:
58
+ parts.append(f"Database={self._database}")
59
+ if self._user:
60
+ parts.append(f"UID={self._user}")
61
+ if self._password:
62
+ parts.append(f"PWD={self._password}")
63
+ conn_str = ";".join(parts)
64
+
65
+ self._pool = await self._aioodbc.create_pool(dsn=conn_str, minsize=minsize, maxsize=maxsize, loop=self._loop)
66
+
67
+ async def close(self) -> None:
68
+ if self._pool is not None:
69
+ self._pool.close()
70
+ await self._pool.wait_closed()
71
+
72
+ async def ping(self) -> bool:
73
+ """Check connection by running a simple query."""
74
+ try:
75
+ if self._pool is None:
76
+ await self.connect_pool()
77
+ async with self._pool.acquire() as conn:
78
+ async with conn.cursor() as cur:
79
+ await cur.execute("SELECT 1")
80
+ return True
81
+ except Exception:
82
+ return False
83
+
84
+ async def execute(self, sql: str, params: Optional[Sequence[Any]] = None) -> None:
85
+ if self._pool is None:
86
+ await self.connect_pool()
87
+ async with self._pool.acquire() as conn:
88
+ async with conn.cursor() as cur:
89
+ await cur.execute(sql, params or [])
90
+ # do not fetch results here
91
+
92
+ async def fetch_rows(self, sql: str, params: Optional[Sequence[Any]] = None) -> List[Dict[str, Any]]:
93
+ if self._pool is None:
94
+ await self.connect_pool()
95
+ async with self._pool.acquire() as conn:
96
+ async with conn.cursor() as cur:
97
+ await cur.execute(sql, params or [])
98
+ cols = [c[0] for c in cur.description]
99
+ rows = []
100
+ async for r in cur:
101
+ rows.append({k: v for k, v in zip(cols, r)})
102
+ return rows
103
+
104
+ async def fetch_iter(self, sql: str, params: Optional[Sequence[Any]] = None) -> AsyncIterator[Dict[str, Any]]:
105
+ if self._pool is None:
106
+ await self.connect_pool()
107
+ async with self._pool.acquire() as conn:
108
+ async with conn.cursor() as cur:
109
+ await cur.execute(sql, params or [])
110
+ cols = [c[0] for c in cur.description]
111
+ async for r in cur:
112
+ yield {k: v for k, v in zip(cols, r)}
113
+
114
+ async def bulk_insert(
115
+ self, table: str, columns: Sequence[str], rows: Sequence[Sequence[Any]], batch_size: int = 1000
116
+ ) -> None:
117
+ """
118
+ Bulk insert rows into a table using executemany in batches.
119
+
120
+ Note: For very large bulk loads consider using bcp / BULK INSERT or SSIS outside of Python.
121
+ """
122
+ if self._pool is None:
123
+ await self.connect_pool()
124
+ placeholders = ",".join(["?" for _ in columns])
125
+ cols = ",".join(columns)
126
+ sql = f"INSERT INTO {table} ({cols}) VALUES ({placeholders})"
127
+
128
+ async with self._pool.acquire() as conn:
129
+ async with conn.cursor() as cur:
130
+ for i in range(0, len(rows), batch_size):
131
+ batch = rows[i : i + batch_size]
132
+ await cur.executemany(sql, batch)
@@ -0,0 +1,270 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import json
5
+ from typing import Any, AsyncIterator, Dict, Iterable, List, Optional, cast
6
+
7
+ from ..interfaces import Connector
8
+
9
+
10
+ class OpenSearchConnector(Connector):
11
+ """
12
+ Async OpenSearch connector using httpx.
13
+
14
+ Features:
15
+ - `index_doc` to index a single document
16
+ - `bulk_index` to index many docs (sync or async iterable) using the bulk API
17
+ - `search` and `scroll` helpers for paging large result sets
18
+ - `ping` health check and `close`
19
+
20
+ Authentication: supports API Key via `api_key` or HTTP Basic auth using `basic_auth`.
21
+ """
22
+
23
+ def __init__(
24
+ self,
25
+ base_url: str,
26
+ api_key: Optional[str] = None,
27
+ basic_auth: Optional[tuple[str, str]] = None,
28
+ timeout: float = 30.0,
29
+ max_retries: int = 3,
30
+ backoff_factor: float = 0.5,
31
+ ):
32
+ self._base = base_url.rstrip("/")
33
+ # Lazy import httpx to avoid importing during test collection in constrained envs.
34
+ try:
35
+ import httpx as _httpx
36
+
37
+ self._httpx = _httpx
38
+ self._client = _httpx.AsyncClient(base_url=self._base, timeout=timeout)
39
+ except Exception:
40
+ self._httpx = None
41
+ self._client = None
42
+ self._api_key = api_key
43
+ self._basic_auth = basic_auth
44
+ self._max_retries = max_retries
45
+ self._backoff_factor = backoff_factor
46
+
47
+ def _auth_headers(self) -> Dict[str, str]:
48
+ headers: Dict[str, str] = {}
49
+ if self._api_key:
50
+ headers["Authorization"] = f"ApiKey {self._api_key}"
51
+ return headers
52
+
53
+ def _auth_kwargs(self) -> Dict[str, Any]:
54
+ kwargs: Dict[str, Any] = {}
55
+ if self._basic_auth is not None:
56
+ kwargs["auth"] = self._basic_auth
57
+ return kwargs
58
+
59
+ async def _request(self, method: str, path: str, **kwargs):
60
+ """
61
+ Internal request with simple retry/backoff for transient errors.
62
+
63
+ Retries on `httpx.RequestError` and 5xx responses.
64
+ """
65
+ attempt = 0
66
+ while True:
67
+ try:
68
+ if self._client is None:
69
+ raise RuntimeError("httpx not available in this environment")
70
+ resp = await self._client.request(method, path, **kwargs)
71
+ except Exception:
72
+ attempt += 1
73
+ if attempt > self._max_retries:
74
+ raise
75
+ backoff = self._backoff_factor * (2 ** (attempt - 1))
76
+ await asyncio.sleep(backoff)
77
+ continue
78
+
79
+ # if server error, retry
80
+ if 500 <= resp.status_code < 600:
81
+ attempt += 1
82
+ if attempt > self._max_retries:
83
+ resp.raise_for_status()
84
+ backoff = self._backoff_factor * (2 ** (attempt - 1))
85
+ await asyncio.sleep(backoff)
86
+ continue
87
+
88
+ return resp
89
+
90
+ @staticmethod
91
+ def build_bulk_ndjson(
92
+ docs: Iterable[Dict[str, Any]] | AsyncIterator[Dict[str, Any]],
93
+ index: str,
94
+ id_field: Optional[str] = None,
95
+ routing_field: Optional[str] = None,
96
+ chunk_size: int = 500,
97
+ ) -> AsyncIterator[str]:
98
+ """
99
+ Build NDJSON chunks for the bulk API from docs.
100
+
101
+ Accepts sync iterable or async iterator. Yields NDJSON chunk strings.
102
+ """
103
+
104
+ async def _async_from_sync(sync_iter: Iterable[Dict[str, Any]]):
105
+ for d in sync_iter:
106
+ yield d
107
+
108
+ async def _gen(async_iter: AsyncIterator[Dict[str, Any]]):
109
+ out: List[str] = []
110
+ cnt = 0
111
+ async for doc in async_iter:
112
+ action: Dict[str, Any] = {"index": {"_index": index}}
113
+ if id_field and id_field in doc:
114
+ action["index"]["_id"] = doc[id_field]
115
+ if routing_field and routing_field in doc:
116
+ action["index"]["routing"] = doc[routing_field]
117
+
118
+ out.append(json.dumps(action, ensure_ascii=False))
119
+ out.append(json.dumps(doc, ensure_ascii=False))
120
+ cnt += 1
121
+ if cnt >= chunk_size:
122
+ yield "\n".join(out) + "\n"
123
+ out = []
124
+ cnt = 0
125
+ if out:
126
+ yield "\n".join(out) + "\n"
127
+
128
+ # normalize
129
+ if hasattr(docs, "__aiter__"):
130
+ return _gen(cast(AsyncIterator[Dict[str, Any]], docs))
131
+ else:
132
+ return _gen(_async_from_sync(cast(Iterable[Dict[str, Any]], docs)))
133
+
134
+ async def ping(self) -> bool:
135
+ try:
136
+ r = await self._client.get("/")
137
+ return r.status_code == 200
138
+ except Exception:
139
+ return False
140
+
141
+ async def index_doc(self, index: str, doc: Dict[str, Any], id: Optional[str] = None) -> Dict[str, Any]:
142
+ """Index a single document. If `id` is provided, uses PUT to set the document id."""
143
+ headers = self._auth_headers()
144
+ # Use explicit json dumps with ensure_ascii=False for unicode support
145
+ headers.setdefault("Content-Type", "application/json")
146
+ body = json.dumps(doc, ensure_ascii=False)
147
+
148
+ if id is None:
149
+ r = await self._client.post(f"/{index}/_doc", content=body, headers=headers, **self._auth_kwargs())
150
+ else:
151
+ r = await self._client.put(f"/{index}/_doc/{id}", content=body, headers=headers, **self._auth_kwargs())
152
+ r.raise_for_status()
153
+ return r.json()
154
+
155
+ async def bulk_index(
156
+ self,
157
+ index: str,
158
+ docs: Iterable[Dict[str, Any]] | AsyncIterator[Dict[str, Any]],
159
+ chunk_size: int = 500,
160
+ refresh: bool = False,
161
+ ) -> List[Dict[str, Any]]:
162
+ """
163
+ Bulk index documents using the `_bulk` API.
164
+
165
+ Accepts either a synchronous iterable or an async iterator of documents.
166
+ Returns list of responses from each bulk request.
167
+ """
168
+ headers = self._auth_headers()
169
+ headers.setdefault("Content-Type", "application/x-ndjson")
170
+
171
+ async def _iter_ndjson(async_iter: AsyncIterator[Dict[str, Any]]):
172
+ chunk = []
173
+ async for d in async_iter:
174
+ action = {"index": {"_index": index}}
175
+ chunk.append(json.dumps(action, ensure_ascii=False))
176
+ chunk.append(json.dumps(d, ensure_ascii=False))
177
+ if len(chunk) >= chunk_size * 2:
178
+ yield "\n".join(chunk) + "\n"
179
+ chunk = []
180
+ if chunk:
181
+ yield "\n".join(chunk) + "\n"
182
+
183
+ async def _async_from_sync_iterable(sync_iterable: Iterable[Dict[str, Any]]):
184
+ for d in sync_iterable:
185
+ yield d
186
+
187
+ results: List[Dict[str, Any]] = []
188
+
189
+ # Normalize to async iterator
190
+ async_iter: AsyncIterator[Dict[str, Any]]
191
+ if hasattr(docs, "__aiter__"):
192
+ async_iter = cast(AsyncIterator[Dict[str, Any]], docs)
193
+ else:
194
+ async_iter = _async_from_sync_iterable(cast(Iterable[Dict[str, Any]], docs))
195
+
196
+ # stream NDJSON chunks and POST to _bulk
197
+ # use build_bulk_ndjson to support metadata fields
198
+ async for ndchunk in self.build_bulk_ndjson(
199
+ async_iter, index, id_field=None, routing_field=None, chunk_size=chunk_size
200
+ ):
201
+ r = await self._request(
202
+ "POST",
203
+ f"/_bulk?refresh={str(refresh).lower()}",
204
+ content=ndchunk,
205
+ headers=headers,
206
+ **self._auth_kwargs(),
207
+ )
208
+ r.raise_for_status()
209
+ results.append(r.json())
210
+
211
+ return results
212
+
213
+ async def search(self, index: str, query: Dict[str, Any], size: int = 10, from_: int = 0) -> Dict[str, Any]:
214
+ body = dict(query)
215
+ body.setdefault("size", size)
216
+ body.setdefault("from", from_)
217
+ headers = self._auth_headers()
218
+ r = await self._client.post(f"/{index}/_search", json=body, headers=headers, **self._auth_kwargs())
219
+ r.raise_for_status()
220
+ return r.json()
221
+
222
+ async def scroll(self, index: str, query: Dict[str, Any], scroll: str = "1m") -> AsyncIterator[Dict[str, Any]]:
223
+ """Scroll over search results. Yields individual hits (dicts)."""
224
+ headers = self._auth_headers()
225
+ body = dict(query)
226
+ body.setdefault("size", 1000)
227
+ r = await self._client.post(
228
+ f"/{index}/_search?scroll={scroll}", json=body, headers=headers, **self._auth_kwargs()
229
+ )
230
+ r.raise_for_status()
231
+ data = r.json()
232
+ scroll_id = data.get("_scroll_id")
233
+ hits = data.get("hits", {}).get("hits", [])
234
+ for h in hits:
235
+ yield h
236
+
237
+ try:
238
+ while True:
239
+ if not scroll_id:
240
+ break
241
+ r = await self._client.post(
242
+ "/_search/scroll",
243
+ json={"scroll": scroll, "scroll_id": scroll_id},
244
+ headers=headers,
245
+ **self._auth_kwargs(),
246
+ )
247
+ r.raise_for_status()
248
+ data = r.json()
249
+ scroll_id = data.get("_scroll_id")
250
+ hits = data.get("hits", {}).get("hits", [])
251
+ if not hits:
252
+ break
253
+ for h in hits:
254
+ yield h
255
+ finally:
256
+ if scroll_id:
257
+ # best-effort clear scroll
258
+ try:
259
+ await self._client.request(
260
+ "DELETE",
261
+ "/_search/scroll",
262
+ json={"scroll_id": [scroll_id]},
263
+ headers=headers,
264
+ **self._auth_kwargs(),
265
+ )
266
+ except Exception:
267
+ pass
268
+
269
+ async def close(self) -> None:
270
+ await self._client.aclose()