Skip to content

Retrieval and reranking

Find the passages most relevant to a question, with citations. Pagelore does not write the answer: pass the results to your own LLM. For the concepts, see Retrieval, Hybrid search, Small-to-big, Reranking, Query transformations and Knowledge graph.

Paths are relative to /api/v1. These endpoints are POST, but a read key is enough. The examples use BASE=http://localhost:8000/api/v1 and an API key in $KEY.

POST /projects/{project_id}/retrieve

Search one project.

POST /retrieve

Search several projects at once, with one ranking. It takes every field of the single-project request, plus:

Field Type
project_ids list of integers, 1 to 20 The projects to search. Required. A key limited to projects must be allowed all of them (else 403)

Scores from different projects can be compared, because every collection uses the configured embedding model. Projects that share a collection are searched together.

curl -X POST "$BASE/retrieve" -H "Authorization: Bearer $KEY" \
     -H 'Content-Type: application/json' \
     -d '{"project_ids": [1, 4], "query": "travel reimbursement limits", "mode": "hybrid"}'

Request body

JSON. All fields are optional except as noted under Rules.

Field Type Allowed values Default
query string 1 to 100000 characters The search text. It is embedded with the collection's model and / or matched against the keyword index, depending on mode
vector list of numbers at least 1, the embedding model's dimension A query vector made with the same model, instead of query (vector mode) or with it (hybrid mode). A wrong size gives 400
mode string vector, keyword, hybrid vector vector: semantic similarity of embeddings. keyword: Postgres full-text search ranked with BM25 (exact words, names, codes). hybrid: both lists fused into one ranking
top_k integer 1 to 100 5 Results to return
score_threshold number none Drop results scoring below it. The scale depends on the mode: vector, the backend's similarity (cosine for most, higher is closer); keyword, BM25 (unbounded); hybrid, the fused score
candidates integer 1 to 500, at least top_k chosen from top_k and the options Records fetched from each list (vector DB, keyword index) before filtering, de-duplicating and diversifying. By default 2 x top_k (at least top_k + 10); 4 x top_k (at least 40) when results are thinned afterwards (hybrid mode, diversity, max_per_document, page filters, small-to-big parents, several queries, graph); at least rerank_candidates + 10 when reranking; at most 500
filters object see Filters none Narrow the documents and pages searched
user object {id, groups} none Search only what this user may see; see Searching as a user. A key bound to a user always searches as that user

Hybrid and keyword

Field Type Allowed values Default
alpha number 0 to 1 0.5 Hybrid: the vector list's weight. The keyword list gets 1 - alpha. 1 is vectors only, 0 keywords only
fusion string rrf, relative_score rrf Hybrid: rrf adds weight / (rrf_k + rank) from each list (ranks only, robust). relative_score adds the weighted scores, each list scaled to 0 to 1
rrf_k integer 1 to 1000 60 Reciprocal rank fusion: higher values flatten the rank curve. Also used to fuse several queries and the graph
keyword_match string any, all any Keyword and hybrid. any: chunks with any query word, best BM25 first. all: web search syntax, where every word must appear, "quoted phrases" must appear as written, -word excludes, and OR gives alternatives

Results

Field Type Allowed values Default
neighbors integer 0 to 10 0 Add context to each result: the chunk with this many chunks before and after it, merged without repeating overlaps
diversity number 0 to 1 0 0 ranks by score only. Higher values trade relevance for variety (maximal marginal relevance)
max_per_document integer 1 or more none At most this many results from one document
dedupe boolean true Drop results whose text repeats a better one (ignoring case and spacing)
return_parents boolean true Small-to-big: for documents chunked with parent_chunk_size, return the parent of each matching chunk; chunks of one parent become one result. false returns the matching chunks themselves

Reranking

Field Type Allowed values Default
rerank boolean RERANK_BY_DEFAULT (false) Rescore the best candidates with the configured reranker (a cross-encoder) and order the results by its score. Needs a text query and a reranker (RERANKER_PROVIDER)
rerank_candidates integer 1 to 200, at least top_k 4 x top_k, at least 20, at most 100 How many of the best candidates the reranker scores. The rest are dropped
rerank_threshold number none Drop reranked results scoring below it, on the reranker's scale (0 to 1 for most rerank APIs)

query_transform

