Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

refactor(examples): csv_to_iggy and the image search examples declare their target states per item (#2889)

LJ πŸ₯₯🌴41eee64f5967
diff --git a/examples/rust/csv_to_iggy/Cargo.lock b/examples/rust/csv_to_iggy/Cargo.lock
index 8b7bb900..d8cf15eb 100644
--- a/examples/rust/csv_to_iggy/Cargo.lock
+++ b/examples/rust/csv_to_iggy/Cargo.lock
@@ -723,6 +723,7 @@ dependencies = [
"globset",
"iggy",
"linkme",
+ "notify",
"rmp-serde",
"rustc-hash",
"serde",
@@ -2339,6 +2340,26 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "inotify"
+version = "0.11.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592"
+dependencies = [
+ "bitflags 2.13.1",
+ "inotify-sys",
+ "libc",
+]
+
+[[package]]
+name = "inotify-sys"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "inout"
version = "0.1.4"
@@ -2520,6 +2541,26 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "kqueue"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8d763e5b24120b4ddf50de6c92308156765aabfbbccebf401da7cff2d70a41ea"
+dependencies = [
+ "kqueue-sys",
+ "libc",
+]
+
+[[package]]
+name = "kqueue-sys"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087"
+dependencies = [
+ "bitflags 2.13.1",
+ "libc",
+]
+
[[package]]
name = "lazy_static"
version = "1.5.0"
@@ -2697,6 +2738,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427"
dependencies = [
"libc",
+ "log",
"wasi",
"windows-sys 0.61.2",
]
@@ -2767,6 +2809,34 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38bf9645c8b145698bb0b18a4637dcacbc421ea49bef2317e4fd8065a387cf21"
+[[package]]
+name = "notify"
+version = "8.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c41a04a5f59df9322cc657286dd2d79f90816119b22c5f847607c850110205ab"
+dependencies = [
+ "bitflags 2.13.1",
+ "inotify",
+ "kqueue",
+ "libc",
+ "log",
+ "mio",
+ "notify-types",
+ "objc2-core-foundation",
+ "objc2-core-services",
+ "walkdir",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "notify-types"
+version = "2.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cbd044e85df3d939d8e32a1c35a3b737c7d0a4eeb7acd737bd207644e00f4e5f"
+dependencies = [
+ "bitflags 2.13.1",
+]
+
[[package]]
name = "nougat"
version = "0.2.4"
@@ -2841,6 +2911,25 @@ dependencies = [
"libc",
]
+[[package]]
+name = "objc2-core-foundation"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
+dependencies = [
+ "bitflags 2.13.1",
+]
+
+[[package]]
+name = "objc2-core-services"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "583300ad934cba24ff5292aee751ecc070f7ca6b39a574cc21b7b5e588e06a0b"
+dependencies = [
+ "libc",
+ "objc2-core-foundation",
+]
+
[[package]]
name = "oid-registry"
version = "0.8.1"
diff --git a/examples/rust/csv_to_iggy/Cargo.toml b/examples/rust/csv_to_iggy/Cargo.toml
index 0ad26949..8df252b2 100644
--- a/examples/rust/csv_to_iggy/Cargo.toml
+++ b/examples/rust/csv_to_iggy/Cargo.toml
@@ -6,7 +6,7 @@ version = "0.1.0"
edition = "2024"
[dependencies]
-cocoindex = { path = "../../../rust/sdk/cocoindex", features = ["iggy"] }
+cocoindex = { path = "../../../rust/sdk/cocoindex", features = ["iggy", "fs_live"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
diff --git a/examples/rust/csv_to_iggy/src/main.rs b/examples/rust/csv_to_iggy/src/main.rs
index 3c85042c..2be1dc9b 100644
--- a/examples/rust/csv_to_iggy/src/main.rs
+++ b/examples/rust/csv_to_iggy/src/main.rs
@@ -10,17 +10,24 @@
//! cargo run -- consume # poll and print all messages on the topic
//!
//! Incrementality (two layers):
-//! - `process_csv` is memoized, so unchanged CSV files skip parsing entirely;
+//! - `process_csv` is memoized, so unchanged CSV files skip parsing entirely
+//! (each file is its own processing component declaring its rows'
+//! messages, so a removed file takes its messages with it);
//! - the managed `IggyTopicTarget` only *sends* a message when its value
//! changed since the last run. Iggy has no tombstone, so a removed row is
//! represented by a custom deletion value (`{"_deleted":"<key>"}`).
//!
//! Stream/topic are user-managed (CocoIndex never creates/drops them); `index`
//! creates them up front as a convenience.
+//!
+//! Parallels the Python example:
+//! - target : `iggy::mount_iggy_topic_target` (cf. `mount_iggy_topic_target`)
+//! - source : `walk_dir(..).live()` + `ctx.mount_each_live` (cf. `localfs.walk_dir(live=True)` + `coco.mount_each`)
+//! - per-file compute : `#[cocoindex::function(memo)]` declaring its messages (cf. `@coco.fn(memo=True)`)
+//! - declare a message : `target.declare_message(key, value)` (cf. `topic_target.declare_target_state`)
-use cocoindex::resources::fs::FileEntry;
-use cocoindex::connectors::iggy::{self, IggyProducer};
use cocoindex::Environment;
+use cocoindex::connectors::iggy::{self, IggyProducer};
cocoindex::context_key!(static PRODUCER: IggyProducer);
use cocoindex::prelude::*;
@@ -45,23 +52,23 @@ fn topic_name() -> String {
std::env::var("IGGY_TOPIC").unwrap_or_else(|_| "csv-rows".to_string())
}
-/// Parse one CSV file into `(message_key, json_value)` pairs. Memoized: a file
-/// whose content is unchanged since the last run is not re-parsed.
-#[cocoindex::function]
-async fn process_csv(_ctx: &Ctx, file: FileEntry) -> Result<Vec<(String, String)>> {
- let text = file.content_str()?;
+/// Parse one CSV file and declare one message per row (cf. Python `process_csv`).
+/// Memoized on the file: an unchanged file keeps its messages without re-parsing.
+/// The topic target is one per app, so it is not part of the memo key.
+#[cocoindex::function(memo, memo_key(target = skip))]
+async fn process_csv(ctx: &Ctx, file: &FileEntry, target: &iggy::IggyTopicTarget) -> Result<()> {
+ let text = file.read_text().await?;
let mut reader = csv::Reader::from_reader(text.as_bytes());
let headers = reader
.headers()
.map_err(|e| Error::engine(format!("csv headers: {e}")))?
.clone();
if headers.is_empty() {
- return Ok(Vec::new());
+ return Ok(());
}
- let mut out = Vec::new();
for record in reader.records() {
let record = record.map_err(|e| Error::engine(format!("csv record: {e}")))?;
- let Some(first) = record.get(0).filter(|s| !s.is_empty()) else {
+ let Some(key) = record.get(0).filter(|s| !s.is_empty()) else {
continue;
};
let mut row = serde_json::Map::new();
@@ -71,11 +78,10 @@ async fn process_csv(_ctx: &Ctx, file: FileEntry) -> Result<Vec<(String, String)
serde_json::Value::String(field.to_string()),
);
}
- let key = first.to_string();
let value = serde_json::to_string(&row).map_err(|e| Error::engine(format!("json: {e}")))?;
- out.push((key, value));
+ target.declare_message(ctx, key, value)?;
}
- Ok(out)
+ Ok(())
}
/// Create the (user-managed) stream + single-partition topic if they don't exist.
@@ -120,27 +126,24 @@ async fn index(producer: IggyProducer, stream: String, topic: String) -> Result<
partition: PARTITION,
// Iggy has no tombstone; emit a delete marker for removed rows.
deletion_value_fn: Some(Arc::new(|key: &[u8]| {
- format!("{{\"_deleted\":\"{}\"}}", String::from_utf8_lossy(key)).into_bytes()
+ format!("{{\"_deleted\":\"{}\"}}", String::from_utf8_lossy(key))
+ .into_bytes()
})),
};
let target =
- iggy::mount_iggy_topic_target(&ctx, &PRODUCER, stream, topic, options)
- .await?;
-
- let files = cocoindex::resources::fs::walk_items("./data", &["**/*.csv"])?;
- println!("found {} CSV file(s)", files.len());
-
- let per_file = use_mount_each!(files, |file| process_csv(ctx, file)).await?;
-
- let mut declared = 0;
- for messages in &per_file {
- for (key, value) in messages {
- target.declare_message(&ctx, key, value)?;
- declared += 1;
- }
- }
- println!("declared {declared} row message(s)");
- Ok(())
+ iggy::mount_iggy_topic_target(&ctx, &PRODUCER, stream, topic, options).await?;
+
+ // The source supports live watch (cf. Python `localfs.walk_dir(live=True)`).
+ let files = walk_dir("./data")
+ .path_matcher(PatternFilePathMatcher::include(["**/*.csv"])?)
+ .live();
+ // One processing component per file: each file's messages sync and
+ // clean up with that file (cf. Python `coco.mount_each(process_csv, files.items(), topic_target)`).
+ ctx.mount_each_live(&"process_csv", files, move |ctx, file: FileEntry| {
+ let target = target.clone();
+ async move { process_csv(&ctx, &file, &target).await }
+ })
+ .await
}
})
.await?;
diff --git a/examples/rust/image_search/Cargo.lock b/examples/rust/image_search/Cargo.lock
index e84a0e40..ed879b27 100644
--- a/examples/rust/image_search/Cargo.lock
+++ b/examples/rust/image_search/Cargo.lock
@@ -510,6 +510,7 @@ dependencies = [
"globset",
"hf-hub",
"linkme",
+ "notify",
"qdrant-client",
"rmp-serde",
"rust_decimal",
@@ -1845,6 +1846,26 @@ dependencies = [
"web-time",
]
+[[package]]
+name = "inotify"
+version = "0.11.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592"
+dependencies = [
+ "bitflags 2.13.1",
+ "inotify-sys",
+ "libc",
+]
+
+[[package]]
+name = "inotify-sys"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "interpolate_name"
version = "0.2.4"
@@ -2006,6 +2027,26 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "kqueue"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8d763e5b24120b4ddf50de6c92308156765aabfbbccebf401da7cff2d70a41ea"
+dependencies = [
+ "kqueue-sys",
+ "libc",
+]
+
+[[package]]
+name = "kqueue-sys"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087"
+dependencies = [
+ "bitflags 2.13.1",
+ "libc",
+]
+
[[package]]
name = "lazy_static"
version = "1.5.0"
@@ -2208,6 +2249,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427"
dependencies = [
"libc",
+ "log",
"wasi",
"windows-sys 0.61.2",
]
@@ -2334,6 +2376,34 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8"
+[[package]]
+name = "notify"
+version = "8.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c41a04a5f59df9322cc657286dd2d79f90816119b22c5f847607c850110205ab"
+dependencies = [
+ "bitflags 2.13.1",
+ "inotify",
+ "kqueue",
+ "libc",
+ "log",
+ "mio",
+ "notify-types",
+ "objc2-core-foundation",
+ "objc2-core-services",
+ "walkdir",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "notify-types"
+version = "2.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cbd044e85df3d939d8e32a1c35a3b737c7d0a4eeb7acd737bd207644e00f4e5f"
+dependencies = [
+ "bitflags 2.13.1",
+]
+
[[package]]
name = "nu-ansi-term"
version = "0.50.3"
@@ -2415,6 +2485,25 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3"
+[[package]]
+name = "objc2-core-foundation"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
+dependencies = [
+ "bitflags 2.13.1",
+]
+
+[[package]]
+name = "objc2-core-services"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "583300ad934cba24ff5292aee751ecc070f7ca6b39a574cc21b7b5e588e06a0b"
+dependencies = [
+ "libc",
+ "objc2-core-foundation",
+]
+
[[package]]
name = "once_cell"
version = "1.21.4"
diff --git a/examples/rust/image_search/Cargo.toml b/examples/rust/image_search/Cargo.toml
index 855da713..db504dfa 100644
--- a/examples/rust/image_search/Cargo.toml
+++ b/examples/rust/image_search/Cargo.toml
@@ -9,6 +9,7 @@ edition = "2024"
cocoindex = { path = "../../../rust/sdk/cocoindex", features = [
"qdrant",
"fastembed",
+ "fs_live",
] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
diff --git a/examples/rust/image_search/src/main.rs b/examples/rust/image_search/src/main.rs
index 138239bd..3b00c9f7 100644
--- a/examples/rust/image_search/src/main.rs
+++ b/examples/rust/image_search/src/main.rs
@@ -17,6 +17,10 @@
//! Build note: `qdrant-client` compiles protobufs, so a `protoc` binary is
//! required to build (set `PROTOC` or put it on `PATH`). `fastembed` downloads
//! the CLIP ONNX models on first run.
+//!
+//! Parallels the Python example:
+//! - source : `walk_dir(..).live()` + `ctx.mount_each_live` (cf. `localfs.walk_dir(live=True)` + `coco.mount_each`)
+//! - per-image compute : `#[cocoindex::function(memo)]` declaring its point (cf. `@coco.fn(memo=True)`)
use std::path::PathBuf;
@@ -49,26 +53,23 @@ cocoindex::context_key!(
detect_change
);
-/// A computed point: stable id + image vector + source filename.
-#[derive(Clone, Serialize, Deserialize)]
-struct PointData {
- id: u64,
- vector: Vec<f32>,
- filename: String,
-}
-
-#[cocoindex::function]
-async fn process_image(ctx: &Ctx, file: FileEntry) -> Result<PointData> {
+/// Embed one image and declare its point (cf. Python `process_file`).
+/// Memoized on the file: an unchanged image keeps its point without re-embedding.
+/// The collection target is one per app, so it is not part of the memo key.
+#[cocoindex::function(memo, memo_key(target = skip))]
+async fn process_image(
+ ctx: &Ctx,
+ file: &FileEntry,
+ target: &qdrant::CollectionTarget,
+) -> Result<()> {
let filename = file.key();
- let bytes = file.content()?;
+ let bytes = file.read().await?;
let vector = ctx.get_key(&EMBEDDER)?.embed(ctx, bytes).await?;
- let id_gen = IdGenerator::new();
- let id = id_gen.next_id(&ctx, &filename).await?;
- Ok(PointData {
- id,
- vector,
- filename,
- })
+ let id = IdGenerator::new().next_id(ctx, &filename).await?;
+ let serde_json::Value::Object(payload) = json!({ "filename": filename }) else {
+ return Err(Error::engine("point payload is not a JSON object"));
+ };
+ target.declare_point(ctx, id, vector, payload)
}
async fn app_main(ctx: Ctx, sourcedir: PathBuf) -> Result<()> {
@@ -80,24 +81,18 @@ async fn app_main(ctx: Ctx, sourcedir: PathBuf) -> Result<()> {
)
.await?;
- let files = walk_items(&sourcedir, IMAGE_GLOBS)?;
- println!(
- "indexing {} image(s) from {}",
- files.len(),
- sourcedir.display()
- );
-
- let points = use_mount_each!(files, |file| process_image(ctx, file)).await?;
-
- for p in &points {
- let payload = json!({ "filename": p.filename })
- .as_object()
- .unwrap()
- .clone();
- target.declare_point(&ctx, p.id, p.vector.clone(), payload)?;
- }
- println!("indexed {} image(s) total", points.len());
- Ok(())
+ // The source supports live watch (cf. Python `localfs.walk_dir(live=True)`).
+ let files = walk_dir(sourcedir)
+ .recursive(true)
+ .path_matcher(PatternFilePathMatcher::include(IMAGE_GLOBS)?)
+ .live();
+ // One processing component per image: its point syncs and cleans up with
+ // the image (cf. Python `coco.mount_each(process_file, files.items(), target)`).
+ ctx.mount_each_live(&"process_image", files, move |ctx, file: FileEntry| {
+ let target = target.clone();
+ async move { process_image(&ctx, &file, &target).await }
+ })
+ .await
}
async fn query_once(
@@ -105,7 +100,10 @@ async fn query_once(
text_embedder: &SentenceTransformerEmbedder,
query: &str,
) -> Result<()> {
- let query_vec = text_embedder.embed_batch(vec![query.to_string()]).await?.remove(0);
+ let query_vec = text_embedder
+ .embed_batch(vec![query.to_string()])
+ .await?
+ .remove(0);
let hits = qdrant::vector_search(conn, COLLECTION, query_vec, TOP_K).await?;
for hit in hits {
let filename = hit
diff --git a/examples/rust/image_search_colpali/Cargo.lock b/examples/rust/image_search_colpali/Cargo.lock
index f2e36967..7eb61362 100644
--- a/examples/rust/image_search_colpali/Cargo.lock
+++ b/examples/rust/image_search_colpali/Cargo.lock
@@ -359,6 +359,7 @@ dependencies = [
"futures",
"globset",
"linkme",
+ "notify",
"qdrant-client",
"rmp-serde",
"rust_decimal",
@@ -1410,6 +1411,26 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "inotify"
+version = "0.11.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592"
+dependencies = [
+ "bitflags 2.13.1",
+ "inotify-sys",
+ "libc",
+]
+
+[[package]]
+name = "inotify-sys"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "ipnet"
version = "2.12.1"
@@ -1560,6 +1581,26 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "kqueue"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8d763e5b24120b4ddf50de6c92308156765aabfbbccebf401da7cff2d70a41ea"
+dependencies = [
+ "kqueue-sys",
+ "libc",
+]
+
+[[package]]
+name = "kqueue-sys"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087"
+dependencies = [
+ "bitflags 2.13.1",
+ "libc",
+]
+
[[package]]
name = "lazy_static"
version = "1.5.0"
@@ -1680,6 +1721,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427"
dependencies = [
"libc",
+ "log",
"wasi",
"windows-sys 0.61.2",
]
@@ -1719,6 +1761,34 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38bf9645c8b145698bb0b18a4637dcacbc421ea49bef2317e4fd8065a387cf21"
+[[package]]
+name = "notify"
+version = "8.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c41a04a5f59df9322cc657286dd2d79f90816119b22c5f847607c850110205ab"
+dependencies = [
+ "bitflags 2.13.1",
+ "inotify",
+ "kqueue",
+ "libc",
+ "log",
+ "mio",
+ "notify-types",
+ "objc2-core-foundation",
+ "objc2-core-services",
+ "walkdir",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "notify-types"
+version = "2.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cbd044e85df3d939d8e32a1c35a3b737c7d0a4eeb7acd737bd207644e00f4e5f"
+dependencies = [
+ "bitflags 2.13.1",
+]
+
[[package]]
name = "nu-ansi-term"
version = "0.50.3"
@@ -1743,6 +1813,25 @@ dependencies = [
"autocfg",
]
+[[package]]
+name = "objc2-core-foundation"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
+dependencies = [
+ "bitflags 2.13.1",
+]
+
+[[package]]
+name = "objc2-core-services"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "583300ad934cba24ff5292aee751ecc070f7ca6b39a574cc21b7b5e588e06a0b"
+dependencies = [
+ "libc",
+ "objc2-core-foundation",
+]
+
[[package]]
name = "once_cell"
version = "1.21.4"
diff --git a/examples/rust/image_search_colpali/Cargo.toml b/examples/rust/image_search_colpali/Cargo.toml
index 6f690869..39f67ee7 100644
--- a/examples/rust/image_search_colpali/Cargo.toml
+++ b/examples/rust/image_search_colpali/Cargo.toml
@@ -6,7 +6,7 @@ version = "0.1.0"
edition = "2024"
[dependencies]
-cocoindex = { path = "../../../rust/sdk/cocoindex", features = ["qdrant"] }
+cocoindex = { path = "../../../rust/sdk/cocoindex", features = ["qdrant", "fs_live"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
diff --git a/examples/rust/image_search_colpali/src/main.rs b/examples/rust/image_search_colpali/src/main.rs
index 53ead886..894156cb 100644
--- a/examples/rust/image_search_colpali/src/main.rs
+++ b/examples/rust/image_search_colpali/src/main.rs
@@ -22,6 +22,10 @@
//! `cocoindex::connectors::qdrant`.
//!
//! Build note: `qdrant-client` compiles protobufs, so `protoc` is required.
+//!
+//! Parallels the Python example:
+//! - source : `walk_dir(..).live()` + `ctx.mount_each_live` (cf. `localfs.walk_dir(live=True)` + `coco.mount_each`)
+//! - per-image compute : `#[cocoindex::function(memo)]` declaring its point (cf. `@coco.fn(memo=True)`)
use std::path::PathBuf;
@@ -111,26 +115,23 @@ impl MemoInput for ColpaliClient {
}
}
-/// A computed point: stable id + multi-vector embedding + source filename.
-#[derive(Clone, Serialize, Deserialize)]
-struct PointData {
- id: u64,
- vectors: Vec<Vec<f32>>,
- filename: String,
-}
-
-#[cocoindex::function]
-async fn process_image(ctx: &Ctx, file: FileEntry) -> Result<PointData> {
+/// Embed one image and declare its point (cf. Python `process_file`).
+/// Memoized on the file: an unchanged image keeps its point without re-embedding.
+/// The collection target is one per app, so it is not part of the memo key.
+#[cocoindex::function(memo, memo_key(target = skip))]
+async fn process_image(
+ ctx: &Ctx,
+ file: &FileEntry,
+ target: &qdrant::CollectionTarget,
+) -> Result<()> {
let filename = file.key();
- let bytes = file.content()?;
- let vectors = ctx.get_key(&COLPALI)?.embed_image(bytes).await?;
- let id_gen = IdGenerator::new();
- let id = id_gen.next_id(&ctx, &filename).await?;
- Ok(PointData {
- id,
- vectors,
- filename,
- })
+ let bytes = file.read().await?;
+ let vectors = ctx.get_key(&COLPALI)?.embed_image(bytes.to_vec()).await?;
+ let id = IdGenerator::new().next_id(ctx, &filename).await?;
+ let serde_json::Value::Object(payload) = json!({ "filename": filename }) else {
+ return Err(Error::engine("point payload is not a JSON object"));
+ };
+ target.declare_multivector_point(ctx, id, vectors, payload)
}
async fn app_main(ctx: Ctx, sourcedir: PathBuf) -> Result<()> {
@@ -142,24 +143,18 @@ async fn app_main(ctx: Ctx, sourcedir: PathBuf) -> Result<()> {
)
.await?;
- let files = walk_items(&sourcedir, IMAGE_GLOBS)?;
- println!(
- "indexing {} image(s) from {}",
- files.len(),
- sourcedir.display()
- );
-
- let points = use_mount_each!(files, |file| process_image(ctx, file)).await?;
-
- for p in &points {
- let payload = json!({ "filename": p.filename })
- .as_object()
- .unwrap()
- .clone();
- target.declare_multivector_point(&ctx, p.id, p.vectors.clone(), payload)?;
- }
- println!("indexed {} image(s) total", points.len());
- Ok(())
+ // The source supports live watch (cf. Python `localfs.walk_dir(live=True)`).
+ let files = walk_dir(sourcedir)
+ .recursive(true)
+ .path_matcher(PatternFilePathMatcher::include(IMAGE_GLOBS)?)
+ .live();
+ // One processing component per image: its point syncs and cleans up with
+ // the image (cf. Python `coco.mount_each(process_file, files.items(), target)`).
+ ctx.mount_each_live(&"process_image", files, move |ctx, file: FileEntry| {
+ let target = target.clone();
+ async move { process_image(&ctx, &file, &target).await }
+ })
+ .await
}
async fn query_once(conn: &QdrantConnection, colpali: &ColpaliClient, query: &str) -> Result<()> {