What Are Text Embeddings? Build Semantic Search in Python

Text embeddings 101: what an embedding is, how similarity works, why you chunk, and how to build a semantic search index with CocoIndex v1 and pgvector.

TutorialUpdated 8 min read
What are text embeddings? Semantic search in Python. The question how do I log back in? becomes 384 numbers through one model. Similarity to 3 sentences: recover your account access 0.527, the top hit with no shared words; write the error to the log file 0.265; today's lunch menu 0.146.
Enlarge cover

What Are Text Embeddings? Build Semantic Search in Python

Zoom in to see details.

What are text embeddings? Semantic search in Python. The question how do I log back in? becomes 384 numbers through one model. Similarity to 3 sentences: recover your account access 0.527, the top hit with no shared words; write the error to the log file 0.265; today's lunch menu 0.146.

Keyword search only finds the words you typed. Ask “how do I log back in?” and a page titled “recover your account access” never comes up, because it shares no words with your question. A page about log files does come up, because it contains “log”.

One question, 2 kinds of search. The question how do I log back in? asked of 3 sentences. Keyword search finds write the error to the log file, because it shares the word log, which is the wrong answer; it misses recover your account access, which shares 0 words; and it does not find today's lunch menu. Embedding search ranks recover your account access first with similarity 0.527, then write the error to the log file with 0.265, then today's lunch menu with 0.146. The answer ranks first with no word in common.
One question, 2 kinds of searchEnlarge

One question, 2 kinds of search

Zoom in to see details.

One question, 2 kinds of search. The question how do I log back in? asked of 3 sentences. Keyword search finds write the error to the log file, because it shares the word log, which is the wrong answer; it misses recover your account access, which shares 0 words; and it does not find today's lunch menu. Embedding search ranks recover your account access first with similarity 0.527, then write the error to the log file with 0.265, then today's lunch menu with 0.146. The answer ranks first with no word in common.

Semantic search matches on meaning, so a question finds its answer even when the words are different. This guide explains the 4 ideas behind it (embeddings, similarity, chunks and an index) and then builds a semantic search index over a folder of Markdown with CocoIndex v1 and Postgres. You do not need to know anything about embeddings to start.

Every number in the figures is real. We computed it for this post with the model the example uses, all-MiniLM-L6-v2, and the 3 sample files that come with the example: the Transformer paper (1706.03762v7.md), the BERT paper (1810.04805v2.md) and the JSON spec, RFC 8259 (rfc8259.md). The full code is in the CocoIndex v1 repo.

What is a text embedding?

An embedding is a list of numbers (a vector) that a model gives to a piece of text. The model is trained so that texts with similar meanings get similar lists. all-MiniLM-L6-v2 gives every text 384 numbers, whether it is 3 words or a full paragraph.

The phrase reset my password goes into the embedding model all-MiniLM-L6-v2 and comes out as 384 numbers, starting -0.034, -0.064, -0.042 and ending -0.097. Below, all 384 numbers are drawn as 1 bar each, up for positive and down for negative. One number alone means nothing a person can read; together they place the text at one point in a 384-dimensional space.
Text in, 384 numbers outEnlarge

Text in, 384 numbers out

Zoom in to see details.

The phrase reset my password goes into the embedding model all-MiniLM-L6-v2 and comes out as 384 numbers, starting -0.034, -0.064, -0.042 and ending -0.097. Below, all 384 numbers are drawn as 1 bar each, up for positive and down for negative. One number alone means nothing a person can read; together they place the text at one point in a 384-dimensional space.

No single number means “password” or “account”. The meaning is in the pattern of all 384 together. You can think of the list as coordinates: it puts the text at one point in a space with 384 directions. Texts about the same thing end up near each other in that space.

You cannot draw 384 directions, but you can flatten them to 2 with PCA (principal component analysis), which keeps the largest differences between the points. Here are 10 everyday phrases after that flattening:

A 2-D map of 10 phrases embedded with all-MiniLM-L6-v2 and flattened from 384 dimensions to 2 with PCA. 3 groups form. Logging in: the question how do I log back in?, reset my password, recover your account access and sign in to your account, all close together. Pets: my cat sleeps all day, kittens love to nap and dogs need a daily walk. Food: today's lunch menu, pizza for dinner tonight and fresh bread from the bakery. Positions are real model output; 2-D distances are approximate, and the search uses all 384 numbers.
A map of meaningEnlarge

