Rerankers¶
pgvectordb.rerankers
¶
Reranker Module for pgVectorDB¶
This module provides reranking backends that improve retrieval precision by scoring initial search results against the query using specialized models.
Why Reranking? Bi-encoder models (used for embeddings) are optimized for speed — they encode queries and documents independently. Cross-encoder/reranker models are slower but more accurate: they see both the query and document together, enabling richer comparisons.
Typical workflow
- Retrieve top-100 candidates quickly (semantic / hybrid / multimodal search)
- Rerank with a cross-encoder or API-based model
- Return top-5 or top-10 by rerank score
Supported backends:
| Class | Backend | Requires |
|---|---|---|
CrossEncoderReranker |
Local sentence-transformers | sentence-transformers |
CohereReranker |
Cohere API | cohere, API key |
AWSBedrockReranker |
AWS Bedrock | boto3, AWS credentials |
HuggingFaceReranker |
Local transformers pipeline | transformers, torch |
Examples:
>>> from pgvectordb.rerankers import CrossEncoderReranker, CohereReranker
>>>
>>> # Local cross-encoder (no API key needed)
>>> reranker = CrossEncoderReranker(
... model="cross-encoder/ms-marco-MiniLM-L-6-v2"
... )
>>>
>>> # Rerank via core method
>>> results = await rag.rerank_search(
... query="best noise cancelling headphones under $200",
... reranker=reranker,
... k=100, # Retrieve 100 candidates
... rerank_top_k=5, # Return best 5 after reranking
... )
Version: 0.0.3
Classes¶
BaseReranker
¶
Bases: ABC
Abstract base class for all reranking backends.
A reranker takes an initial list of search results and re-orders them by computing a relevance score for each (query, document) pair.
Subclass Contract
- Implement
rerank(query, documents, top_k) - Return results sorted by rerank score, descending
Examples:
>>> class MyReranker(BaseReranker):
... def rerank(self, query, documents, top_k=None):
... # Score each document
... scored = [(doc, my_score(query, doc)) for doc in documents]
... scored.sort(key=lambda x: x[1], reverse=True)
... return [(doc, score) for doc, score in scored[:top_k]]
Source code in pgvectordb\rerankers.py
Functions¶
rerank(query, documents, top_k=None)
abstractmethod
¶
Rerank a list of documents by relevance to the query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The search query string. |
required |
documents
|
List[Dict[str, Any]]
|
List of QueryResult-like dicts with at minimum
|
required |
top_k
|
Optional[int]
|
Maximum results to return. If None, returns all input docs (reordered). |
None
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
Documents re-ordered by rerank score (best first). |
List[Dict[str, Any]]
|
The |
Source code in pgvectordb\rerankers.py
CrossEncoderReranker
¶
Bases: BaseReranker
Local cross-encoder reranker using sentence-transformers.
Cross-encoders process query and document together, providing high accuracy at the cost of latency (no pre-computation possible).
Recommended models
cross-encoder/ms-marco-MiniLM-L-6-v2— Fast, good accuracy (~100ms/batch)cross-encoder/ms-marco-MiniLM-L-12-v2— Slower, better accuracycross-encoder/ms-marco-electra-base— Best accuracy, slowestBAAI/bge-reranker-v2-m3— Multilingualcross-encoder/nli-deberta-v3-small— General NLI (not search-tuned)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
HuggingFace model name or local path. |
'cross-encoder/ms-marco-MiniLM-L-6-v2'
|
device
|
Optional[str]
|
Device to run on ( |
None
|
batch_size
|
int
|
Documents to score per batch (default: 32). |
32
|
max_length
|
int
|
Max token length per (query, doc) pair (default: 512). |
512
|
Examples:
>>> reranker = CrossEncoderReranker(
... model="cross-encoder/ms-marco-MiniLM-L-6-v2"
... )
>>> results = reranker.rerank(query, candidates, top_k=5)
Source code in pgvectordb\rerankers.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | |
Functions¶
rerank(query, documents, top_k=None)
¶
Score each document using the cross-encoder and reorder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
Search query. |
required |
documents
|
List[Dict[str, Any]]
|
Initial search results. |
required |
top_k
|
Optional[int]
|
Number to return (default: all). |
None
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
Reordered documents with updated |
Source code in pgvectordb\rerankers.py
CohereReranker
¶
Bases: BaseReranker
Cloud reranker using the Cohere Rerank API.
Cohere's rerank endpoint is highly optimized for production use — no GPU required locally, and the API handles batching automatically.
Available models
rerank-english-v3.0— English-only, frontier modelrerank-multilingual-v3.0— Multiple languagesrerank-english-v2.0— Legacy English (cheaper)
Pricing: per 1K search units (query + top doc == 1 search unit)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api_key
|
Optional[str]
|
Cohere API key. If None, reads from |
None
|
model
|
str
|
Rerank model name (default: |
'rerank-english-v3.0'
|
max_chunks_per_doc
|
int
|
Max text chunks per document (default: 10). |
10
|
Examples:
>>> import os
>>> reranker = CohereReranker(api_key=os.environ["COHERE_API_KEY"])
>>> results = reranker.rerank(query, candidates, top_k=5)
Source code in pgvectordb\rerankers.py
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 | |
Functions¶
rerank(query, documents, top_k=None)
¶
Rerank using Cohere Rerank API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
Search query. |
required |
documents
|
List[Dict[str, Any]]
|
Initial search results. |
required |
top_k
|
Optional[int]
|
Number to return (default: all). |
None
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
Reordered documents with updated |
Source code in pgvectordb\rerankers.py
AWSBedrockReranker
¶
Bases: BaseReranker
Cloud reranker using AWS Bedrock's rerank endpoint (amazon.rerank-v1:0).
Uses the Amazon Bedrock rerank API, which wraps a hosted reranking model. Requires AWS credentials (via environment, IAM role, or profile).
Available models
amazon.rerank-v1:0— Amazon's primary reranking modelcohere.rerank-v3-5:0— Cohere v3.5 via Bedrock
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
region_name
|
str
|
AWS region (default: |
'us-east-1'
|
model_id
|
str
|
Bedrock model ID (default: |
'amazon.rerank-v1:0'
|
aws_access_key_id
|
Optional[str]
|
Optional, falls back to env/IAM. |
None
|
aws_secret_access_key
|
Optional[str]
|
Optional, falls back to env/IAM. |
None
|
aws_session_token
|
Optional[str]
|
Optional, for temporary credentials. |
None
|
Examples:
>>> reranker = AWSBedrockReranker(region_name="us-east-1")
>>> results = reranker.rerank(query, candidates, top_k=5)
Source code in pgvectordb\rerankers.py
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 | |
Functions¶
rerank(query, documents, top_k=None)
¶
Rerank using AWS Bedrock Rerank API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
Search query. |
required |
documents
|
List[Dict[str, Any]]
|
Initial search results. |
required |
top_k
|
Optional[int]
|
Number to return (default: all). |
None
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
Reordered documents with updated |
Source code in pgvectordb\rerankers.py
HuggingFaceReranker
¶
Bases: BaseReranker
Local reranker using HuggingFace transformers text-classification pipeline.
Any sequence-classification model that scores (query, document) pairs can be used here. This is the most flexible option for custom or fine-tuned models.
Recommended models
BAAI/bge-reranker-v2-m3— Strong multilingual rerankerBAAI/bge-reranker-base— Lighter versioncross-encoder/ms-marco-MiniLM-L-6-v2— Popular, fastjinaai/jina-reranker-v2-base-multilingual— Jina's multilingual model
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
HuggingFace model name or local path. |
'BAAI/bge-reranker-v2-m3'
|
device
|
Optional[str]
|
Device ( |
None
|
batch_size
|
int
|
Batch size for inference (default: 16). |
16
|
max_length
|
int
|
Max token length (default: 512). |
512
|
Examples:
>>> reranker = HuggingFaceReranker(
... model="BAAI/bge-reranker-v2-m3",
... device="cuda",
... )
>>> results = reranker.rerank(query, candidates, top_k=5)
Source code in pgvectordb\rerankers.py
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 | |
Functions¶
rerank(query, documents, top_k=None)
¶
Rerank documents using the local HuggingFace model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
Search query. |
required |
documents
|
List[Dict[str, Any]]
|
Initial search results. |
required |
top_k
|
Optional[int]
|
Number to return (default: all). |
None
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
Reordered documents with updated |
Source code in pgvectordb\rerankers.py
Functions¶
create_reranker(backend, **kwargs)
¶
Factory function to create a reranker by backend name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str
|
One of |
required |
**kwargs
|
Any
|
Arguments forwarded to the reranker constructor. |
{}
|
Returns:
| Type | Description |
|---|---|
BaseReranker
|
Configured reranker instance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If backend name is unknown. |
Examples:
>>> reranker = create_reranker("cross_encoder",
... model="cross-encoder/ms-marco-MiniLM-L-6-v2"
... )
>>> reranker = create_reranker("cohere", api_key="...", model="rerank-english-v3.0")
>>> reranker = create_reranker("bedrock", region_name="us-west-2")
>>> reranker = create_reranker("huggingface", model="BAAI/bge-reranker-v2-m3")