Skip to content

Commit 2cbb8b9

Browse files
authored
Merge branch 'main' into patches
2 parents 9258ecb + d3bc087 commit 2cbb8b9

File tree

36 files changed

+1485
-584
lines changed

36 files changed

+1485
-584
lines changed

.github/workflows/_doc_release.yml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ jobs:
1111
- uses: actions/checkout@v4
1212
- uses: actions/setup-node@v4
1313
with:
14-
node-version: 18
1514
cache: yarn
1615
cache-dependency-path: docs/yarn.lock
1716
- uses: webfactory/ssh-agent@v0.5.0

.github/workflows/_test.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ jobs:
4343
- name: Install Python toolchains
4444
run: |
4545
source .venv/bin/activate
46-
pip install maturin pytest mypy
46+
pip install maturin mypy pytest pytest-asyncio
4747
- name: Python build
4848
run: |
4949
source .venv/bin/activate

.github/workflows/docs.yml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ jobs:
1919
- uses: actions/checkout@v4
2020
- uses: actions/setup-node@v4
2121
with:
22-
node-version: 18
2322
cache: yarn
2423
cache-dependency-path: docs/yarn.lock
2524
- name: Install dependencies

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,7 @@ It defines an index flow like this:
185185
| [Image Search with Vision API](examples/image_search) | Generates detailed captions for images using a vision model, embeds them, enables live-updating semantic search via FastAPI and served on a React frontend|
186186
| [Face Recognition](examples/face_recognition) | Recognize faces in images and build embedding index |
187187
| [Paper Metadata](examples/paper_metadata) | Index papers in PDF files, and build metadata tables for each paper |
188+
| [Custom Output Files](examples/custom_output_files) | Convert markdown files to HTML files and save them to a local directory, using *CocoIndex Custom Targets* |
188189

189190
More coming and stay tuned 👀!
190191

docs/docs/core/flow_def.mdx

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,23 +33,23 @@ It takes two arguments:
3333
* `flow_builder`: a `FlowBuilder` object to help build the flow.
3434
* `data_scope`: a `DataScope` object, representing the top-level data scope. Any data created by the flow should be added to it.
3535

36-
Alternatively, for more flexibility (e.g. you want to do this conditionally or generate dynamic name), you can explicitly call the `cocoindex.add_flow_def()` method:
36+
Alternatively, for more flexibility (e.g. you want to do this conditionally or generate dynamic name), you can explicitly call the `cocoindex.open_flow()` method:
3737

3838
```python
3939
def demo_flow_def(flow_builder: cocoindex.FlowBuilder, data_scope: cocoindex.DataScope):
4040
...
4141

4242
# Add the flow definition to the flow registry.
43-
demo_flow = cocoindex.add_flow_def("DemoFlow", demo_flow_def)
43+
demo_flow = cocoindex.open_flow("DemoFlow", demo_flow_def)
4444
```
4545

4646
In both cases, `demo_flow` will be an object with `cocoindex.Flow` class type.
4747
See [Flow Running](/docs/core/flow_methods) for more details on it.
4848

49-
Sometimes you no longer want to keep states of the flow in memory. We provide a `cocoindex.remove_flow()` method for this purpose:
49+
Sometimes you no longer want to keep states of the flow in memory. We provide a `close()` method for this purpose:
5050

5151
```python
52-
cocoindex.remove_flow(demo_flow)
52+
demo_flow.close()
5353
```
5454

5555
After it's called, `demo_flow` becomes an invalid object, and you should not call any methods of it.

docs/docs/core/flow_methods.mdx

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
---
2-
title: Run a Flow
2+
title: Operate a Flow
33
toc_max_heading_level: 4
4-
description: Run a CocoIndex Flow, including build / update data in the target and evaluate the flow without changing the target.
4+
description: Operate a CocoIndex Flow, including build / update data in the target and evaluate the flow without changing the target.
55
---
66

77
import Tabs from '@theme/Tabs';
88
import TabItem from '@theme/TabItem';
99

10-
# Run a CocoIndex Flow
10+
# Operate a CocoIndex Flow
1111

1212
After a flow is defined as discussed in [Flow Definition](/docs/core/flow_def), you can start to transform data with it.
1313

@@ -39,7 +39,7 @@ It creates a `demo_flow` object in `cocoindex.Flow` type.
3939
For a flow, its persistent backends need to be ready before it can run, including:
4040