A map of meaning

Zoom in to see details.

A 2-D map of 10 phrases embedded with all-MiniLM-L6-v2 and flattened from 384 dimensions to 2 with PCA. 3 groups form. Logging in: the question how do I log back in?, reset my password, recover your account access and sign in to your account, all close together. Pets: my cat sleeps all day, kittens love to nap and dogs need a daily walk. Food: today's lunch menu, pizza for dinner tonight and fresh bread from the bakery. Positions are real model output; 2-D distances are approximate, and the search uses all 384 numbers.

We gave the model no labels or groups. It still put “my cat sleeps all day” next to “kittens love to nap” (they share no words), and it put all the ways of saying “I can’t get into my account” next to the question.

How close is close?

Search needs a number for “how close”. The usual one is cosine similarity: it compares the directions of 2 vectors. 1 means the same direction, 0 means unrelated, and a value below 0 points the other way. This model scales every vector to length 1, so cosine similarity equals the dot product: multiply the 2 lists number by number and add the results.

Cosine similarity of each phrase to how do I log back in?, with distance = 1 minus similarity. log in 0.746, distance 0.254. sign in to your account 0.636, distance 0.364. reset my password 0.543, distance 0.457. recover your account access 0.527, distance 0.473. today's lunch menu 0.146, distance 0.854. fresh bread from the bakery 0.131, distance 0.869. my cat sleeps all day 0.046, distance 0.954. pizza for dinner tonight 0.015, distance 0.985. kittens love to nap -0.040, distance 1.040. dogs need a daily walk -0.058, distance 1.058. Phrases about logging in score 0.5 or more; reset my password and recover your account access share no word with the question.
Cosine similarityEnlarge

Cosine similarity

Zoom in to see details.

Cosine similarity of each phrase to how do I log back in?, with distance = 1 minus similarity. log in 0.746, distance 0.254. sign in to your account 0.636, distance 0.364. reset my password 0.543, distance 0.457. recover your account access 0.527, distance 0.473. today's lunch menu 0.146, distance 0.854. fresh bread from the bakery 0.131, distance 0.869. my cat sleeps all day 0.046, distance 0.954. pizza for dinner tonight 0.015, distance 0.985. kittens love to nap -0.040, distance 1.040. dogs need a daily walk -0.058, distance 1.058. Phrases about logging in score 0.5 or more; reset my password and recover your account access share no word with the question.

Postgres with the pgvector extension computes this for you. Its <=> operator returns the cosine distance, which is 1 minus the similarity, so a smaller distance means a closer match. A search is then: embed the question, sort the rows by distance, keep the first few.

Why split files into chunks?

Our sample files are long. The Transformer paper in the sample folder is 46,145 characters, which is 12,746 tokens (the word pieces a model reads). all-MiniLM-L6-v2 reads at most 256 tokens. If you embed the whole file as one text, the model uses the first 2% and drops the rest without a warning.

Why chunk, shown on 1706.03762v7.md, the Transformer paper: 46,145 characters and 12,746 tokens. Left, embed the whole file: the model reads the first 256 tokens and cuts off the other 12,490, so they have no effect on the 1 vector. Right, split into chunks: 31 chunks of up to about 2,000 bytes give 31 vectors, though each chunk is still cut at 256 tokens; chunk 12 is section 4, Why Self-Attention, with its own vector and its own search hit. Below, the first 3 chunks of rfc8259.md by character offset, 0 to 1,064, 739 to 2,652 and 2,604 to 3,997, overlap by 325 and 48 characters; chunk_overlap=500 is the upper bound, and some neighbors do not overlap.
Why chunkEnlarge

Why chunk

Zoom in to see details.

Why chunk, shown on 1706.03762v7.md, the Transformer paper: 46,145 characters and 12,746 tokens. Left, embed the whole file: the model reads the first 256 tokens and cuts off the other 12,490, so they have no effect on the 1 vector. Right, split into chunks: 31 chunks of up to about 2,000 bytes give 31 vectors, though each chunk is still cut at 256 tokens; chunk 12 is section 4, Why Self-Attention, with its own vector and its own search hit. Below, the first 3 chunks of rfc8259.md by character offset, 0 to 1,064, 739 to 2,652 and 2,604 to 3,997, overlap by 325 and 48 characters; chunk_overlap=500 is the upper bound, and some neighbors do not overlap.

