CocoIndex has a built-in Amazon S3 source connector. The pipeline in this post reads Markdown files from an S3 bucket, chunks and embeds them, and writes the vectors to a Postgres pgvector table for semantic search.
The example is about incremental processing: when you add one object to the bucket, CocoIndex embeds that one object, not the whole bucket. It is Semantic Search 101 with the source changed from a local folder to S3; everything downstream is the same.
The full project is in the CocoIndex v1 repo.
Why incremental processing
Incremental processing processes only the data that changed since the last run, instead of reprocessing everything. Three properties of an S3 corpus make it worth the effort: search results must stay fresh, each item is expensive to transform, and the bucket can be large.
People who edit a document expect search to reflect the edit soon after. An AI agent that retrieves a stale chunk answers from out-of-date text, and the answer does not show that the source was out of date.
When each item goes through an embedding model or an LLM, the transform costs far more than reading the item. Re-embedding unchanged text spends that cost again and returns the same vector.
With terabytes in S3, reprocessing everything on each new file takes too long and costs too much. Incremental processing keeps the work proportional to the size of the change.
As a rule: if T is the staleness you can tolerate, and you do not want to recompute the whole corpus every T, you need incremental processing.
The indexing flow
The flow lists the Markdown objects in the bucket. For each object it splits the text into chunks, embeds each chunk and declares one row per chunk in the vector table:
Each object is handled by its own processing component, so change detection and parallelism are per object.
A re-run embeds only new chunk text
CocoIndex decides what to redo at two levels. Both come from the code below.
- Per object.
process_fileis memoized (memo=True). The memo belongs to the object’s path. It stays valid while the object’s ETag (the content fingerprint S3 returns in the listing) and the code are the same. An unchanged object is skipped without a download. - Per chunk. A changed object is read again and split again from the start.
process_chunkruns for every chunk, but the embedder’sembed()is memoized on the chunk text. A chunk whose text the embedder saw in this object’s last run is a memo hit and makes no model call.
On the write side, each row’s id comes from IdGenerator.next_id(chunk.text), so a chunk keeps its id while its text stays the same. CocoIndex compares the rows that a component declares in this run with the rows it declared in the last run:
- A chunk with new text gets a new
id. Its row is inserted, and the row of the text it replaced is deleted. - A chunk with the same text at new offsets keeps its
id. Its row is updated with the new offsets and the cached vector. - A chunk with the same text and the same offsets keeps its row as it is.
Pick a change to one object and run the update. The object is 1706.03762v7.md, one of the 3 Markdown files from the Semantic Search 101 example (examples/text_embedding/markdown_files). The chunks and offsets are the real output of the example’s splitter on it:
Pick a change, then run the update
Real chunks of1706.03762v7.md: 31 chunks, 46,145 charactersThe object is not touched. The next listing returns the same ETag.
End-to-end memory networks are based on a recurrent attention mechanism instead of sequencealigned sequence-aligned recurrence and have been shown to perform well on simple-la…character 6,363 · +1 character
…We trained the base models for a total of 100,000 steps or 12 hours. For our big models,(described models (described on the bottom line of table [3)](#page-8-0), step time was…character 22,323 · same length
End-to-end memory networks are based on a recurrent attention mechanism instead of sequencealigned recurrence and have been shown to perform well on simple-lan…character 6,278 · −235 characters
EMBED_MODEL = sentence-transformers/all-MiniLM-L6-v2 sentence-transformers/paraphrase-MiniLM-L3-v2no object in the bucket changes
- objects read
- –
- chunks produced
- –
- model calls
- –
- rows written
- –
Pick a change and run the update. A full rebuild would read all 3 objects and make 106 model calls.
In these edits, a change touches the text of one chunk, or of two when it falls where two chunks overlap (chunk_overlap=500). Only those chunks go to the model. An edit that changes the length of the object also shifts every later chunk; those rows are updated with new offsets but keep their vectors.
We ran the typo fix against the pipeline, with those 3 Markdown files in an S3-compatible store. CocoIndex reported process_file: 3 total | 1 reprocessed, 2 unchanged. In Postgres, 1 row was deleted and 1 inserted, 27 rows got new offsets and kept the same vectors, and the other 3 rows of the object and all 75 rows of the other 2 objects were not written.
A new model re-embeds every chunk
EMBEDDER is declared with detect_change=True, so CocoIndex fingerprints the embedder and invalidates every memo that read it. Context reads propagate transitively: process_chunk calls use_context(EMBEDDER) inside process_file, so changing EMBED_MODEL invalidates the process_file memo of every object. The next run reads every object from S3 again, splits it again and embeds every chunk with the new model. Chunk texts do not change, so every row keeps its id and gets a new vector.
After we changed EMBED_MODEL to sentence-transformers/paraphrase-MiniLM-L3-v2 (also 384 dimensions), the run reported process_file: 3 total | 3 reprocessed, and all 106 rows kept their ids and got new vectors.
Without detect_change=True, the process_file memos would stay valid, so unchanged objects would keep vectors from the old model while queries use the new one.
Define the pipeline
The app reads its settings from the environment. Shared resources (the Postgres pool, the S3 client and the embedder) are provided once in the app lifespan and read anywhere with coco.use_context:
from __future__ import annotations
import asyncio
import os
import sys
from dataclasses import dataclass
from dotenv import load_dotenv
from typing import AsyncIterator, Annotated
import aiobotocore.session
import asyncpg
from aiobotocore.client import AioBaseClient
from numpy.typing import NDArray
from pgvector.asyncpg import register_vector
import cocoindex as coco
from cocoindex.connectors import amazon_s3, postgres
from cocoindex.ops.sentence_transformers import SentenceTransformerEmbedder
from cocoindex.ops.text import RecursiveSplitter
from cocoindex.resources.chunk import Chunk
from cocoindex.resources.file import PatternFilePathMatcher
from cocoindex.resources.id import IdGenerator
DATABASE_URL = os.getenv(
"POSTGRES_URL", "postgres://cocoindex:cocoindex@localhost/cocoindex"
)
TABLE_NAME = "amazon_s3_doc_embeddings"
PG_SCHEMA_NAME = "coco_examples"
TOP_K = 5
# S3 configuration
S3_BUCKET = os.environ["S3_BUCKET"]
S3_PREFIX = os.getenv("S3_PREFIX", "")
EMBED_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
PG_DB = coco.ContextKey[asyncpg.Pool]("s3_embedding_db")
S3_CLIENT = coco.ContextKey[AioBaseClient]("s3_client")
EMBEDDER = coco.ContextKey[SentenceTransformerEmbedder]("embedder", detect_change=True)
_splitter = RecursiveSplitter()
@coco.lifespan
async def coco_lifespan(
builder: coco.EnvironmentBuilder,
) -> AsyncIterator[None]:
async with asyncpg.create_pool(DATABASE_URL) as pool:
builder.provide(PG_DB, pool)
builder.provide(EMBEDDER, SentenceTransformerEmbedder(EMBED_MODEL))
# Set AWS_ENDPOINT_URL for S3-compatible services (e.g. MinIO).
session = aiobotocore.session.get_session()
async with session.create_client("s3") as s3_client:
builder.provide(S3_CLIENT, s3_client)
yield
create_client("s3") takes AWS credentials from the standard chain: environment variables, ~/.aws/credentials or an IAM role.
The target row is a plain dataclass. The embedding column is annotated with the embedder, so CocoIndex knows the vector dimension:
@dataclass
class DocEmbedding:
id: int
filename: str
chunk_start: int
chunk_end: int
text: str
embedding: Annotated[NDArray, EMBEDDER]
Chunk, embed, declare
Each chunk becomes one row. process_chunk embeds the chunk text and declares the row:
@coco.fn
async def process_chunk(
chunk: Chunk,
filename: str,
id_gen: IdGenerator,
table: postgres.TableTarget[DocEmbedding],
) -> None:
table.declare_row(
row=DocEmbedding(
id=await id_gen.next_id(chunk.text),
filename=filename,
chunk_start=chunk.start.char_offset,
chunk_end=chunk.end.char_offset,
text=chunk.text,
embedding=await coco.use_context(EMBEDDER).embed(chunk.text),
),
)
process_file reads one S3 object, splits it into chunks and maps process_chunk over them. memo=True skips an object whose ETag did not change, as long as the code did not change either:
@coco.fn(memo=True)
async def process_file(
file: amazon_s3.S3File,
table: postgres.TableTarget[DocEmbedding],
) -> None:
text = await file.read_text()
chunks = _splitter.split(
text, chunk_size=2000, chunk_overlap=500, language="markdown"
)
id_gen = IdGenerator()
await coco.map(process_chunk, chunks, file.file_path.path.as_posix(), id_gen, table)
Wire up the app
app_main mounts the pgvector table target, lists the Markdown objects in the bucket, and starts one process_file component per object with mount_each:
@coco.fn
async def app_main() -> None:
target_table = await postgres.mount_table_target(
PG_DB,
table_name=TABLE_NAME,
table_schema=await postgres.TableSchema.from_class(
DocEmbedding,
primary_key=["id"],
),
pg_schema_name=PG_SCHEMA_NAME,
)
client = coco.use_context(S3_CLIENT)
files = amazon_s3.list_objects(
client,
S3_BUCKET,
prefix=S3_PREFIX,
path_matcher=PatternFilePathMatcher(included_patterns=["**/*.md"]),
)
await coco.mount_each(process_file, files.items(), target_table)
app = coco.App(
coco.AppConfig(name="AmazonS3EmbeddingV1"),
app_main,
)
amazon_s3.list_objects lists the objects under the prefix; prefix filters on the server and the **/*.md pattern filters the listed keys. files.items() yields (key, file) pairs, where the key is the object key relative to the prefix, and mount_each gives each object a stable component keyed on the object key. When an object is deleted from the bucket, its component goes away and CocoIndex deletes the rows that component declared.
Query the index
The query embeds the question with the same model and returns the nearest chunks by pgvector cosine distance:
async def query_once(
pool: asyncpg.Pool,
embedder: SentenceTransformerEmbedder,
query: str,
*,
top_k: int = TOP_K,
) -> None:
query_vec = await embedder.embed(query)
async with pool.acquire() as conn:
rows = await conn.fetch(
f"""
SELECT
filename,
text,
embedding <=> $1 AS distance
FROM "{PG_SCHEMA_NAME}"."{TABLE_NAME}"
ORDER BY distance ASC
LIMIT $2
""",
query_vec,
top_k,
)
for r in rows:
score = 1.0 - float(r["distance"])
print(f"[{score:.3f}] {r['filename']}")
print(f" {r['text']}")
print("---")
async def query(initial_query: str | None = None) -> None:
embedder = SentenceTransformerEmbedder(EMBED_MODEL)
async with asyncpg.create_pool(DATABASE_URL, init=register_vector) as pool:
if initial_query is not None:
await query_once(pool, embedder, initial_query)
return
while True:
q = input("Enter search query (or Enter to quit): ").strip()
if not q:
break
await query_once(pool, embedder, q)
if __name__ == "__main__":
load_dotenv()
initial = " ".join(sys.argv[1:]) if len(sys.argv) > 1 else None
asyncio.run(query(initial))
init=register_vector lets asyncpg pass the numpy query vector to pgvector.
Run it
1. Install. Get the example and install its dependencies (Python 3.11 or later):
git clone https://github.com/cocoindex-io/cocoindex.git
cd cocoindex/examples/amazon_s3_embedding
pip install -e .
This installs cocoindex[amazon_s3,postgres,sentence_transformers], asyncpg, pgvector, numpy and python-dotenv.
2. Start Postgres with pgvector. From the example folder:
docker compose -f ../../dev/postgres.yaml up -d
This starts pgvector/pgvector:pg17 on port 5432 with user, password and database cocoindex.
3. Set up the S3 bucket. Create a bucket and upload your Markdown files. The pipeline only lists and reads objects, so read-only permissions are enough (the AWS managed policy AmazonS3ReadOnlyAccess). The Amazon S3 connector docs describe the client and the source API. Copy .env.example to .env and set these values:
COCOINDEX_DB=./cocoindex.db
POSTGRES_URL=postgres://cocoindex:cocoindex@localhost/cocoindex
S3_BUCKET=your-bucket-name
S3_PREFIX=markdown_files/
# For an S3-compatible service such as MinIO:
# AWS_ENDPOINT_URL=http://localhost:9000
COCOINDEX_DB is where CocoIndex keeps its own state (memos and the rows each component declared). AWS credentials come from your environment, ~/.aws/credentials or an IAM role.
4. Build the index. This is a one-shot catch-up run: it lists the bucket, processes what changed, syncs Postgres and exits.
cocoindex update main
The first run embeds every chunk. On the 3 Markdown files the final stats were:
[Stats] (terminated)
✅ app_main: 1 total | 1 added
✅ declare_target_state_with_child: 1 total | 1 added
✅ process_file: 3 total | 3 added
5. Search. cocoindex update loads .env by itself. main.py reads S3_BUCKET when it is imported, before its own load_dotenv() call, so export the variables before you run the query:
set -a; source .env; set +a
python main.py "what is self-attention?"
This is the output on the 3 Markdown files. Each result prints the whole chunk; here every chunk is cut to its first line:
[0.494] 1706.03762v7.md
#### Attention Visualizations **Input-Input Layer5**
---
[0.445] 1706.03762v7.md
### 3.2.3 Applications of Attention in our Model
---
[0.419] 1706.03762v7.md
### 4 Why Self-Attention
---
[0.343] 1706.03762v7.md
## 2 Background
---
[0.329] 1706.03762v7.md
### 3.2.1 Scaled Dot-Product Attention
---
We ran these steps on a local machine, with an S3-compatible server in place of AWS (AWS_ENDPOINT_URL) and the 3 Markdown files from examples/text_embedding/markdown_files.
Keep the index fresh
Run cocoindex update main again after the bucket changes. As the demo shows, the run reads only changed objects and embeds only new chunk text, so frequent runs are cheap. Schedule it as often as your freshness target requires, with cron, Airflow, GitHub Actions, or an Azure or Lambda function.
The amazon_s3 source does not support live mode, so each run is a catch-up pass that lists the bucket. If you need event-driven, second-level freshness instead of scheduled runs, use a source that supports live mode, such as Kafka or Iggy, as the source of your pipeline. Continuous updates compares scheduled catch-up runs with live mode.
Frequently asked questions
How do I build an incremental ETL pipeline on Amazon S3?
CocoIndex has a built-in Amazon S3 source connector. You list the objects with amazon_s3.list_objects, hand them to coco.mount_each, and each object is processed by its own component that chunks, embeds and declares vector rows. The component is memoized on the object's ETag, so a re-run reads only the objects that changed: adding one object to the bucket embeds only that object.
See The indexing flow.
When should I use incremental processing instead of reprocessing everything?
Incremental processing only handles data that is new or changed since the last run. It matters when search results must stay fresh, when each item is expensive to transform (an embedding model or an LLM), and when the corpus is large enough that reprocessing it for each new file is impractical. As a rule: if T is the staleness you can tolerate and you do not want to recompute everything every T, you need incremental processing.
Does CocoIndex re-embed an entire file when only part of it changes?
No. A changed object is read and split again, but the embedder's embed() is memoized on the chunk text, so only chunks with new text call the model. Each row's id comes from IdGenerator.next_id(chunk.text): a chunk with new text gets a new id, so its row is inserted and the replaced row is deleted. Chunks with the same text keep their id and vector; if the edit shifted them, only their offsets are updated. In the example, a one-character typo fix makes 1 model call for a 31-chunk file.
What happens when I change the embedding model?
EMBEDDER is declared with detect_change=True. Context reads propagate transitively, so changing EMBED_MODEL invalidates the process_file memo of every object: the next run reads every object from S3 again, splits it and embeds every chunk with the new model. Row ids stay the same, so every row is updated with its new vector.
What IAM permissions does CocoIndex need to read from S3?
Read-only S3 access is enough: the AmazonS3ReadOnlyAccess policy plus AWS credentials from the standard credential chain (environment variables, ~/.aws/credentials or an IAM role). The pipeline only lists and reads objects; it does not write to the bucket. See Run it for the setup steps.
How do I keep the S3 index fresh?
Run cocoindex update main on a schedule that matches the freshness you need: cron, Airflow, GitHub Actions, or an Azure or Lambda function. A re-run reads only changed objects and embeds only new chunk text, so running it often costs little. The amazon_s3 source has no live mode, so each run is a catch-up pass over the listing; for event-driven, second-level freshness, use a source that supports live mode, such as Kafka or Iggy.
See Keep the index fresh.
Can I use the same pipeline for local files or other object stores?
Yes. This example is Semantic Search 101 with the source swapped from a local folder to S3; chunking, embedding, the pgvector target and the query are identical. Swapping the source to localfs, Azure Blob or Google Drive leaves the rest of the flow unchanged.
See Define the pipeline.
Build fresh context for your agents.
CocoIndex keeps derived data in sync with its sources. Only what changed re-runs.


