Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
607 changes: 303 additions & 304 deletions Pipfile.lock

Large diffs are not rendered by default.

21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,27 @@ with CaptureClient() as client:
)
```

On a composite IKG, set `location` on the nodes. Each node is written to the
database of its location, and `create_proxy=True` also puts a proxy of it in the
global database. A relationship goes to the database its source and target
share, or to the global database when their locations differ. Such calls return
the GIDs per location in `BatchResults.by_location` (nodes without a location
under `LOCATION_DEFAULT`, proxies and cross-location relationships under
`LOCATION_GLOBAL`); calls without any location fill `BatchResults.results`.

```python
from indykite_sdk import CaptureClient

with CaptureClient() as client:
results = client.upsert_nodes(
[
{"external_id": "ada", "type": "Person", "location": "east", "create_proxy": True},
{"external_id": "kitt", "type": "Car", "location": "west"},
]
)
print(results.by_location) # {"east": ["gid:..."], "west": ["gid:..."], "global": ["gid:..."]}
```

### Read the graph with a knowledge query (ContX IQ)

```python
Expand Down
2 changes: 1 addition & 1 deletion examples/capture_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def main() -> None:
{"external_id": "kitt", "type": "Car", "properties": [{"type": "model", "value": "K.I.T.T."}]},
]
)
print(f"Upserted {len(results)} nodes")
print(f"Upserted {len(results.results)} nodes")