Even a model with a longer input limit gives a file only 1 vector. A paper about many things gets 1 point somewhere between all of them, and a question about one section has to match that average. When you split the file into chunks and embed each chunk, every passage gets its own point, and the search can return the exact passage that answers the question.

The example uses CocoIndex’s RecursiveSplitter. With language="markdown" it picks split points from the Markdown structure, and it aims for chunks of about 2,000 bytes (for English text, about 2,000 characters). Neighboring chunks can overlap by up to 500 bytes, so text near a boundary often appears in both. The 3 sample files give 106 chunks.

The pipeline: 3 files in, 106 rows out

The index is a short pipeline: read the files, split each one into chunks, embed each chunk, and store one row per chunk in Postgres.

The pipeline: 3 files in, 106 rows out. markdown_files/, 3 .md files, read with localfs.walk_dir; process_file, 1 per file, memo=True; RecursiveSplitter with chunk_size=2000 and chunk_overlap=500; process_chunk, 1 per chunk, which embeds and calls declare_row; doc_embeddings in Postgres with pgvector, 106 rows. process_file, the splitter and process_chunk form one processing component per file, mounted with coco.mount_each. Counts: 3 files, 3 components, 106 chunks (31 + 50 + 25), 106 embeddings, 106 rows.
The pipelineEnlarge

The pipeline

Zoom in to see details.

The pipeline: 3 files in, 106 rows out. markdown_files/, 3 .md files, read with localfs.walk_dir; process_file, 1 per file, memo=True; RecursiveSplitter with chunk_size=2000 and chunk_overlap=500; process_chunk, 1 per chunk, which embeds and calls declare_row; doc_embeddings in Postgres with pgvector, 106 rows. process_file, the splitter and process_chunk form one processing component per file, mounted with coco.mount_each. Counts: 3 files, 3 components, 106 chunks (31 + 50 + 25), 106 embeddings, 106 rows.

Keeping the index correct is the hard part

You could write this pipeline as a plain loop, and it would embed every file once. Keeping the index correct as files change takes more code: on every run you must find what changed, embed only the new text, and make the table match.

Keeping the index correct is the hard part. By hand you write and maintain 5 jobs: find the files that changed since the last run; re-chunk them and find the chunks that are new; embed only the new chunks; insert and delete rows so the table matches; drop the rows of files that were deleted. With CocoIndex you write the transformation, target_state = transformation(source_state): process_file reads and splits into chunks, process_chunk embeds and calls declare_row, app_main says which files and which table. The engine does the 5 jobs on the left.
By hand vs CocoIndexEnlarge

By hand vs CocoIndex

Zoom in to see details.

Keeping the index correct is the hard part. By hand you write and maintain 5 jobs: find the files that changed since the last run; re-chunk them and find the chunks that are new; embed only the new chunks; insert and delete rows so the table matches; drop the rows of files that were deleted. With CocoIndex you write the transformation, target_state = transformation(source_state): process_file reads and splits into chunks, process_chunk embeds and calls declare_row, app_main says which files and which table. The engine does the 5 jobs on the left.

CocoIndex is declarative: you describe what the table should contain, not the steps to update it. You write the target as a function of the source, target_state = transformation(source_state), and its Rust engine keeps the 2 in sync. You write the transformation (chunk, embed, and declare the row each chunk should have). The engine detects changes, embeds only the text it has not seen, and applies the inserts and deletes, including cleanup when a file is removed.

Build it

Prerequisites

Clone the CocoIndex repo and work in examples/text_embedding; the commands below expect its main.py and markdown_files/ folder.

Install Postgres with the pgvector extension; that is where the embeddings live. Set the connection string:

sh
export POSTGRES_URL="postgres://cocoindex:cocoindex@localhost/cocoindex"

Install CocoIndex and the packages the example uses:

sh
pip install -U "cocoindex[postgres,sentence_transformers]" asyncpg pgvector numpy python-dotenv

Step 1: define the row

Each chunk becomes one row. A plain dataclass describes the columns. The embedding field is annotated with the embedder, so CocoIndex gets the vector size from the model:

main.py
import os
import pathlib
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

