Your product table answers exact questions well: WHERE product_category = 'Electronics', ORDER BY price. Search it for “quiet on a long flight” and keyword search returns nothing, because no row contains those words.
This post turns an existing Postgres table into a semantic index that lives in the same Postgres, with pgvector, and keeps it in step with the table as rows change. The demo below runs both kinds of search over the example’s 5 sample rows, with real similarity scores.
Same 5 rows, two kinds of search
Pick a queryto_tsvector('english',
product_category || ' ' ||
product_name || ' ' || description)
@@ plainto_tsquery('english',
'quiet on a long flight')embedding <=> $1Scores are real: cosine similarity from all-MiniLM-L6-v2 between the query and each row's full_description, as the example computes them. For every query, the top match is the product you meant, while full-text search returns nothing.
The full code is in the CocoIndex repo and runs on CocoIndex v1.
Why index the table you already have
- Vectors sit next to the rowsVectors land in Postgres with pgvector, next to the rows they describe. Rank by meaning and filter with an ordinary WHERE clause in one SQL query.
- Reads the table in placePgTableSource reads the table you already have. Source and target can be the same database or two different ones.
- Model calls only for new textUnchanged rows are memo hits. A price edit re-runs the arithmetic and reuses the vector; only new text reaches the model.
- Deletes carry overRemove a source row and its output row is removed on the next update. CocoIndex handles the cleanup.
You write the transformation in plain Python with your own dataclasses, target_state = transformation(source_state). CocoIndex’s Rust engine handles the rest: change tracking, memoization, and a managed target table.
What we’ll build
The pipeline reads product rows from source_products, computes a total_value and a combined full_description, embeds that description, and writes the enriched rows plus their vectors to a second Postgres table.
Postgres source indexing flow: a Postgres source_products table feeds a CocoIndex app; one processing component per row derives total_value and a full_description, embeds the description with a sentence-transformer model, and declares a row that CocoIndex stores back in a Postgres pgvector table.
source_productsfetch_rowsCocoIndex app · mount_each: one component per rowprocessing component · Audio | Headphonesderivetotal_value + textembedtext → vectordeclare_rowfields + vector… one source row = one output row; change a row and only it re-embedsupsertPostgres · pgvectoroutput tableOne row, end to end
The stepper below follows one row through the per-row function. It plays on its own, or you can step through it.
Follow one row through process_product
mount_each gives every source row its own processing component, keyed by (product_category, product_name). row_type=SourceProduct has already turned the row into a dataclass.
Category and name join the description, so the vector carries them too. full_description is a local variable: it feeds the model and is not stored.
total_value is ordinary Python arithmetic, 199.99 × 50, sitting next to the model call in the same function.
all-MiniLM-L6-v2 turns the text into 384 numbers. embed() is itself memoized on the model and the text, so when this row re-runs with the same text, the stored vector is reused instead of calling the model.
declare_row states the row that should exist. CocoIndex upserts it into coco_examples_v1.output, and deletes it when the source row goes away. You do not write the SQL for either.
- product_category
- Electronics
- product_name
- Wireless Headphones
- description
- High-quality wireless headphones with noise cancellation
- price
- 199.99
- amount
- 50
- full_description local
- Category: Electronics Name: Wireless Headphones High-quality wireless headphones with noise cancellation
- total_value
- 199.99 × 50 = 9999.5
- embedding
- [-0.122, 0.070, -0.043, -0.007, … ] 384 floats
coco_examples_v1.output@coco.fn(memo=True)async def process_product( product: SourceProduct, table: postgres.TableTarget[OutputProduct],) -> None: full_description = ( f"Category: {product.product_category}\n" f"Name: {product.product_name}\n\n" f"{product.description}" ) total_value = product.price * product.amount embedding = await coco.use_context(EMBEDDER).embed( full_description) table.declare_row(row=OutputProduct( ..., total_value=total_value, embedding=embedding))The code has three parts: the row shapes, the per-row function, and the app that connects them.
Define the row shapes
Each source row maps into a plain dataclass, and each output row into another. The embedding field is annotated with the embedder, so CocoIndex infers the vector’s size (384 for this model) and creates a matching vector(384) column:
from dataclasses import dataclass
from typing import Annotated, AsyncIterator
from numpy.typing import NDArray
import cocoindex as coco
from cocoindex.ops.sentence_transformers import SentenceTransformerEmbedder
EMBED_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
EMBEDDER = coco.ContextKey[SentenceTransformerEmbedder]("embedder", detect_change=True)
@dataclass
class SourceProduct:
product_category: str
product_name: str
description: str
price: float
amount: int
@dataclass
class OutputProduct:
product_category: str
product_name: str
description: str
price: float
amount: int
total_value: float
embedding: Annotated[NDArray, EMBEDDER]
The database pools and the embedder are created once, in the app lifespan, and handed to the pipeline through context keys. Set SOURCE_DATABASE_URL to read from a separate database, or leave it pointing at the same instance:
import os
import asyncpg
from cocoindex.connectors import postgres
DATABASE_URL = os.getenv(
"POSTGRES_URL", "postgres://cocoindex:cocoindex@localhost/cocoindex"
)
SOURCE_DATABASE_URL = os.getenv("SOURCE_DATABASE_URL", DATABASE_URL)
PG_DB = coco.ContextKey[asyncpg.Pool]("postgres_source_db")
SOURCE_POOL = coco.ContextKey[asyncpg.Pool]("source_pool")
@coco.lifespan
async def coco_lifespan(builder: coco.EnvironmentBuilder) -> AsyncIterator[None]:
async with (
asyncpg.create_pool(DATABASE_URL) as target_pool,
asyncpg.create_pool(SOURCE_DATABASE_URL) as source_pool,
):
builder.provide(PG_DB, target_pool)
builder.provide(SOURCE_POOL, source_pool)
builder.provide(EMBEDDER, SentenceTransformerEmbedder(EMBED_MODEL))
yield
Transform and embed each row
process_product runs once per source row. It composes the text, computes the derived field, embeds the text, and declares the output row. memo=True caches the whole call, so a row whose content and code are unchanged is skipped on the next run:
@coco.fn(memo=True)
async def process_product(
product: SourceProduct,
table: postgres.TableTarget[OutputProduct],
) -> None:
full_description = (
f"Category: {product.product_category}\n"
f"Name: {product.product_name}\n\n{product.description}"
)
total_value = product.price * product.amount
embedding = await coco.use_context(EMBEDDER).embed(full_description)
table.declare_row(
row=OutputProduct(
product_category=product.product_category,
product_name=product.product_name,
description=product.description,
price=product.price,
amount=product.amount,
total_value=total_value,
embedding=embedding,
),
)
We embed the composed description, category and name included. A query that matches a product’s category or name finds it even when the description body never uses those words.
The model call and the arithmetic sit side by side. total_value = price * amount is ordinary Python, and embed(...) is a model call. To CocoIndex both are transforms that derive an output field from the source row.
Wire up the app
app_main mounts the target table, opens the source table, and mounts one processing component per source row:
@coco.fn
async def app_main() -> None:
target_table = await postgres.mount_table_target(
PG_DB,
table_name="output",
table_schema=await postgres.TableSchema.from_class(
OutputProduct,
primary_key=["product_category", "product_name"],
),
pg_schema_name="coco_examples_v1",
)
source = postgres.PgTableSource(
coco.use_context(SOURCE_POOL),
table_name="source_products",
row_type=SourceProduct,
)
await coco.mount_each(
process_product,
source.fetch_rows().items(lambda p: (p.product_category, p.product_name)),
target_table,
)
app = coco.App(
coco.AppConfig(name="PostgresSourceV1"),
app_main,
)
PgTableSourcereads the existing table, androw_type=SourceProductmaps each row into the dataclass. See the Postgres connector docs forcolumns,row_factory, and schema options.items(...)tags each row with its(product_category, product_name)key. That key names the row’s component, so CocoIndex can tell on the next run which rows are new, which changed, and which disappeared.mount_table_targetcreates and manages the target table: schema, idempotent upserts, and removal of rows whose target state is no longer declared.
An update costs what changed
Every run of cocoindex update re-reads the whole source table and checks each row against its memo. That costs little next to a model call, and the model only sees text it has not embedded for that row before. Make some edits and run the update:
Edit the table, then run the update
Illustrative: the rows from the examplecocoindex updateoutput- rows read
- –
process_productran- –
- model calls
- –
- output rows changed
- –
Pick any edits (or none) and run the update. A full rebuild would make one model call per row.
The demo shows two layers of memoization:
process_productis memoized on the whole row. An unchanged row skips the function entirely and keeps its output row as it is.embed()is memoized on the model and the text. A row whose price or amount changed re-runsprocess_product, sototal_valueis recomputed and the output row is upserted, but itsfull_descriptionis unchanged and the vector comes from the cache.
Only new text reaches the model: an inserted row, a rewritten description, or a renamed product or category (both are part of the embedded text, and part of the row’s key). A deleted source row needs no model call: its component is not mounted on the next run, so CocoIndex deletes the output row it declared.
Code and model changes are tracked too. Editing process_product re-runs it for every row, but embed() still hits its cache unless the composed text changed. Swapping the model re-embeds every row, because EMBEDDER is declared with detect_change=True.
Run it
Start Postgres with pgvector (the repo ships a compose file), configure the connection strings, and seed the source table with psql (use your SOURCE_DATABASE_URL if the source is a separate database):
docker compose -f ../../dev/postgres.yaml up -d
cp .env.example .env # set POSTGRES_URL and SOURCE_DATABASE_URL
pip install -e .
psql "postgres://cocoindex:cocoindex@localhost/cocoindex" -f ./prepare_source_data.sql
Build the index. The Postgres source runs as a one-shot catch-up: it scans the source table, syncs the target, and exits.
cocoindex update main
Re-run it any time; the cost follows what changed, as in the demo above. To keep the index fresh on a schedule, run cocoindex update from cron.
Query the index
Searching mirrors indexing: embed the query with the same model, then ask Postgres for the nearest vectors. The <=> operator is pgvector’s cosine distance, so smaller means more similar:
async def query_once(pool, embedder, query: str, *, top_k: int = 5) -> None:
query_vec = await embedder.embed(query)
async with pool.acquire() as conn:
rows = await conn.fetch(
"""
SELECT product_category, product_name, description, amount,
total_value, embedding <=> $1 AS distance
FROM "coco_examples_v1"."output"
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['product_category']} | {r['product_name']} | {r['amount']} | {r['total_value']}"
)
print(f" {r['description']}")
print("---")
The pool here must encode numpy arrays as pgvector values, so main.py creates it with asyncpg.create_pool(DATABASE_URL, init=register_vector) (from pgvector.asyncpg).
Ask in plain language:
python main.py "quiet on a long flight"
The headphones come first, though the query shares no word with the row. These are the top 3 of the 5 results, with the example’s sample data:
[0.220] Electronics | Wireless Headphones | 50 | 9999.5
High-quality wireless headphones with noise cancellation
---
[0.090] Electronics | Laptop | 15 | 19499.85
High-performance laptop for work and gaming
---
[0.045] Sports | Running Shoes | 60 | 7770.0
Lightweight running shoes for daily training
---
Because the vectors sit in the same database as the rows, you can mix meaning with filters in one query, for example WHERE total_value > 5000 ORDER BY embedding <=> $1.
Where to go next
The result is a semantic index over an existing Postgres table, updated by cocoindex update. To adapt it, swap the source for Amazon S3 or Azure Blob, swap the target for a vector database such as Qdrant, or pass the retrieved rows to an LLM. The pipeline stays incremental in each case.
Frequently asked questions
How do I use an existing PostgreSQL table as a source in CocoIndex?
Open the table with postgres.PgTableSource(pool, table_name="source_products", row_type=SourceProduct), then call .fetch_rows().items(...) to tag each row with a key and pass it to coco.mount_each. Passing row_type maps each database row straight into your dataclass. See Wire up the app.
How does incremental sync work with a Postgres source in CocoIndex v1?
It uses two layers of memoization. process_product is decorated with @coco.fn(memo=True), so an unchanged row skips it entirely. The embedder's embed() is memoized on the model and the text, so a row whose price changed re-runs the function but reuses its vector; only new or changed text reaches the model. A deleted source row has its output row removed. The Postgres source runs as a one-shot catch-up, so schedule cocoindex update from cron to keep the index fresh. See An update costs what changed.
How do I combine AI and non-AI transformations in one function?
Inside a single @coco.fn you compute plain fields and call the embedder side by side. The example derives total_value = price * amount with ordinary Python and builds a full_description by concatenating fields, then embeds that string with coco.use_context(EMBEDDER).embed(...). To CocoIndex both are transforms that derive an output field from the source row. See Transform and embed each row.
How do I store embeddings in Postgres with pgvector in CocoIndex v1?
Annotate the embedding field as Annotated[NDArray, EMBEDDER] on your output dataclass so CocoIndex infers the vector size, then mount the target with postgres.mount_table_target(...) and a TableSchema.from_class(OutputProduct, primary_key=[...]). CocoIndex creates and manages the target table: schema, idempotent upserts, and cleanup. See Wire up the app.
Can the source and target be different databases?
Yes. The lifespan provides two connection pools, and you set SOURCE_DATABASE_URL to read from a separate instance while writing to the one behind POSTGRES_URL. Leave them equal to use a single database for both. See Define the row shapes.
How do I run a semantic search query over the indexed Postgres table?
Embed the query with the same model, then run a SQL query that orders by pgvector's cosine distance operator (embedding <=> $1) and limits to the top matches. Smaller distance means more similar, and the example prints a similarity score of 1.0 - distance. See Query the index.
Build fresh context for your agents.
CocoIndex keeps derived data in sync with its sources. Only what changed re-runs.