Have the configured LLM write better queries, search each of them, and fuse the result lists with reciprocal rank fusion. One LLM call writes them all. Needs LLM_PROVIDER (else 409). Unknown fields are refused.

Field Type Allowed values Default
kinds list of strings 1 to 6 of rewrite, multi_query, hyde, decompose, step_back, expand, without repeats required What to write; see below
history list of messages at most 20 [] The conversation the query follows, oldest first, so a follow-up such as "and its price?" can be searched. Used by rewrite. Each message is {"role": "user" or "assistant", "content": 1 to 20000 characters}
variants integer 1 to 10 3 multi_query: how many other phrasings
hypothetical_documents integer 1 to 5 1 hyde: how many hypothetical passages
max_sub_questions integer 1 to 10 4 decompose: the most sub-questions
include_original boolean true, or false when rewrite is used Also search the query as given
fallback boolean false If the LLM fails, search the query as given and add a warning, instead of failing with 502
Kind Writes Searched in
rewrite One standalone, search-ready query. It resolves references to the history, and replaces the query unless include_original the mode's indexes
multi_query variants other phrasings of the query the mode's indexes
hyde hypothetical_documents passages that could answer the query the vector index only (vector or hybrid mode)
decompose Up to max_sub_questions simple sub-questions of a multi-part question the mode's indexes
step_back A more general background question the mode's indexes
expand The key terms with synonyms and related terms the keyword index only (keyword or hybrid mode)

graph

Fuse a knowledge graph ranking into the results: a Personalized PageRank over the project's graph, seeded with the entities named in the query and the best search results, finds chunks tied to them. Send {} for the defaults. The project needs a built graph (POST .../graph/build); projects without one are skipped with a warning. Unknown fields are refused.

Field Type Allowed values Default
weight number more than 0, at most 10 1.0 The graph ranking's weight in the fusion with the search's ranking, which weighs 1
seed_chunks integer 0 to 50 1 How many of the search's best results seed the walk. Their entities lead to related chunks
entity_seeds boolean true Entities named in the query seed the walk too
hops integer 1 to 3 2 How far the walk reaches. Entity, then its chunks, then their entities is one hop
damping number 0.05 to 0.95 0.5 The chance of following an edge rather than jumping back to a seed. Higher reaches further

seed_chunks: 0 together with entity_seeds: false is refused: the walk needs seeds.

Filters

filters narrows what is searched. Conditions are combined with AND, and a list matches any of its items. Unknown fields are refused.

Field Type Allowed values
document_ids list of integers 1 to 10000 Only these documents
exclude_document_ids list of integers up to 10000 Never these documents
file_extensions list of strings 1 to 100 Such as ["pdf", "docx"]. Case and a leading dot are ignored
created_after datetime ISO 8601 Documents added at or after this time
created_before datetime ISO 8601, after created_after Documents added before this time
page_from integer 1 or more Chunks whose pages (or slides, sheets, ...) overlap this range. Chunks without page numbers are left out
page_to integer 1 or more, at least page_from
metadata object a metadata filter Documents whose metadata matches
sources list of strings at least 1 of upload, text, url, s3 Documents from these sources
external_ids list of strings 1 to 1000, each 1 to 2048 characters Documents with these external_ids, such as URLs

Rules

The request is refused (422) when:

  • In vector mode, it does not have exactly one of query and vector.
  • In keyword or hybrid mode, it has no query. keyword mode also refuses a vector.
  • candidates or rerank_candidates is less than top_k.
  • rerank: true is sent with a vector and no query.
  • rerank: false is sent with rerank_candidates or rerank_threshold.
  • query_transform is sent without a query, hyde is used in keyword mode, or expand in vector mode.
  • filters has page_from greater than page_to, or created_after not before created_before.

Response

  1. Fields that don't apply are left out (rather than sent as null).
Field Type
query string
mode string
project_ids list of integers
reranker object {provider, model}, when the results were reranked
query_transform object When the query was transformed; see below
graph object When the graph ranking was fused in; see below
results list The results, best first; see below
documents list One entry per document in the results; see below
stats object What the search did; see below
warnings list of strings For example, documents still being indexed, stale documents, a query with only stop words, or a project without a built graph

Each result

