# Build a retrieval index

> **About this page**
>
> - Kind: Example
> - Summary: Splits PDFs into text chunks with Docling, embeds them with Text Embeddings Inference, stores them as a Parquet index, and answers a test query.
> - Last changed: 2026-12-03
> - Page: https://docs.swale.io/examples/retrieval-index
> - CLI reference for its commands: [`swale workflow create`](https://docs.swale.io/reference/cli-reference.md#workflow-create), [`swale workflow run start`](https://docs.swale.io/reference/cli-reference.md#workflow-run-start)
> - Index of these docs: https://docs.swale.io/llms.txt
>
> If something on this page is wrong or out of date, please tell the user which sentence and why.
>
> The steps on this page cost money or cannot be undone. Please check with the user before running them.

Source on GitHub: the [`workflows/retrieval-index`](https://github.com/swaleio/examples/tree/main/workflows/retrieval-index) folder, with its [README](https://github.com/swaleio/examples/blob/main/workflows/retrieval-index/README.md) and its [workflow file](https://github.com/swaleio/examples/blob/main/workflows/retrieval-index/workflow.yaml).

Builds the index a retrieval-augmented generation (RAG) application searches.
Each PDF is fetched and split into chunks of text by Docling, all PDFs at the
same time; Text Embeddings Inference embeds every chunk; DuckDB stores chunks
and vectors in one Parquet file; and a test query is answered from it with
cosine similarity, to show the index works.

| Step | Task definition | Compute |
|------|-----------------|---------|
| For each PDF: fetch it | [`swaleio/http-request`](https://hub.swale.io/swaleio/http-request) | `cpu-4` |
| For each PDF: convert it to chunks | [`swaleio/docling`](https://hub.swale.io/swaleio/docling) | `cpu-4` |
| Serve the embedding model, as a runner | [`swaleio/tei-serve`](https://hub.swale.io/swaleio/tei-serve) | `a100-1` |
| Wait for the server, checking every 5 seconds | [`swaleio/http-request`](https://hub.swale.io/swaleio/http-request) | `cpu-4` |
| Embed the chunks, 32 per request | [`swaleio/python-3-13`](https://hub.swale.io/swaleio/python-3-13) | `cpu-4` |
| Embed the test query | [`swaleio/http-request`](https://hub.swale.io/swaleio/http-request) | `cpu-4` |
| Write `index.parquet`, count chunks per document | [`swaleio/duckdb`](https://hub.swale.io/swaleio/duckdb) | `cpu-4` |
| Find the five chunks closest to the query | [`swaleio/duckdb`](https://hub.swale.io/swaleio/duckdb) | `cpu-4` |
| Upload the index, when `hub_repo` is set | [`swaleio/hf-upload`](https://hub.swale.io/swaleio/hf-upload) | `cpu-4` |

The Compute column gives each step's [compute type](https://docs.swale.io/explanation/core-concepts.md#compute-types), the compute its tasks are allocated.

Every step is its own task. The embedding client is a short Python script inside
the workflow that uses only the standard library. Docling counts each chunk's
tokens with a tokenizer it downloads from the Hugging Face Hub.

## Inputs

| Input | Default | Description |
|-------|---------|-------------|
| `pdf_urls` | three papers from arXiv | The PDFs, as a JSON array of URLs. |
| `model` | `BAAI/bge-small-en-v1.5` | Embedding model; the query must be embedded with the same one. |
| `query` | a question about Docling's tables | A question to test the index with; leave double quotes out of it. |
| `hub_repo` | empty | Hugging Face dataset repo to upload the index to, as `data/train.parquet`. |

The upload reads the secret `hf_token`.

## Output

`index.parquet` on the workspace, with `url`, `chunk`, `text` and `embedding`
for every chunk. The five closest chunks to the query are in the search task's
log.

## Run it

You need the CLI, logged in to your account, and a project to add the workflow to; [Getting started](https://docs.swale.io/getting-started.md) sets them up.

1. Save the file under [The workflow file](#the-workflow-file) as `workflow.yaml`, and add it to a project:

   ```bash
   swale workflow create --project-name my-project --file workflow.yaml
   ```

   The command prints `Workflow created:` followed by the workflow's ID.

2. The workflow reads the secret `hf_token`. Create it as a project secret, or as an account secret that allows the project, as [Use secrets in workflows](https://docs.swale.io/how-to-guides/use-secrets-in-workflows.md) shows.

3. Start a run with the workflow's ID:

   ```bash
   swale workflow run start --project-name my-project --workflow-id <workflow-id>
   ```

   Each input you leave out takes its default from [Inputs](#inputs), and `--input <name>=<value>` gives it another value.

[Create and manage workflows](https://docs.swale.io/how-to-guides/create-and-manage-workflows.md) covers the other ways to add a workflow, [Start and manage workflow runs](https://docs.swale.io/how-to-guides/start-and-manage-workflow-runs.md) how to follow a run, and [View and stream task logs](https://docs.swale.io/how-to-guides/view-and-stream-task-logs.md) how to read its tasks' logs.

## The workflow file

[Workflow definition syntax](https://docs.swale.io/reference/workflow-definition-syntax.md) describes each key in it.

```yaml title="workflow.yaml"
name: Build a retrieval index
description: Splits PDFs into text chunks with Docling, embeds them with Text Embeddings Inference, stores them as a Parquet index, and answers a test query.
compute_type: cpu-4

inputs:
  pdf_urls:
    description: The PDFs to index, as a JSON array of URLs.
    default: '["https://arxiv.org/pdf/2408.09869v5", "https://arxiv.org/pdf/2501.17887v1", "https://arxiv.org/pdf/2305.14314v1"]'
  model:
    description: Hugging Face repo id of the embedding model.
    default: BAAI/bge-small-en-v1.5
  query:
    description: A question to test the index with.
    default: How does Docling recognize the structure of tables?
  hub_repo:
    description: Hugging Face dataset repo to upload the index to, as namespace/name. Leave empty to keep it on the workspace only.
    default: ""

entry_point: main

blocks:
  main:
    tasks:
      each_pdf:
        name: Chunk each PDF
        for_each:
          items: ${{inputs.pdf_urls}}
          block: chunk_one

      serve:
        name: Serve the embedding model
        uses: swaleio/tei-serve
        compute_type: a100-1
        terminate_on:
          - embed_chunks
          - embed_query
        args:
          model: ${{inputs.model}}

      wait_ready:
        name: Wait for the server
        uses: swaleio/http-request
        start_on:
          - serve
        args:
          url: http://${{tasks.serve.ip-address}}:8080/health
          retry: "360"
          retry_delay: "5"
          expected_status: "200"

      embed_chunks:
        name: Embed the chunks
        uses: swaleio/python-3-13
        start_on:
          - wait_ready
          - each_pdf
        args:
          script: |
            import glob, json, os, urllib.request

            storage = os.environ["WORKFLOW_STORAGE"]
            server = "http://${{tasks.serve.ip-address}}:8080/embed"
            chunks = []
            for path in sorted(glob.glob(f"{storage}/chunks/*.jsonl")):
                with open(path) as f:
                    chunks += [json.loads(line) for line in f if line.strip()]

            def embed(texts):
                body = json.dumps({"inputs": texts, "truncate": True}).encode()
                request = urllib.request.Request(server, body, {"Content-Type": "application/json"})
                with urllib.request.urlopen(request, timeout=300) as response:
                    return json.load(response)

            with open(f"{storage}/chunk-vectors.jsonl", "w") as out:
                for start in range(0, len(chunks), 32):
                    batch = chunks[start:start + 32]
                    for chunk, vector in zip(batch, embed([c["text"] for c in batch])):
                        out.write(json.dumps({"document": chunk["filename"], "chunk": chunk["chunk_index"],
                                              "text": chunk["text"], "embedding": vector}) + "\n")
            print(f"embedded {len(chunks)} chunks")

      embed_query:
        name: Embed the test query
        uses: swaleio/http-request
        start_on:
          - wait_ready
        args:
          url: http://${{tasks.serve.ip-address}}:8080/embed
          method: POST
          headers: |
            Content-Type: application/json
          body: '{"inputs": "${{inputs.query}}", "truncate": true}'
          expected_status: "200"
          response_path: ${{env.WORKFLOW_STORAGE}}/query-vector.json

      index:
        name: Write the index
        uses: swaleio/duckdb
        start_on:
          - embed_chunks
        args:
          sql: |
            CREATE TABLE sources AS
              SELECT unnest(from_json($$${{inputs.pdf_urls}}$$, '["VARCHAR"]')) AS url,
                     (generate_subscripts(from_json($$${{inputs.pdf_urls}}$$, '["VARCHAR"]'), 1) - 1)::VARCHAR AS document;
            CREATE TABLE chunks AS
              SELECT s.url, c.chunk, c.text, c.embedding::FLOAT[] AS embedding
              FROM read_json('${{env.WORKFLOW_STORAGE}}/chunk-vectors.jsonl',
                             columns = {'document': 'VARCHAR', 'chunk': 'INTEGER', 'text': 'VARCHAR', 'embedding': 'DOUBLE[]'}) c
              JOIN sources s USING (document)
              ORDER BY s.url, c.chunk;
            COPY chunks TO '${{env.WORKFLOW_STORAGE}}/index.parquet' (FORMAT parquet);
            SELECT url, count(*) AS chunks FROM chunks GROUP BY url ORDER BY url;

      search:
        name: Answer the test query
        uses: swaleio/duckdb
        start_on:
          - index
          - embed_query
        args:
          sql: |
            -- The server answers /embed with one vector per input, so the query's is the first.
            CREATE TABLE query AS
              SELECT json_extract(json, '$[0]')::FLOAT[] AS vector
              FROM read_json_objects('${{env.WORKFLOW_STORAGE}}/query-vector.json', format = 'unstructured');
            SELECT round(list_cosine_similarity(c.embedding, q.vector), 3) AS similarity,
                   c.url, c.chunk, left(replace(c.text, chr(10), ' '), 160) AS text
            FROM '${{env.WORKFLOW_STORAGE}}/index.parquet' c, query q
            ORDER BY similarity DESC LIMIT 5;

      publish:
        name: Upload when asked
        start_on:
          - search
        if:
          condition: ${{inputs.hub_repo}}
          true: upload

  chunk_one:
    tasks:
      fetch:
        name: Fetch PDF
        uses: swaleio/http-request
        args:
          url: ${{tasks.each_pdf.for_each.item}}
          expected_status: "200"
          response_path: ${{env.WORKFLOW_STORAGE}}/pdf/${{tasks.each_pdf.for_each.index}}.pdf
      chunk:
        name: Convert to chunks
        uses: swaleio/docling
        start_on:
          - fetch
        args:
          source: ${{env.WORKFLOW_STORAGE}}/pdf/${{tasks.each_pdf.for_each.index}}.pdf
          output_dir: ${{env.WORKFLOW_STORAGE}}/chunks
          to: chunks

  upload:
    tasks:
      upload_index:
        name: Upload to the Hugging Face Hub
        uses: swaleio/hf-upload
        args:
          repo: ${{inputs.hub_repo}}
          repo_type: dataset
          source: ${{env.WORKFLOW_STORAGE}}/index.parquet
          path_in_repo: data/train.parquet
          token: ${{secrets.hf_token}}
```

## Licenses of the defaults

- Embedding model: [BAAI/bge-small-en-v1.5](https://huggingface.co/BAAI/bge-small-en-v1.5), MIT.
- Chunking tokenizer: [sentence-transformers/all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2), Apache-2.0.
- Documents: three arXiv papers licensed CC BY 4.0 by their authors, listed in the [PDFs to Markdown](https://docs.swale.io/examples/pdfs-to-markdown.md) workflow. An index of them keeps their attribution.
