popoto.fields.indexed_field_mixin¶
popoto.fields.indexed_field_mixin
¶
Indexed Field Mixin - Secondary Indexing for Non-Key Fields¶
This module provides the IndexedFieldMixin class, which enables exact-match secondary indexing on fields that are NOT part of the model's Redis key.
Design Philosophy¶
KeyField conflates two concerns: identity (forming the Redis storage key) and indexing (enabling queries). IndexedFieldMixin decouples these by providing Set-based indexing without making the field part of the Redis key (identity).
This allows developers to query on fields like email, status, or
category without making them part of the model's identity.
The implementation follows the exact same pattern as KeyFieldMixin:
- on_save(): Maintains a Redis Set at $IndexF:Model:field_name:value
- on_delete(): Removes from the Set
- filter_query(): Uses SMEMBERS/SUNION for lookups
- get_filter_query_params(): Declares supported query lookups
Index Key Pattern¶
$IndexF:ModelName:field_name:value -> Set of redis_keys
This mirrors the $KeyF pattern used by KeyFieldMixin but uses the
$IndexF prefix (auto-generated by FieldBase metaclass via field_class_key).
Usage¶
from popoto import Model, Field
from popoto.fields.shortcuts import IndexedField, UniqueField
class User(Model):
user_id = AutoKeyField()
email = UniqueField(type=str) # indexed + unique
status = IndexedField(type=str) # indexed, not unique
# Efficient exact-match queries without making email a KeyField
User.query.filter(email="alice@example.com")
User.query.filter(status="active")
User.query.filter(status__in=["active", "pending"])
IndexedFieldMixin
¶
Mixin that provides Set-based secondary indexing for non-key fields.
When mixed with Field, this mixin maintains Redis Sets that track which model instances have a given value for the indexed field. This enables efficient exact-match queries without making the field part of the model's Redis key (identity).
Supports the same query lookups as KeyFieldMixin:
- Exact match: filter(field=value)
- IN queries: filter(field__in=[v1, v2])
- Null checks: filter(field__isnull=True/False)
- Pattern matching: filter(field__startswith="prefix")
- Pattern matching: filter(field__endswith="suffix")
Uniqueness enforcement is available via unique=True. The check is
performed server-side inside the atomic INDEX_SWAP_LUA script, eliminating
the classic check-then-act race condition.
When an external pipeline is provided, a best-effort pre-check is made before queuing the EVAL. The authoritative uniqueness guarantee is only enforced at pipeline.execute() time, when the Lua script runs atomically on the server.
Attributes:
| Name | Type | Description |
|---|---|---|
indexed |
bool
|
Always True for indexed fields. |
Source code in src/popoto/fields/indexed_field_mixin.py
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 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 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 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 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 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 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 | |
on_save(model_instance, field_name, field_value, pipeline=None, **kwargs)
classmethod
¶
Maintain the secondary index Set when a model instance is saved.
Internal path (no pipeline): queues INDEX_SWAP_LUA into an internal MULTI/EXEC pipeline. The Lua script atomically reads the old-set pointer from the model hash, removes the member from the old Set, enforces uniqueness (if configured), SADD to the new Set, and writes the server-authoritative pointer and field bytes — all as a single Redis command. No separate round-trips; no race window.
External path (pipeline provided): performs a best-effort SMEMBERS pre-check for fast early raise on uniqueness violation, then queues the EVAL into the caller's pipeline. The authoritative guarantee is enforced at execute() time when the Lua script runs on the server. The pre-check reduces latency for the common conflict case but cannot close the TOCTOU window because the caller controls execute().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_instance
|
Model
|
The Model instance being saved. |
required |
field_name
|
str
|
The name of this field on the model. |
required |
field_value
|
The value being saved for this field. |
required | |
pipeline
|
Pipeline
|
Optional Redis pipeline for batched operations. When provided, EVAL is queued into the caller's pipeline. When omitted, an internal pipeline is used for atomicity. |
None
|
Returns:
| Type | Description |
|---|---|
|
The pipeline (if provided) or 1 (EVAL result from internal pipeline). |
Raises:
| Type | Description |
|---|---|
ModelException
|
If unique=True and the value is already taken by a different instance. Raised immediately on the internal path; raised at execute() time on the external path. |
Source code in src/popoto/fields/indexed_field_mixin.py
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 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 434 | |
on_delete(model_instance, field_name, field_value, pipeline=None, **kwargs)
classmethod
¶
Remove the model instance from the index Set on delete.
Uses the server-authoritative pointer side key (#476) — if present — to determine which value-Set to SREM from. Falls back to the legacy pre-#476 in-hash pointer field (for records written before this fix shipped), then to a field_value-derived key for records that predate any pointer at all.
Important: this reads live Redis state (GET/HGET), so it must be called BEFORE the model hash itself is deleted — see Model.delete() in base.py, which now runs field.on_delete() hooks ahead of the hash DELETE for exactly this reason (#476 latent bug: reading the pointer after the hash was already gone always returned nothing, silently falling back to a possibly-stale in-memory snapshot).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_instance
|
Model
|
The Model instance being deleted. |
required |
field_name
|
str
|
The name of this field on the model. |
required |
field_value
|
The value stored for this field. |
required | |
pipeline
|
Pipeline
|
Optional Redis pipeline for batched operations. |
None
|
Returns:
| Type | Description |
|---|---|
|
The pipeline (if provided) or the SREM result. |
Source code in src/popoto/fields/indexed_field_mixin.py
get_filter_query_params(field_name)
¶
Return the set of valid query parameter names for filtering on this field.
Supports the same lookups as KeyFieldMixin: - exact match - __in - __isnull - __startswith - __endswith
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field_name
|
str
|
The name of this field on the model. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
set |
set
|
Valid query parameter strings. |
Source code in src/popoto/fields/indexed_field_mixin.py
filter_query(model, field_name, **query_params)
classmethod
¶
Execute a filter query on this indexed field and return matching Redis keys.
Uses Set-based lookups for exact match and __in queries. Falls back to SCAN for pattern queries (__startswith, __endswith).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Model
|
The Model class being queried. |
required |
field_name
|
str
|
The name of this field on the model. |
required |
**query_params
|
Dict mapping query parameter names to values. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
set |
set
|
Redis keys (as bytes) of matching model instances. |
Raises:
| Type | Description |
|---|---|
QueryException
|
If __isnull receives a non-boolean value. |
Source code in src/popoto/fields/indexed_field_mixin.py
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 | |