4141
* [Internal storage](/docs/core/basics#internal-storage) for CocoIndex.
42-
* Backend entities for targets exported by the flow, e.g. a table (in relational databases), a collection (in some vector databases), etc.
42+
* Backend resources for targets exported by the flow, e.g. a table (in relational databases), a collection (in some vector databases), etc.
4343

4444
The desired state of the backends for a flow is derived based on the flow definition itself.
4545
CocoIndex supports two types of actions to manage the persistent backends automatically:
@@ -104,7 +104,7 @@ cocoindex.drop_all_flows(report_to_stdout=True)
104104

105105
After dropping the flow, the in-memory `cocoindex.Flow` instance is still valid, and you can call setup methods on it again.
106106

107-
If you want to remove the flow from the current process, you can call `cocoindex.remove_flow(demo_flow)` to do so (see [related doc](/docs/core/flow_def#entry-point)).
107+
If you want to remove the flow from the current process, you can call `demo_flow.close()` to do so (see [related doc](/docs/core/flow_def#entry-point)).
108108

109109
:::
110110

docs/docs/custom_ops/custom_functions.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
title: Custom Functions
3-
description: Build Custom Functions
3+
description: Build powerful custom functions in CocoIndex for data transformation and processing. Create standalone functions or advanced function specs with executors, including caching, GPU support, and configurable behavior for scalable data operations.
44
---
55

66
import Tabs from '@theme/Tabs';
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
---
2+
title: Custom Targets
3+
description: Learn how to create custom targets in CocoIndex to export data to any destination including databases, cloud storage, file systems, and APIs. Build target specs and connectors with setup and data methods for flexible data export operations.
4+
toc_max_heading_level: 4
5+
---
6+
7+
import Tabs from '@theme/Tabs';
8+
import TabItem from '@theme/TabItem';
9+
10+
A custom target allows you to export data to any destination you want, such as databases, cloud storage, file systems, APIs, or other external systems.
11+
12+
Custom targets are defined by two components:
13+
14+
* A **target spec** that configures the behavior and connection parameters for the target.
15+
* A **target connector** that handles the actual data export operations.
16+
17+
## Target Spec
18+
19+
The target spec defines the configuration parameters for your custom target. When you use this target in a flow (typically by calling [`export()`](/docs/core/flow_def#export)), you instantiate this target spec with specific parameter values.
20+
21+
<Tabs>
22+
<TabItem value="python" label="Python" default>
23+
24+
A target spec is defined as a class that inherits from `cocoindex.op.TargetSpec`.
25+
26+
```python
27+
class CustomTarget(cocoindex.op.TargetSpec):
28+
"""
29+
Documentation for the target.
30+
"""
31+
param1: str
32+
param2: int | None = None
33+
...
34+
```
35+
36+
Notes:
37+
* All fields of the spec must have a type serializable / deserializable by the `json` module.
38+
* All subclasses of `TargetSpec` can be instantiated similar to a dataclass, i.e. `ClassName(param1=value1, param2=value2, ...)`.
39+
40+
</TabItem>
41+
</Tabs>
42+
43+
## Target Connector
44+
45+
A target connector handles the actual data export operations for your custom target. It defines how data should be written to your target destination.
46+
47+
Target connectors implement two categories of methods: **setup methods** for managing target infrastructure (similar to DDL operations in databases), and **data methods** for handling specific data operations (similar to DML operations).
48+
49+
<Tabs>
50+
<TabItem value="python" label="Python" default>
51+
52+
A target connector is defined as a class decorated by `@cocoindex.op.target_connector(spec_cls=CustomTarget)`.
53+
54+
```python
55+
@cocoindex.op.target_connector(spec_cls=CustomTarget)
56+
class CustomTargetConnector:
57+
# Setup methods
58+
@staticmethod
59+
def get_persistent_key(spec: CustomTarget, target_name: str) -> PersistentKey:
60+
"""Required. Return a persistent key that uniquely identifies this target instance."""
61+
...
62+
63+
@staticmethod
64+
def apply_setup_change(
65+
key: PersistentKey, previous: CustomTarget | None, current: CustomTarget | None
66+
) -> None:
67+
"""Required. Apply setup changes to the target."""
68+
...
69+
70+
@staticmethod
71+
def describe(key: PersistentKey) -> str:
72+
"""Optional. Return a human-readable description of the target."""
73+
...
74+
75+
# Data methods
76+
@staticmethod
77+
def prepare(spec: CustomTarget) -> PreparedCustomTarget:
78+
"""Optional. Prepare for execution before applying mutations."""
79+
...
80+
81+
@staticmethod
82+
def mutate(
83+
*all_mutations: tuple[PreparedCustomTarget, dict[DataKeyType, DataValueType | None]],
84+
) -> None:
85+
"""Required. Apply data mutations to the target."""
86+
...
87+
```
88+
89+
</TabItem>
90+
</Tabs>
91+
92+
The following data types are involved in the method definitions above: `CustomTarget`, `PersistentKey`, `PreparedCustomTarget`, `DataKeyType`, `DataValueType`. They should be replaced with the actual types in your implementation. We will explain each of them below.
93+
94+
### Setup Methods
95+
Setup methods manage the target infrastructure - creating, configuring, and cleaning up target resources.
96+
97+
#### `get_persistent_key(spec, target_name) -> PersistentKey` (Required)
98+
99+
This method returns a unique identifier for the target instance. This key is used by CocoIndex to keep track of target state and drive target spec changes.
100+
101+
The key should be stable across different runs. If a previously existing key no longer exists, CocoIndex will assume the target is gone, and will drop it by calling `apply_setup_change` with `current` set to `None`.
102+
103+
The return type of this method should be serializable by the `json` module. It will be passed to other setup methods.
104+
105+
#### `apply_setup_change(key, previous, current) -> None` (Required)
106+
107+
This method is called when the target configuration changes. It receives:
108+
- `key`: The persistent key for this target
109+
- `previous`: The previous target spec (or `None` if this is a new target)
110+
- `current`: The current target spec (or `None` if the target is being removed)
111+
112+
This method should be implemented to:
113+
- Create resources when a target is first added (`previous` is `None`)
114+
- Update configuration when a target spec changes
115+
- Clean up resources when a target is removed (`current` is `None`)
116+
117+
#### `describe(key) -> str` (Optional)
118+
119+
Returns a human-readable description of the target for logging and debugging purposes.
120+
121+
122+
### Data Methods
123+
124+
Data methods handle the actual data operations - inserting, updating, and deleting records in the target.
125+
126+
#### `mutate(*all_mutations) -> None` (Required)
127+
128+
This method applies data changes to the target. It receives multiple mutation batches, where each batch is a tuple containing:
129+
130+
- The target spec (`PreparedCustomTarget`, or `CustomTarget` if `prepare` is not provided).
131+
132+
- A dictionary of mutations (`dict[DataKeyType, DataValueType | None]`).
133+
Each entry represents a mutation for a single row. When the value is `None`, it represents a deletion for the row, otherwise it's an upsert.
134+
135+
It represented in the same way as [*KTable*](/docs/core/data_types#ktable), except the value can be `None`.
136+
In particular:
137+
138+
- Since both `DataKeyType` and `DataValueType` can have multiple columns, they're [*Struct*](/docs/core/data_types#struct-types).
139+
- `DataKeyType` can be represented by a frozen dataclass (i.e. `@dataclass(frozen=True)`) or a `NamedTuple`, as it needs to be immutable.
140+
- `DataValueType` can be represented by a `dataclass`, a `NamedTuple` or a `dict[str, Any]`.
141+
142+
- For simplicity, when there're a single primary key column with basic type, we allow using type of this column (e.g. `str`, `int` etc.) as the key type, and a wrapper *Struct* type can be omitted.
143+
You can still use a `@dataclass(frozen=True)` or a `NamedTuple` to represent the key for this case though, if you want to handle both cases consistently.
144+
145+
#### `prepare(spec) -> PreparedCustomTarget` (Optional)
146+
147+
Prepares for execution by performing common operations before applying mutations. The returned value will be passed as the first element of tuples in the `mutate` method instead of the original spec.
148+
149+
```python
150+
@staticmethod
151+
def prepare(spec: CustomTarget) -> PreparedCustomTarget:
152+
"""
153+
Prepare for execution. Called once before mutations.
154+
"""
155+
# Initialize connections, validate configuration, etc.
156+
return PreparedCustomTarget(...)
157+
```
158+
159+
If not provided, the original spec will be passed directly to `mutate`.
160+
161+
## Best Practices
162+
163+
### Idempotency of Methods with Side Effects
164+
165+
`apply_setup_change()` and `mutate()` are the two methods that are expected to produce side effects.
166+
We expect them to be idempotent, i.e. when calling them with the same arguments multiple times, the effect should remain the same.
167+
168+
For example,
169+
- For `apply_setup_change()`, if the target is a directory, it should be a no-op if we try to create it (`previous` is `None`) when the directory already exists, and also a no-op if we try to delete it (`current` is `None`) when the directory does not exist.
170+
- For `mutate()`, if a mutation is a deletion, it should be a no-op if the row does not exist.
171+
172+
This is to make sure when the system if left in an intermediate state, e.g. interrupted in the middle between a change is made and CocoIndex notes down the change is completed, the targets can still be gracefully rolled forward to the desired states after the system is resumed.
173+
174+
## Examples
175+
176+
The cocoindex repository contains the following examples of custom targets:
177+
178+
* In the [custom_output_files](https://github.com/cocoindex-io/cocoindex/blob/main/examples/custom_output_files/main.py) example, `LocalFileTarget` exports data to local HTML files.

0 commit comments

Comments
 (0)