Field Type
rank integer From 1
score number The reranker's score when reranked, else the mode's retrieval score (or the fused score with several queries or the graph)
chunk_id integer The matching chunk. With a parent, the best of its matching chunks
project_id, document_id integer
file_name string
chunk_index integer
text string The chunk's text, or its parent's (small-to-big)
metadata object Where the text is: page_start, page_end, page_unit, titles, headings, start_time, end_time, row_start, row_end, char_start, char_end, ... A parent's also has chunk_start and chunk_end
citation string Ready to show, such as "report.pdf, pages 3-4, Methods > Data"
parent_id, parent_index integer Small-to-big: the parent returned as text
matches list Small-to-big: the parent's chunks that matched, best first: {chunk_id, chunk_index, score, text, metadata}
context string With neighbors: the chunk with its surrounding chunks
context_chunks list of 2 integers With neighbors: the first and last chunk_index in context
vector_score, vector_rank number, integer Hybrid: the score and rank in the vector list (left out if it was not in that list)
keyword_score, keyword_rank number, integer Hybrid: the BM25 score and rank (left out if no query word matched)
retrieval_score, retrieval_rank number, integer Reranked: the score and rank before reranking
query_ranks list With query_transform: {query, rank, score} for each query whose list had this chunk. query is the index in query_transform.queries
graph object With graph: {score, rank} in the graph's list, {base_score, base_rank} in the search's list (each left out when that list did not have it), and entities: the entities that tie the chunk to the query, {entity_id, name, type}, most relevant first

Each document

document_id, project_id, file_name, file_extension, mime_type, metadata (yours), document_metadata (from the file), source, source_uri, external_id, version, created_at, hits (results from it) and best_score.

stats

Field
candidates Records the vector DB and keyword index returned
vector_candidates, keyword_candidates Each list's share
keyword_terms The normalized query words the keyword index searched for (stemmed, stop words removed)
missing_chunk Records without a chunk row (deleted meanwhile, or not written by Pagelore)
filtered Dropped by the document and page filters
below_threshold Dropped by score_threshold
duplicate Dropped by dedupe
parent_merged Small-to-big: matching chunks folded into a better chunk's parent
reranked, rerank_ms Candidates the reranker scored, and how long it took
below_rerank_threshold Dropped by rerank_threshold
searches With query_transform: how many queries were searched. The counts above add them all up
took_ms The whole request

query_transform (response)

Field
kinds The kinds asked for
primary_query The query results are reranked against: the rewrite if there is one, else the query
queries What was searched: {index, kind, text, indexes}. kind is original or a transform kind; indexes is ["vector"], ["keyword"] or both
provider, model The LLM
input_tokens, output_tokens Tokens used
attempts LLM calls made. A reply that is not valid JSON is asked for again once
took_ms
error With fallback: why the LLM failed. Only the query as given was searched

graph (response)

Field
seed_entities Entities named in the query that seeded the walk
seed_chunks Chunk ids of the search results that seeded the walk
entities, chunks, edges, relations The size of the walked subgraph
ranked Chunks the graph ranked
graph_only Of the fused candidates, those only the graph found
took_ms

Errors

Status When
400 The query vector has the wrong size
403 The key can't use a project, or a key bound to a user sends another user or groups
404 A project does not exist, or its collection is gone
409 The project's index can't be searched with the configured vector DB and model (reindex), reranking was asked for without a reranker, or query_transform without an LLM
422 A field breaks the rules or its range, or a bad metadata filter
502 The embedding provider, reranker or LLM failed

Examples

The simplest search:

curl -X POST "$BASE/projects/1/retrieve" -H "Authorization: Bearer $KEY" \
     -H 'Content-Type: application/json' -d '{"query": "What is the refund policy?"}'
{
  "query": "What is the refund policy?",
  "mode": "vector",
  "project_ids": [1],
  "results": [
    {
      "rank": 1,
      "score": 0.83,
      "chunk_id": 912,
      "project_id": 1,
      "document_id": 31,
      "file_name": "terms.pdf",
      "chunk_index": 14,
      "text": "Refunds are issued within 14 days of a return...",
      "metadata": {"page_start": 6, "page_end": 6, "page_unit": "page", "headings": ["Payments", "Refunds"]},
      "citation": "terms.pdf, page 6, Payments > Refunds"
    }
  ],
  "documents": [
    {"document_id": 31, "project_id": 1, "file_name": "terms.pdf", "file_extension": ".pdf",
     "metadata": {}, "document_metadata": {"title": "Terms of sale"}, "source": "upload",
     "external_id": "terms.pdf", "version": 1, "hits": 1, "best_score": 0.83}
  ],
  "stats": {"candidates": 15, "vector_candidates": 15, "missing_chunk": 0, "filtered": 0,
            "below_threshold": 0, "duplicate": 0, "took_ms": 42.7},
  "warnings": []
}