DATABASE_URL = os.getenv("POSTGRES_URL", "postgres://cocoindex:cocoindex@localhost/cocoindex")
EMBED_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
EMBEDDER = coco.ContextKey[SentenceTransformerEmbedder]("embedder", detect_change=True)

@dataclass
class DocEmbedding:
    id: int
    filename: str
    chunk_start: int
    chunk_end: int
    text: str
    embedding: Annotated[NDArray, EMBEDDER]

This is one real row from the sample files, the chunk that holds section 4 of the Transformer paper:

One chunk becomes one row. Field in DocEmbedding, Postgres column, value in this row: id int, bigint, from IdGenerator, stable across runs; filename str, text, 1706.03762v7.md; chunk_start int, bigint, 17982; chunk_end int, bigint, 19559; text str, text, ### 4 Why Self-Attention followed by In this section we...; embedding NDArray, vector(384), -0.040, -0.080, 0.081, -0.022 through -0.057. Annotated[NDArray, EMBEDDER] gives the size, 384, from the model; you do not write CREATE TABLE.
One rowEnlarge

One row

Zoom in to see details.

One chunk becomes one row. Field in DocEmbedding, Postgres column, value in this row: id int, bigint, from IdGenerator, stable across runs; filename str, text, 1706.03762v7.md; chunk_start int, bigint, 17982; chunk_end int, bigint, 19559; text str, text, ### 4 Why Self-Attention followed by In this section we...; embedding NDArray, vector(384), -0.040, -0.080, 0.081, -0.022 through -0.057. Annotated[NDArray, EMBEDDER] gives the size, 384, from the model; you do not write CREATE TABLE.

The database connection and the embedder are created once when the app starts (in the coco_lifespan function) and shared through context:

main.py
import asyncpg
from cocoindex.connectors import postgres

PG_DB = coco.ContextKey[asyncpg.Pool]("text_embedding_db")

@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))
        yield

detect_change=True on EMBEDDER tells CocoIndex to watch the embedder itself. If you change EMBED_MODEL, the next run embeds every chunk again with the new model.

Step 2: chunk and embed

process_chunk embeds one chunk and declares its row. process_file reads a file, splits it into chunks, and runs process_chunk on each one. memo=True turns on memoization: CocoIndex caches the result, and when a file’s content and the function’s code are unchanged, it skips the file on the next run.

main.py
from cocoindex.ops.text import RecursiveSplitter
from cocoindex.resources.chunk import Chunk
from cocoindex.resources.file import FileLike
from cocoindex.resources.id import IdGenerator

_splitter = RecursiveSplitter()

@coco.fn
async def process_chunk(
    chunk: Chunk,
    filename: pathlib.PurePath,
    id_gen: IdGenerator,
    table: postgres.TableTarget[DocEmbedding],
) -> None:
    table.declare_row(
        row=DocEmbedding(
            id=await id_gen.next_id(chunk.text),
            filename=str(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),
        ),
    )

@coco.fn(memo=True)
async def process_file(
    file: FileLike,
    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, id_gen, table)
Match chunk_size to your model

chunk_size=2000 comes from the upstream example. With all-MiniLM-L6-v2, most of those chunks are longer than 256 tokens (the median is 433 tokens in the sample files), so the model reads only the start of each one. A smaller chunk_size keeps more of each chunk inside the limit: at 1,000 bytes about 3 in 4 chunks of the sample files fit, and at 600 bytes almost all do. A model with a longer input limit can use larger chunks.

declare_row does not write to the database at once. It declares a target state, a row that should exist. CocoIndex compares the declared rows with the ones it declared on the last run and writes only the difference.

Step 3: wire up the app

app_main sets up (mounts) the Postgres table, adds a vector index so Postgres can find the closest vectors quickly, walks the folder of Markdown files, and runs one process_file per file:

main.py
from cocoindex.connectors import localfs
from cocoindex.resources.file import PatternFilePathMatcher

@coco.fn
async def app_main(sourcedir: pathlib.Path) -> None:
    table = await postgres.mount_table_target(
        PG_DB,
        table_name="doc_embeddings",
        table_schema=await postgres.TableSchema.from_class(DocEmbedding, primary_key=["id"]),
        pg_schema_name="coco_examples",
    )
    table.declare_vector_index(column="embedding")

    files = localfs.walk_dir(
        sourcedir,
        recursive=True,
        path_matcher=PatternFilePathMatcher(included_patterns=["**/*.md"]),
        live=True,
    )
    await coco.mount_each(process_file, files.items(), table)