client.upsert_relationships(
[
Expand Down
6 changes: 6 additions & 0 deletions indykite_sdk/capture/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
from indykite_sdk.capture.aio import AsyncCaptureClient
from indykite_sdk.capture.client import CaptureClient
from indykite_sdk.capture.models import (
LOCATION_DEFAULT,
LOCATION_GLOBAL,
BaseProperty,
BatchResult,
BatchResults,
DeleteNodeProperties,
DeleteNodePropertyMetadata,
DeleteRelationshipProperties,
Expand All @@ -17,9 +20,12 @@
)

__all__ = [
"LOCATION_DEFAULT",
"LOCATION_GLOBAL",
"AsyncCaptureClient",
"BaseProperty",
"BatchResult",
"BatchResults",
"CaptureClient",
"DeleteNodeProperties",
"DeleteNodePropertyMetadata",
Expand Down
53 changes: 40 additions & 13 deletions indykite_sdk/capture/_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,13 @@

from indykite_sdk._core.models import IKModel
from indykite_sdk._core.ops import RequestSpec
from indykite_sdk.capture.models import MAX_BATCH_SIZE, BatchResult
from indykite_sdk.capture.models import (
LOCATION_DEFAULT,
LOCATION_GLOBAL,
MAX_BATCH_SIZE,
BatchResult,
BatchResults,
)
from indykite_sdk.errors import RequestValidationError


Expand All @@ -29,36 +35,57 @@ def coerce_items[ModelT: IKModel](
return coerced


def request_locations(items: Sequence[IKModel]) -> frozenset[str]:
"""Collect the locations named by the nodes of a batch.

A node entry carries its own location; a relationship entry is routed by
the locations of its source and target nodes.
"""
locations: set[str] = set()
for item in items:
nodes = (item.source, item.target) if hasattr(item, "source") else (item,)
locations.update(node.location for node in nodes if node.location)
return frozenset(locations)


def batch_specs[ModelT: IKModel](
path: str,
field_name: str,
items: list[ModelT],
*,
auto_chunk: bool,
extra_body: dict[str, Any] | None = None,
) -> list[tuple[int, RequestSpec]]:
) -> list[tuple[int, RequestSpec, frozenset[str]]]:
"""Split ``items`` into request specs of at most 250 items each.

Returns ``(start_index, spec)`` pairs so callers can report where a chunk
failed. Without ``auto_chunk``, more than 250 items is a client-side error.
Returns ``(start_index, spec, locations)`` triples: the start index lets
callers report where a chunk failed, and the locations of the chunk select
the shape its response is parsed in.
"""
if len(items) > MAX_BATCH_SIZE and not auto_chunk:
raise RequestValidationError(
f"The Capture API accepts at most {MAX_BATCH_SIZE} items per request, got {len(items)}. "
f"Pass auto_chunk=True to split the batch automatically."
)
specs: list[tuple[int, RequestSpec]] = []
specs: list[tuple[int, RequestSpec, frozenset[str]]] = []
for start in range(0, len(items), MAX_BATCH_SIZE):
chunk = items[start : start + MAX_BATCH_SIZE]
body: dict[str, Any] = {field_name: [item.to_wire() for item in chunk]}
if extra_body:
body.update(extra_body)
specs.append((start, RequestSpec("POST", path, json_body=body)))
specs.append((start, RequestSpec("POST", path, json_body=body), request_locations(chunk)))
return specs


def parse_batch_results(response: httpx.Response) -> list[BatchResult]:
"""Parse a ``{"results": [...]}`` batch response envelope."""
def parse_batch_results(response: httpx.Response, locations: frozenset[str]) -> BatchResults:
"""Parse a batch response in the shape the request selects.

The API answers ``{"results": [...]}`` when no node of the request has a
location, and ``{"<location>": [gid, ...]}`` otherwise. In the second shape
only the request's locations, plus the default and global keys the API can
add on its own, are read as locations.
"""
data = response.json() if response.content else {}
results = data.get("results") or [] if isinstance(data, dict) else []
return [BatchResult.model_validate(result) for result in results]
if not isinstance(data, dict):
data = {}
if not locations:
return BatchResults(results=[BatchResult.model_validate(result) for result in data.get("results") or []])
known = locations | {LOCATION_DEFAULT, LOCATION_GLOBAL}
return BatchResults(by_location={key: list(gids or []) for key, gids in data.items() if key in known})
42 changes: 17 additions & 25 deletions indykite_sdk/capture/aio.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from indykite_sdk._core.ops import RequestSpec
from indykite_sdk.capture import _ops
from indykite_sdk.capture.models import (
BatchResult,
BatchResults,
DeleteNodeProperties,
DeleteNodePropertyMetadata,
DeleteRelationshipProperties,
Expand Down Expand Up @@ -40,23 +40,23 @@ class AsyncCaptureClient(BaseAsyncClient):

async def _send_batches(
self,
specs: list[tuple[int, RequestSpec]],
specs: list[tuple[int, RequestSpec, frozenset[str]]],
*,
timeout: httpx.Timeout | float | None,
) -> list[BatchResult]:
results: list[BatchResult] = []
for start, spec in specs:
) -> BatchResults:
results = BatchResults()
for start, spec, locations in specs:
try:
response = await self._send(spec, timeout=timeout)
except IndyKiteError as exc:
if len(specs) > 1:
raise ChunkedCaptureError(
f"Chunked capture call failed at item {start} after {len(results)} successful items.",
f"Chunked capture call failed at item {start} after {start} successful items.",
completed=results,
failed_at=start,
) from exc
raise
results.extend(_ops.parse_batch_results(response))
results.merge(_ops.parse_batch_results(response, locations))
return results

async def upsert_nodes(
Expand All @@ -65,7 +65,7 @@ async def upsert_nodes(
*,
auto_chunk: bool = False,
timeout: httpx.Timeout | float | None = None,
) -> list[BatchResult]:
) -> BatchResults:
"""Create or update nodes (``POST /nodes``)."""
items = _ops.coerce_items(nodes, UpsertNode, "node")
return await self._send_batches(
Expand All @@ -78,7 +78,7 @@ async def delete_nodes(
*,
auto_chunk: bool = False,
timeout: httpx.Timeout | float | None = None,
) -> list[BatchResult]:
) -> BatchResults:
"""Delete whole nodes (``POST /nodes/delete``)."""
items = _ops.coerce_items(nodes, NodeRef, "node reference")
return await self._send_batches(
Expand All @@ -91,7 +91,7 @@ async def delete_node_properties(
*,
auto_chunk: bool = False,
timeout: httpx.Timeout | float | None = None,
) -> list[BatchResult]:
) -> BatchResults:
"""Strip named properties from nodes (``POST /nodes/properties/delete``)."""
items = _ops.coerce_items(nodes, DeleteNodeProperties, "node property delete")
return await self._send_batches(
Expand All @@ -104,7 +104,7 @@ async def delete_node_property_metadata(
*,
auto_chunk: bool = False,
timeout: httpx.Timeout | float | None = None,
) -> list[BatchResult]:
) -> BatchResults:
"""Strip metadata fields from one property per node (``POST /nodes/properties/metadata/delete``)."""
items = _ops.coerce_items(nodes, DeleteNodePropertyMetadata, "property metadata delete")
return await self._send_batches(
Expand All @@ -116,48 +116,40 @@ async def upsert_relationships(
self,
relationships: Sequence[Relationship | dict[str, Any]],
*,
use_global_db: bool = False,
auto_chunk: bool = False,
timeout: httpx.Timeout | float | None = None,
) -> list[BatchResult]:
) -> BatchResults:
"""Create or update relationships (``POST /relationships``)."""
items = _ops.coerce_items(relationships, Relationship, "relationship")
extra = {"use_global_db": True} if use_global_db else None
return await self._send_batches(
_ops.batch_specs("/relationships", "relationships", items, auto_chunk=auto_chunk, extra_body=extra),
_ops.batch_specs("/relationships", "relationships", items, auto_chunk=auto_chunk),
timeout=timeout,
)

async def delete_relationships(
self,
relationships: Sequence[Relationship | dict[str, Any]],
*,
use_global_db: bool = False,
auto_chunk: bool = False,
timeout: httpx.Timeout | float | None = None,
) -> list[BatchResult]:
) -> BatchResults:
"""Delete relationships (``POST /relationships/delete``)."""
items = _ops.coerce_items(relationships, Relationship, "relationship")
extra = {"use_global_db": True} if use_global_db else None
return await self._send_batches(
_ops.batch_specs("/relationships/delete", "relationships", items, auto_chunk=auto_chunk, extra_body=extra),
_ops.batch_specs("/relationships/delete", "relationships", items, auto_chunk=auto_chunk),
timeout=timeout,
)

async def delete_relationship_properties(
self,
relationships: Sequence[DeleteRelationshipProperties | dict[str, Any]],
*,
use_global_db: bool = False,
auto_chunk: bool = False,
timeout: httpx.Timeout | float | None = None,
) -> list[BatchResult]:
) -> BatchResults:
"""Strip named properties from relationships (``POST /relationships/properties/delete``)."""
items = _ops.coerce_items(relationships, DeleteRelationshipProperties, "relationship property delete")
extra = {"use_global_db": True} if use_global_db else None
return await self._send_batches(
_ops.batch_specs(
"/relationships/properties/delete", "relationships", items, auto_chunk=auto_chunk, extra_body=extra
),
_ops.batch_specs("/relationships/properties/delete", "relationships", items, auto_chunk=auto_chunk),
timeout=timeout,
)
Loading
Loading