Hybrid search with reranking, filters and surrounding text:

curl -X POST "$BASE/projects/1/retrieve" -H "Authorization: Bearer $KEY" \
     -H 'Content-Type: application/json' -d '{
  "query": "error code E-4012 after firmware update",
  "mode": "hybrid",
  "alpha": 0.4,
  "top_k": 8,
  "rerank": true,
  "rerank_candidates": 40,
  "neighbors": 1,
  "max_per_document": 3,
  "filters": {
    "file_extensions": ["pdf", "md"],
    "created_after": "2025-01-01T00:00:00Z",
    "metadata": {"product": {"$in": ["router-x", "router-x2"]}}
  }
}'

Exact-phrase keyword search:

curl -X POST "$BASE/projects/1/retrieve" -H "Authorization: Bearer $KEY" \
     -H 'Content-Type: application/json' \
     -d '{"query": "\"notice period\" -contractor", "mode": "keyword", "keyword_match": "all"}'

Search with a vector you computed (same model as the collection):

curl -X POST "$BASE/projects/1/retrieve" -H "Authorization: Bearer $KEY" \
     -H 'Content-Type: application/json' -d '{"vector": [0.012, -0.044, 0.031], "top_k": 3}'

A follow-up question in a chat, rewritten by the LLM, as a user:

curl -X POST "$BASE/projects/1/retrieve" -H "Authorization: Bearer $KEY" \
     -H 'Content-Type: application/json' -d '{
  "query": "and how many days for part-time staff?",
  "mode": "hybrid",
  "user": {"id": "ana@acme.com", "groups": ["staff"]},
  "query_transform": {
    "kinds": ["rewrite", "multi_query"],
    "variants": 2,
    "history": [
      {"role": "user", "content": "How much paid leave do we get?"},
      {"role": "assistant", "content": "Full-time staff get 25 days a year."}
    ],
    "fallback": true
  }
}'

With the knowledge graph:

curl -X POST "$BASE/projects/1/retrieve" -H "Authorization: Bearer $KEY" \
     -H 'Content-Type: application/json' -d '{
  "query": "Which trials did Dr. Rahman lead with Novagen?",
  "mode": "hybrid",
  "graph": {"weight": 1.0, "seed_chunks": 2, "hops": 2}
}'

POST /rerank

Score any texts against a query with the configured reranker, best first. Retrieval reranks its own candidates ("rerank": true); this endpoint is for texts from elsewhere. Needs a read key.

Body:

Field Type Allowed values Default
query string 1 to 100000 characters, not blank required
documents list of strings 1 to 1000, each 1 to 100000 characters, not blank required
top_n integer 1 or more all Return only the best top_n
return_documents boolean false Include each document's text in the results

Response: 200

Field
provider, model The reranker
results Best first: {index, score, document}. index is the position in documents; score is higher for more relevant, on the model's scale (0 to 1 for most rerank APIs); document only with return_documents

Errors: 409 when no reranker is configured, 422, 502 when the reranker fails.

curl -X POST "$BASE/rerank" -H "Authorization: Bearer $KEY" \
     -H 'Content-Type: application/json' -d '{
  "query": "how to reset the router",
  "documents": ["Hold the reset button for 10 seconds.", "Our offices close at 6 pm.",
                "Firmware updates are installed at night."],
  "top_n": 2,
  "return_documents": true
}'
{
  "provider": "cohere",
  "model": "rerank-v3.5",
  "results": [
    {"index": 0, "score": 0.97, "document": "Hold the reset button for 10 seconds."},
    {"index": 2, "score": 0.12, "document": "Firmware updates are installed at night."}
  ]
}

GET /rerank/model

The configured reranker.

Response: 200 with {provider, model, batch_size}. batch_size is the number of documents sent to the provider per request. 409 when no reranker is configured.

curl "$BASE/rerank/model" -H "Authorization: Bearer $KEY"