app = coco.App(
    coco.AppConfig(name="TextEmbeddingV1"),
    app_main,
    sourcedir=pathlib.Path("./markdown_files"),
)

coco.mount_each gives each file its own processing component: a unit of work that CocoIndex runs, tracks and cleans up on its own. That is what lets CocoIndex update one file without touching the others.

Step 4: build the index

sh
cocoindex update main

The first run embeds all 106 chunks of the sample files. Add -L (cocoindex update -L main) to keep watching the folder and update the index as files change (live mode).

Query the index

Search mirrors indexing: embed the question with the same model, then ask Postgres for the nearest vectors. In main.py, the pool is created with asyncpg.create_pool(DATABASE_URL, init=register_vector) (from pgvector.asyncpg), so asyncpg can send a vector as a query parameter. A different model puts text in a different space, so its vectors cannot be compared with the stored ones.

main.py
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 filename, text, embedding <=> $1 AS distance
            FROM "coco_examples"."doc_embeddings"
            ORDER BY distance ASC
            LIMIT $2
            """,
            query_vec,
            top_k,
        )
    for r in rows:
        print(f"[{1.0 - float(r['distance']):.3f}] {r['filename']}")
        print(f"    {r['text']}")

Run it with a question in plain language:

sh
python main.py "what is self-attention?"
A search. The question what is self-attention? goes through all-MiniLM-L6-v2, the same model as indexing, then ORDER BY embedding <=> $1 LIMIT 5. The top 5 of 106 chunks by score, with the chunk's first line and where it is: 0.494, #### Attention Visualizations, 1706.03762v7.md 45126 to 46144; 0.445, ### 3.2.3 Applications of Attention in our Model, 13016 to 14977; 0.419, ### 4 Why Self-Attention, 17982 to 19559; 0.343, ## 2 Background, 4905 to 6513; 0.329, ### 3.2.1 Scaled Dot-Product Attention, 9743 to 11378. Score = 1 minus distance.
A searchEnlarge

A search

Zoom in to see details.

A search. The question what is self-attention? goes through all-MiniLM-L6-v2, the same model as indexing, then ORDER BY embedding <=> $1 LIMIT 5. The top 5 of 106 chunks by score, with the chunk's first line and where it is: 0.494, #### Attention Visualizations, 1706.03762v7.md 45126 to 46144; 0.445, ### 3.2.3 Applications of Attention in our Model, 13016 to 14977; 0.419, ### 4 Why Self-Attention, 17982 to 19559; 0.343, ## 2 Background, 4905 to 6513; 0.329, ### 3.2.1 Scaled Dot-Product Attention, 9743 to 11378. Score = 1 minus distance.

All 5 hits come from the Transformer paper, and none of them comes from the BERT paper or the JSON spec. The section 4 row from Step 1 is the third hit. We computed this ranking with the same model; <=> gives the same order, because distance is 1 minus similarity. With the vector index, Postgres may return a slightly different top 5, because that index finds nearest neighbors approximately.

A re-run redoes only what changed

Run cocoindex update main again and CocoIndex does only the work that the change needs:

What a re-run does, in 5 cases, with what CocoIndex does, the chunks embedded and the rows in Postgres. Nothing changed, dashed gray: process_file is skipped by a memo hit, 0 chunks embedded, rows unchanged. A new .md file, green: a new component runs for it, all of its chunks embedded, its rows added. One paragraph edited, periwinkle: the file is re-chunked and unchanged text hits the cache, only the changed chunks embedded, changed rows replaced and later rows get new offsets. A file deleted, red: its component is gone, 0 embedded, its rows deleted. EMBED_MODEL changed, periwinkle: detect_change=True invalidates the memos that read the embedder, all 106 embedded, every vector updated. A note says an edit changes the text of a few nearby chunks, and only those go to the model, because embed() is memoized by its text.
What a re-run doesEnlarge

What a re-run does

Zoom in to see details.

What a re-run does, in 5 cases, with what CocoIndex does, the chunks embedded and the rows in Postgres. Nothing changed, dashed gray: process_file is skipped by a memo hit, 0 chunks embedded, rows unchanged. A new .md file, green: a new component runs for it, all of its chunks embedded, its rows added. One paragraph edited, periwinkle: the file is re-chunked and unchanged text hits the cache, only the changed chunks embedded, changed rows replaced and later rows get new offsets. A file deleted, red: its component is gone, 0 embedded, its rows deleted. EMBED_MODEL changed, periwinkle: detect_change=True invalidates the memos that read the embedder, all 106 embedded, every vector updated. A note says an edit changes the text of a few nearby chunks, and only those go to the model, because embed() is memoized by its text.

2 mechanisms make this work. memo=True on process_file skips files that did not change. The embedder’s embed() is memoized too, so in an edited file only the chunks with new text go to the model. On the write side, each row’s id comes from IdGenerator.next_id(chunk.text), so a chunk with the same text keeps the same id across runs. Rows for chunks that are gone are deleted, new chunks are inserted, and rows whose text moved get their new offsets without a new embedding.

Where to go next

You now have the core of semantic search: chunk, embed, store, and query by nearest neighbor. The same pipeline can read from Amazon S3, Azure Blob or Google Drive instead of a local folder, write to a vector database such as Qdrant instead of Postgres, or pass the passages it finds to an LLM for RAG (retrieval-augmented generation: the LLM answers from the passages you retrieved). Because the pipeline is declarative and incremental, none of that changes how the index stays fresh.

For code instead of Markdown, Index your codebase uses the same flow with syntax-aware chunking.

Frequently asked questions

What is a text embedding, in plain terms?

An embedding is a list of numbers (a vector) that a model gives to a piece of text. The model is trained so that texts with similar meanings get similar lists. all-MiniLM-L6-v2 gives every text 384 numbers. Once every text is a point in that space, search embeds the question the same way and finds the stored points nearest to it, even when they share no words.

See What is a text embedding?.

How is similarity between 2 embeddings measured?

With cosine similarity, which compares the directions of 2 vectors: 1 means the same direction, 0 means unrelated. pgvector's <=> operator returns the cosine distance, 1 minus the similarity, so a smaller distance is a closer match. In the post, "recover your account access" scores 0.527 against "how do I log back in?" and "today's lunch menu" scores 0.146.

See How close is close?.

Why chunk documents before embedding them?

A model reads a limited number of tokens: all-MiniLM-L6-v2 reads 256, and the Transformer paper in the sample files has 12,746. A whole file would also get only 1 vector for many topics. Splitting it into chunks gives every passage its own vector, so search can return the passage that answers the question. The example chunks Markdown with RecursiveSplitter at chunk_size=2000 and chunk_overlap=500; with this model, a smaller chunk_size keeps more of each chunk inside the 256-token limit (at 1,000 bytes, about 3 in 4 chunks of the sample files fit).

See Why split files into chunks?.

How do I build a text embedding index with CocoIndex v1?

Walk the files with localfs.walk_dir and mount one component per file with coco.mount_each. Each component splits the file with RecursiveSplitter, embeds each chunk with SentenceTransformerEmbedder, and calls declare_row to store the text and its vector in a Postgres pgvector table mounted with postgres.mount_table_target. Add declare_vector_index for fast nearest-neighbor search.

See Build it.

Which embedding model does this use, and how big are the vectors?

sentence-transformers/all-MiniLM-L6-v2, which turns any text into 384 numbers and runs locally with no API key. You can use another SentenceTransformer model by changing EMBED_MODEL; detect_change=True then makes the next run embed every chunk again. The same model must embed both the indexed chunks and the search question, so the vectors are comparable.

See What is a text embedding?.

Why use CocoIndex instead of writing the pipeline by hand?

Embedding once takes a loop. Keeping the index correct as documents change needs change detection, partial re-embedding and row cleanup. By hand you would find which files changed, embed only the new chunks, and insert or delete rows to match, on every run. CocoIndex is declarative: you write the transform (chunk → embed → declare_row), and the engine detects changes, embeds only text it has not seen, and syncs the table, including cleanup when a file is deleted.

See Keeping the index correct is the hard part and A re-run redoes only what changed.

How do I query the embedding index?

Embed the question with the same model, then ask Postgres for the nearest vectors: ORDER BY embedding <=> $1 LIMIT 5. Run python main.py "what is self-attention?" and you get the closest chunks by meaning, with a score of 1 minus the 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.