Spaces¶
pgvectordb.spaces
¶
Vector Spaces Module for pgVectorDB¶
This module defines vector space abstractions for multi-embedding support. Each space encodes a different data modality (text, numbers, categories, timestamps) into a fixed-size vector, enabling multimodal search with weighted fusion.
Inspired by
- Superlinked's "mixture of encoders": https://superlinked.com/vectorhub/articles/why-do-not-need-re-ranking
- Real Estate NLQ agent: https://superlinked.com/vectorhub/articles/real-estate-nlq-agent
Space Types
- TextSpace: Embeds text fields using a LangChain embedding model.
- NumberSpace: Encodes numeric fields via min-max normalization.
- CategorySpace: Encodes categorical fields as one-hot vectors.
- RecencySpace: Encodes timestamps via exponential time-decay.
Examples:
>>> from pgvectordb.spaces import TextSpace, NumberSpace, CategorySpace
>>> spaces = [
... TextSpace(name="description", field="content"),
... NumberSpace(name="price", field="price", min_value=0, max_value=1000000,
... mode="minimum"),
... CategorySpace(name="city", field="city",
... categories=["New York", "San Francisco", "Chicago"]),
... ]
>>> rag.register_spaces(spaces)
>>> await rag.add_documents_multimodal(docs)
>>> results = await rag.multimodal_search(
... query_params={"description": "modern downtown apartment", "price": 500000,
... "city": "New York"},
... weights={"description": 0.5, "price": 0.3, "city": 0.2},
... k=10,
... )
Version: 0.0.3
Classes¶
NumberMode
¶
Bases: str, Enum
Mode for NumberSpace encoding direction.
Determines how numeric values are scored relative to a query value.
Attributes:
| Name | Type | Description |
|---|---|---|
MINIMUM |
Lower values are better (e.g., price — cheaper is better). Distance increases as value moves above the query. |
|
MAXIMUM |
Higher values are better (e.g., rating — higher is better). Distance increases as value moves below the query. |
|
SIMILAR |
Values closest to query are best (e.g., temperature, square footage). Distance increases in both directions from the query. |
Examples:
>>> price_space = NumberSpace(
... name="price", field="price",
... min_value=0, max_value=1000000,
... mode=NumberMode.MINIMUM # Prefer lower prices
... )
Source code in pgvectordb\spaces.py
TimeUnit
¶
Bases: str, Enum
Time unit for RecencySpace decay period.
Determines the granularity of the exponential decay. The decay
time-constant τ is computed as period_value × unit.to_seconds().
Attributes:
| Name | Type | Description |
|---|---|---|
SECOND |
1 second. |
|
MINUTE |
60 seconds. |
|
HOUR |
3 600 seconds. |
|
DAY |
86 400 seconds. |
|
WEEK |
604 800 seconds. |
Examples:
>>> recency = RecencySpace(
... name="updated", field="updated_at",
... time_unit=TimeUnit.DAY, period_value=7 # weekly decay
... )
Source code in pgvectordb\spaces.py
VectorSpace
¶
Bases: ABC
Abstract base class for all vector spaces.
A vector space defines how a specific data field is encoded into a fixed-size embedding vector. Multiple spaces can be registered on a single collection, enabling multimodal search with dynamic query-time weights.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Unique space name. Used as column suffix: |
|
field |
Source data field name. Use |
|
dimensions |
int
|
Output vector dimensionality. |
Subclass Contract
- Implement
encode(value)to convert a field value to a vector. - Implement
encode_query(value)to convert a query parameter to a vector. - Set
dimensionsin__init__.
Examples:
>>> class MyCustomSpace(VectorSpace):
... def __init__(self, name, field, dims):
... super().__init__(name=name, field=field)
... self._dimensions = dims
... @property
... def dimensions(self): return self._dimensions
... def encode(self, value): return [0.0] * self._dimensions
... def encode_query(self, value): return self.encode(value)
Source code in pgvectordb\spaces.py
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 207 208 209 210 211 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 | |
Attributes¶
dimensions
abstractmethod
property
¶
Output vector dimensionality.
column_name
property
¶
The PostgreSQL column name for this space's embedding.
Returns:
| Type | Description |
|---|---|
str
|
Column name in the format |
index_name_suffix
property
¶
Suffix for the index name on this space's column.
Returns:
| Type | Description |
|---|---|
str
|
Index suffix in the format |
Functions¶
__init__(name, field)
¶
Initialize a vector space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique identifier for this space. Must be a valid SQL identifier
(alphanumeric + underscores, no spaces). This becomes the column
suffix: |
required |
field
|
str
|
The document field to encode. Use |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If name is empty or contains invalid characters. |
Source code in pgvectordb\spaces.py
encode(value)
abstractmethod
¶
Encode a document field value into a vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
The raw field value from the document. |
required |
Returns:
| Type | Description |
|---|---|
List[float]
|
Fixed-size float vector of length |
Source code in pgvectordb\spaces.py
encode_query(value)
abstractmethod
¶
Encode a query parameter value into a vector.
For many spaces, this is identical to encode(). However, some spaces
(like NumberSpace with directional modes) may encode queries differently
than document values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
The query parameter value. |
required |
Returns:
| Type | Description |
|---|---|
List[float]
|
Fixed-size float vector of length |
Source code in pgvectordb\spaces.py
extract_value(document)
¶
Extract the relevant field value from a LangChain Document.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
document
|
Any
|
A LangChain Document object. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The field value, or None if not found. |
Source code in pgvectordb\spaces.py
TextSpace
¶
Bases: VectorSpace
Embed text fields using a LangChain embedding model.
This space uses the collection's configured embedding model (or a separate
model) to convert text into dense semantic vectors. It supports both
document page_content and metadata text fields.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Space identifier (column suffix). |
|
field |
Source field — |
|
model |
Optional separate embedding model. If None, uses the collection's default model. |
|
_dimensions |
Detected embedding dimensions (set on first use). |
Examples:
>>> # Embed the document content
>>> desc_space = TextSpace(name="description", field="content")
>>>
>>> # Embed a metadata field with a separate model
>>> from langchain_community.embeddings import HuggingFaceEmbeddings
>>> title_space = TextSpace(
... name="title", field="title",
... model=HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
... )
Source code in pgvectordb\spaces.py
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 309 310 311 312 313 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 | |
Attributes¶
dimensions
property
¶
Embedding dimensionality.
Returns:
| Type | Description |
|---|---|
int
|
The dimension count, or 0 if not yet detected. |
Functions¶
__init__(name, field='content', model=None, dimensions=None)
¶
Initialize a text embedding space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique space name (becomes |
required |
field
|
str
|
Document field to embed. |
'content'
|
model
|
Optional[Any]
|
Optional LangChain Embeddings model. If None, the collection's
default |
None
|
dimensions
|
Optional[int]
|
Embedding dimensions. If None, auto-detected on first encode. |
None
|
Source code in pgvectordb\spaces.py
detect_dimensions(embedding_model)
¶
Auto-detect dimensions by embedding a test string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embedding_model
|
Any
|
LangChain Embeddings model to use for detection. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Detected dimension count. |
Source code in pgvectordb\spaces.py
encode(value, embedding_model=None)
¶
Encode text into an embedding vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Text string to embed. If None or empty, returns a zero vector. |
required |
embedding_model
|
Optional[Any]
|
Fallback model if this space has no dedicated model. |
None
|
Returns:
| Type | Description |
|---|---|
List[float]
|
Embedding vector of length |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no embedding model is available. |
Source code in pgvectordb\spaces.py
encode_query(value, embedding_model=None)
¶
Encode a search query into an embedding vector.
For text spaces, query encoding is identical to document encoding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Query text string. |
required |
embedding_model
|
Optional[Any]
|
Fallback model if no dedicated model is set. |
None
|
Returns:
| Type | Description |
|---|---|
List[float]
|
Embedding vector of length |
Source code in pgvectordb\spaces.py
NumberSpace
¶
Bases: VectorSpace
Encode numeric fields into normalized vectors using min-max scaling.
Numbers are mapped to the [0, 1] range based on configured min/max bounds.
The mode parameter controls how the value is encoded for distance calculation:
- MINIMUM: For fields where lower is better (e.g., price). The encoding ensures that values below the query score closer.
- MAXIMUM: For fields where higher is better (e.g., rating). The encoding ensures that values above the query score closer.
- SIMILAR: For fields where closest-to-query is best (e.g., square footage).
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Space identifier (column suffix). |
|
field |
Metadata field name containing the numeric value. |
|
min_value |
Minimum expected value (maps to 0.0). |
|
max_value |
Maximum expected value (maps to 1.0). |
|
mode |
Encoding mode — MINIMUM, MAXIMUM, or SIMILAR. |
Examples:
>>> price_space = NumberSpace(
... name="price", field="price",
... min_value=0, max_value=2000000,
... mode=NumberMode.MINIMUM # Cheaper is better
... )
>>>
>>> rating_space = NumberSpace(
... name="rating", field="rating",
... min_value=0, max_value=5,
... mode=NumberMode.MAXIMUM # Higher is better
... )
Source code in pgvectordb\spaces.py
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 434 435 436 437 438 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 | |
Attributes¶
dimensions
property
¶
Output vector dimensionality (usually 1).
Functions¶
__init__(name, field, min_value=0.0, max_value=1.0, mode=NumberMode.SIMILAR, dimensions=1)
¶
Initialize a numeric encoding space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique space name (becomes |
required |
field
|
str
|
Metadata field name containing the numeric value. |
required |
min_value
|
float
|
Minimum expected value. Values below this are clamped. |
0.0
|
max_value
|
float
|
Maximum expected value. Values above this are clamped. |
1.0
|
mode
|
Union[NumberMode, str]
|
Encoding direction — |
SIMILAR
|
dimensions
|
int
|
Output dimensions (default 1). Higher dimensions can improve indexing separation but increase storage. |
1
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If min_value >= max_value or dimensions < 1. |
Source code in pgvectordb\spaces.py
encode(value)
¶
Encode a numeric document value into a vector.
The value is normalized to [0, 1] based on min/max bounds, then expanded to the configured number of dimensions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Numeric value (int or float). None defaults to 0. |
required |
Returns:
| Type | Description |
|---|---|
List[float]
|
Normalized vector of length |
Source code in pgvectordb\spaces.py
encode_query(value)
¶
Encode a query parameter value for search.
For NumberSpace, query encoding normalizes the value to match the document encoding scheme.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Query numeric value. None defaults to midpoint. |
required |
Returns:
| Type | Description |
|---|---|
List[float]
|
Normalized query vector of length |
Source code in pgvectordb\spaces.py
CategorySpace
¶
Bases: VectorSpace
Encode categorical fields as one-hot vectors.
Each category maps to a unique dimension. If the document's category matches, that dimension is 1.0, otherwise 0.0. Unknown categories get a zero vector.
This enables fuzzy categorical matching via cosine similarity — when a query specifies a category, exact matches get score 1.0, and with negative filtering, non-matching categories are pushed away.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Space identifier (column suffix). |
|
field |
Metadata field name containing the category value. |
|
categories |
List of valid categories (defines dimensionality). |
|
negative_filter |
Score assigned to non-matching categories.
|
Examples:
>>> city_space = CategorySpace(
... name="city", field="city",
... categories=["New York", "San Francisco", "Chicago", "Austin"],
... negative_filter=-1.0, # Strongly penalize wrong cities
... )
Source code in pgvectordb\spaces.py
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 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 | |
Attributes¶
dimensions
property
¶
Dimensionality equals the number of categories.
Functions¶
__init__(name, field, categories, negative_filter=0.0, uncategorized_as_zero=True)
¶
Initialize a categorical encoding space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique space name (becomes |
required |
field
|
str
|
Metadata field name containing the category string. |
required |
categories
|
List[str]
|
List of valid category values. Dimension = len(categories). |
required |
negative_filter
|
float
|
Score for non-matching dimensions. Use |
0.0
|
uncategorized_as_zero
|
bool
|
If True, unknown categories encode as zero vector. If False, unknown categories raise ValueError. |
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If categories list is empty or has duplicates. |
Source code in pgvectordb\spaces.py
encode(value)
¶
Encode a category value as a one-hot vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Category string. None or unknown → zero vector (or error). |
required |
Returns:
| Type | Description |
|---|---|
List[float]
|
One-hot vector of length |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in pgvectordb\spaces.py
encode_query(value)
¶
Encode a query category. Same as document encoding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Category string to search for. |
required |
Returns:
| Type | Description |
|---|---|
List[float]
|
One-hot query vector. |
RecencySpace
¶
Bases: VectorSpace
Encode timestamps into vectors using exponential time-decay.
Recent documents score close to 1.0; older documents decay towards 0.0.
The decay follows score = exp(-age / τ) where τ = period_value ×
time_unit.to_seconds().
This enables time-aware multimodal search — boost fresh content without post-retrieval re-ranking.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Space identifier (column suffix). |
|
field |
Metadata field containing the timestamp. |
|
time_unit |
Granularity of the decay period. |
|
period_value |
Number of time units for the decay constant τ. |
|
tau |
Precomputed decay constant in seconds. |
Decay behaviour
- age = 0 → score ≈ 1.0 (fresh)
- age = τ → score ≈ 0.37
- age = 3τ → score ≈ 0.05
.. warning::
encode() uses the wall-clock time at invocation as "now". This
means stored embeddings become stale over time. Re-encode periodically
or compute recency at query time for accuracy.
Examples:
>>> recency = RecencySpace(
... name="published", field="published_at",
... time_unit=TimeUnit.DAY, period_value=7,
... )
>>> # Document published 1 day ago scores ~0.87
>>> # Document published 7 days ago scores ~0.37
Source code in pgvectordb\spaces.py
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 | |
Attributes¶
dimensions
property
¶
Output vector dimensionality (usually 1).
Functions¶
__init__(name, field, time_unit=TimeUnit.DAY, period_value=1.0, dimensions=1)
¶
Initialize a recency (time-decay) space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique space name (becomes |
required |
field
|
str
|
Metadata field containing the timestamp. Accepts ISO-8601
strings, |
required |
time_unit
|
Union[TimeUnit, str]
|
Time granularity for the decay period. |
DAY
|
period_value
|
float
|
Number of |
1.0
|
dimensions
|
int
|
Output vector dimensions (default 1). |
1
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If period_value ≤ 0 or dimensions < 1. |
Source code in pgvectordb\spaces.py
encode(value)
¶
Encode a document timestamp into a time-decay vector.
score = exp(-age_seconds / τ) where age is measured from now.
Future timestamps are clamped to 1.0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Timestamp (datetime, ISO string, or Unix epoch).
|
required |
Returns:
| Type | Description |
|---|---|
List[float]
|
Vector of length |
Source code in pgvectordb\spaces.py
encode_query(value=None)
¶
Encode a query value for recency search.
If value is None (the typical case), returns [1.0] —
meaning "prefer the freshest documents". If a specific timestamp is
provided, it is encoded the same way as a document timestamp.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
|
None
|
Returns:
| Type | Description |
|---|---|
List[float]
|
Query vector of length |
Source code in pgvectordb\spaces.py
Functions¶
validate_spaces(spaces)
¶
Validate a list of vector spaces for consistency.
Checks
- At least one space defined
- No duplicate space names
- All dimensions are positive (where detectable)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spaces
|
List[VectorSpace]
|
List of VectorSpace instances. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If validation fails. |
Source code in pgvectordb\spaces.py
get_total_dimensions(spaces)
¶
Get the total dimensions across all spaces.
Note: TextSpace dimensions may be 0 until detect_dimensions() is called.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spaces
|
List[VectorSpace]
|
List of VectorSpace instances. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Sum of all space dimensions. |
Source code in pgvectordb\spaces.py
encode_document_spaces(document, spaces, embedding_model=None)
¶
Encode a single document across all registered spaces.
Extracts the relevant field from the document for each space and encodes it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
document
|
Any
|
A LangChain Document object. |
required |
spaces
|
List[VectorSpace]
|
List of VectorSpace instances. |
required |
embedding_model
|
Optional[Any]
|
Default embedding model for TextSpaces without a dedicated model. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Dict[str, List[float]]
|
Dictionary mapping column names to embedding vectors. |
|
Example |
Dict[str, List[float]]
|
|
Source code in pgvectordb\spaces.py
encode_query_spaces(query_params, spaces, embedding_model=None)
¶
Encode query parameters across all relevant spaces.
Only encodes spaces whose names are present in query_params.
Spaces not in query_params are skipped (not included in search).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query_params
|
Dict[str, Any]
|
Dictionary mapping space names to query values.
Example: |
required |
spaces
|
List[VectorSpace]
|
List of VectorSpace instances. |
required |
embedding_model
|
Optional[Any]
|
Default embedding model for TextSpaces. |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, List[float]]
|
Dictionary mapping column names to query embedding vectors. |
Dict[str, List[float]]
|
Only includes spaces present in |