Search API¶
Search projects manager data into a backend index and exposes configured searches through GraphQL. Begin with the search model and setup tutorial. Use reconciliation to initialize or repair persistent indexes; GraphQL authorization below explains how indexed hits become permitted application results. Direct backend searches do not perform that GraphQL authorization step.
general_manager.search re-exports the configuration types, backend protocol and data/error types, backend registry helpers, SearchIndexer, and concrete backend classes listed in the public API snapshot. Reconciliation, task, async task, registry, and utility helpers are public through their canonical submodules shown below, but they are not re-exported from general_manager.search.
general_manager.search.config.FieldConfig dataclass ¶
Describe a searchable field and its optional boost weight.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Manager attribute name serialized into search documents. | required |
boost | float | None | Optional positive search boost for this field. | None |
Raises:
| Type | Description |
|---|---|
InvalidFieldBoostError | If |
ReservedDocumentFieldNameError | If |
general_manager.search.config.IndexConfig dataclass ¶
Describe how a manager contributes documents to a search index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Search index name. | required |
fields | Sequence[str | FieldConfig] | Searchable field names or | required |
filters | Sequence[str] | Field names allowed for backend filtering. | tuple() |
sorts | Sequence[str] | Field names allowed for backend sorting. | tuple() |
boost | float | None | Optional positive index-level boost. | None |
min_score | float | None | Optional non-negative minimum relevance score. | None |
identity_fields | Mapping[str, type] | Native scalar kinds ( | dict() |
Raises:
| Type | Description |
|---|---|
InvalidIndexBoostError | If |
InvalidIndexMinScoreError | If |
ReservedDocumentFieldNameError | If any configured field, filter, or sort name collides with the search document envelope. |
iter_fields ¶
iter_fields()
Normalize this index's field entries into FieldConfig objects.
String entries are converted to FieldConfig(name=entry). FieldConfig entries are returned unchanged. The returned tuple preserves original field order.
Returns:
| Type | Description |
|---|---|
tuple[FieldConfig, ...] | Normalized field configuration objects. |
Raises:
| Type | Description |
|---|---|
InvalidFieldBoostError | If converting a string entry somehow creates an invalid field config. Existing |
field_boosts ¶
field_boosts()
Map configured field names to their boost values.
Returns:
| Type | Description |
|---|---|
dict[str, float] | Mapping of field name to boost for fields with explicit boosts. |
dict[str, float] | Duplicate field names keep the last boosted entry in |
general_manager.search.config.SearchConfigProtocol ¶
Bases: Protocol
Structural protocol for manager-level search configuration.
document_id and to_document receive the manager instance being indexed. document_id must return a stable document id string. to_document must return a mapping of document field names to arbitrary payload values. invalidation_rules declares source managers and optional owner relations whose changes may invalidate documents from this manager. field_dependencies asserts complete native sources, including property, filter-only and sort-only dependencies. Native projections also retain their actual serialized field gates. Arbitrary serializer/property accesses remain trusted application code covered by this declaration.
general_manager.search.config.SearchConfigSpec dataclass ¶
Resolved configuration from a manager's SearchConfig class.
Attributes:
| Name | Type | Description |
|---|---|---|
indexes | tuple[IndexConfig, ...] | Required tuple of configured search indexes; there is no constructor default. |
invalidation_rules | tuple[SearchInvalidationRule, ...] | Frozen declarative related-data invalidation rules. |
document_id | Callable[[GeneralManager], str] | None | Optional callable receiving a manager instance and returning a stable document id string. |
type_label | str | None | Optional searchable type label; registries fall back to the manager class name when omitted. |
to_document | Callable[[GeneralManager], Mapping[str, object]] | None | Optional callable receiving a manager instance and returning a mapping of document field names to payload values. |
update_strategy | str | None | Optional backend/indexer strategy marker. |
field_dependencies | Mapping[str, tuple[str, ...]] | None | Complete native source paths for each configured document field, including filter-only and sort-only fields. This trusted application assertion covers every serializer branch; it does not assert equality with source values. Missing declarations keep custom projections and opaque native properties unavailable to GraphQL. Native fields cannot relabel away their own gate. An omitted custom key may use the native fallback only if declared. |
general_manager.search.config.SearchChange dataclass ¶
One source-manager lifecycle phase presented to an invalidation resolver.
general_manager.search.config.SearchInvalidationRule dataclass ¶
Declare how one source manager invalidates documents owned by another.
general_manager.search.config.resolve_search_config ¶
resolve_search_config(config)
Normalize a search configuration object into a SearchConfigSpec.
If config is None, returns None. If config is already a SearchConfigSpec, returns it unchanged. Otherwise, extracts indexes, invalidation_rules, document_id, type_label, to_document, and update_strategy plus field_dependencies attributes from config, using default values when attributes are missing. Missing indexes and invalidation_rules resolve to empty tuples. Dependency mappings are copied into immutable tuple-valued snapshots; invalid declarations raise ValueError. Native paths are additionally checked at GraphQL query time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | object | None | Configuration object or resolved spec to normalize. | required |
Returns:
| Type | Description |
|---|---|
SearchConfigSpec | None | A resolved spec, or |
Notes
This helper does not validate that document_id or to_document are callable and does not validate the element type of indexes; invalid values fail later where the indexer, registry, or startup checks use them. Missing optional attributes default to None. Attribute access errors from unusual config objects propagate.
general_manager.search.config.iter_index_names ¶
iter_index_names(config)
Return index names from a resolved search config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | SearchConfigSpec | None | Resolved search configuration or | required |
Returns:
| Type | Description |
|---|---|
Iterable[str] | A list of index names in the same order as |
Iterable[str] | list when |
FieldConfig and IndexConfig validate numeric boost/min-score bounds and reject the reserved document-envelope names id, gm_document_id, type, identification, data, gm_identity, and gm_numeric_tokens at construction time. FieldConfig.boost and IndexConfig.boost must be positive when provided; IndexConfig.min_score must be non-negative when provided. IndexConfig.iter_fields() converts plain string field entries to FieldConfig(name=...) while preserving field order, and field_boosts() keeps only explicit field boosts.
SearchConfig.field_dependencies is an optional mapping from configured document keys to nonempty sequences of exact native source paths. Resolution freezes it as a mapping of tuples. For GraphQL search, custom to_document projections and native properties require complete provenance for every configured searchable, filterable, and sortable key. It is a trusted application assertion covering all branches and indirect reads, not an assertion that output values equal source values. Native projections always authorize their actual serialized fields in addition to the declared paths. Custom native fallback fields must be included in their own dependencies; terminal relations may instead declare every native identity leaf serialized by that fallback. Invalid or incomplete provenance fails before backend search. Declared dependencies contribute to the index's schema fingerprint, so the existing reconciliation pipeline handles declaration changes. Indexes without declarations retain their previous fingerprint. See projection dependencies.
SearchInvalidationRule declares a source manager whose lifecycle changes can invalidate search documents owned by the manager containing the rule. Sources may be manager classes or dotted import paths; dotted paths remain unchanged in the frozen declaration and are resolved lazily by startup validation. Optional indexes select a non-empty subset of the owner's configured indexes. Optional relation names a supported owner-side many-to-many relation. Resolver callbacks receive a frozen SearchChange and the owner manager class. Resolved configurations normalize invalidation_rules to a tuple, defaulting to an empty tuple.
SearchChange exposes action ("create", "update", or "delete"), phase ("before" or "after"), the source manager instance, and its database_alias. Create invokes resolvers after the mutation, update invokes them before and after, and delete invokes them before. Resolver results must be instances of the owner manager. The framework copies each result's identification before scheduling it. resolve=None, resolver errors, invalid targets, and bounded overflow mark the selected owner/index pairs dirty without dispatching partial targeted work.
GENERAL_MANAGER["SEARCH_INVALIDATION_MAX_TARGETS"] is the per-event resolver ceiling and defaults to 1000. GENERAL_MANAGER["SEARCH_INVALIDATION_BATCH_SIZE"] controls exact-index task chunks and defaults to 100. Each must be a positive, non-boolean integer; invalid values force dirty fallback for the affected work. The standard GeneralManager setting lookup order also permits legacy prefixed and top-level settings.
Relation bindings support auto-created and custom Django through models when the owner has exactly the id input and both through foreign keys target their endpoint primary keys. Startup checks use these IDs:
general_manager.search.E000: invalid declaration/configuration;E001: source does not resolve to a manager;E002: resolver is not callable;E003: selected indexes are invalid;E004/E005: owner/source is not ORM-backed;E006: relation is not the expected owner M2M field;E007: owner does not use exactly the standardidinput;E008: relation is self-symmetrical;E009: a through foreign key does not target the endpoint primary key.
The M2M bridge observes related-manager add, remove, clear, and set signals in forward and reverse directions. It does not observe direct through model writes, raw SQL, or bulk operations. These are unsupported and require explicit reconciliation.
SearchConfigSpec.document_id is a callable that receives the manager instance being indexed and returns a stable document id string. The same value is captured before deletion, so applications must keep it stable across updates and related invalidation. SearchConfigSpec.to_document receives the manager instance and returns a mapping of document field names to payload values. SearchConfigSpec.indexes is required when constructing the spec directly. resolve_search_config() copies indexes, document_id, type_label, to_document, update_strategy, and invalidation_rules attributes from arbitrary config objects; missing indexes and invalidation_rules attributes become empty tuples and missing optional attributes become None. It does not validate that callable attributes are callable or that every indexes entry is an IndexConfig; invalid values fail later when the registry or indexer uses them. Attribute access errors from unusual config objects propagate. iter_index_names() returns a concrete list of names, or an empty list for None.
general_manager.search.registry.SearchIndexSettings dataclass ¶
Aggregated index settings derived from manager configurations.
Attributes:
| Name | Type | Description |
|---|---|---|
searchable_fields | tuple[str, ...] | Search document field names in first-seen order. |
filterable_fields | tuple[str, ...] | Alphabetically sorted filterable field names, including the synthetic |
sortable_fields | tuple[str, ...] | Alphabetically sorted sortable field names. |
field_boosts | Mapping[str, float] | Highest configured boost per field name. |
general_manager.search.registry.iter_searchable_managers ¶
iter_searchable_managers()
Iterate manager classes that define at least one search index.
Yields:
| Type | Description |
|---|---|
Iterable[type[GeneralManager]] | Manager classes from |
Iterable[type[GeneralManager]] |
|
Iterable[type[GeneralManager]] | preserving |
Raises:
| Type | Description |
|---|---|
Exception | Errors from |
general_manager.search.registry.get_search_config ¶
get_search_config(manager_class)
Obtain the manager's configured search specification.
Returns:
| Type | Description |
|---|---|
SearchConfigSpec | None | The resolved |
SearchConfigSpec | None | manager does not define |
Raises:
| Type | Description |
|---|---|
Exception | Errors from |
general_manager.search.registry.get_index_config ¶
get_index_config(manager_class, index_name)
Return the first configured index matching index_name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
manager_class | type[GeneralManager] | Manager class whose search configuration is inspected. | required |
index_name | str | Index name to retrieve. | required |
Returns:
| Type | Description |
|---|---|
IndexConfig | None | The first matching |
IndexConfig | None | search config or no index with that name. |
Raises:
| Type | Description |
|---|---|
Exception | Errors from |
general_manager.search.registry.iter_index_configs ¶
iter_index_configs(index_name)
Yield manager/index pairs for every searchable manager declaring an index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Index name to search for across registered managers. | required |
Yields:
| Type | Description |
|---|---|
Iterable[tuple[type[GeneralManager], IndexConfig]] |
|
Iterable[tuple[type[GeneralManager], IndexConfig]] |
|
Iterable[tuple[type[GeneralManager], IndexConfig]] | order. |
Raises:
| Type | Description |
|---|---|
Exception | Errors from |
general_manager.search.registry.get_type_label ¶
get_type_label(manager_class)
Return the searchable type label for a manager class.
Returns:
| Type | Description |
|---|---|
str | The resolved |
str | manager class name. |
Raises:
| Type | Description |
|---|---|
Exception | Errors from |
general_manager.search.registry.get_searchable_type_map ¶
get_searchable_type_map()
Map searchable type labels to their manager classes.
Returns:
| Type | Description |
|---|---|
dict[str, type[GeneralManager]] | Mapping from a manager's searchable type label to its manager class. |
dict[str, type[GeneralManager]] | Only managers that define search indexes are included. If multiple |
dict[str, type[GeneralManager]] | managers resolve to the same type label, the later manager in |
dict[str, type[GeneralManager]] |
|
dict[str, type[GeneralManager]] | warning or error. |
Raises:
| Type | Description |
|---|---|
Exception | Errors from |
general_manager.search.registry.collect_index_settings ¶
collect_index_settings(index_name)
Collect aggregate field roles and boost values for an index name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Index name to collect settings for. | required |
Returns:
| Type | Description |
|---|---|
SearchIndexSettings | Aggregated settings. Searchable fields preserve first-seen order across |
SearchIndexSettings | matching manager configs. Filterable and sortable fields are sorted |
SearchIndexSettings | alphabetically. The synthetic |
SearchIndexSettings | Duplicate boosts keep the highest configured value; missing boosts do |
SearchIndexSettings | not create a field boost entry. Boosts are collected only from |
SearchIndexSettings |
|
SearchIndexSettings | included in |
Raises:
| Type | Description |
|---|---|
Exception | Errors from |
general_manager.search.registry.get_index_names ¶
get_index_names()
List all configured search index names across searchable managers.
Returns:
| Type | Description |
|---|---|
set[str] | Unique configured index name strings from every searchable manager. |
Raises:
| Type | Description |
|---|---|
Exception | Errors from |
general_manager.search.registry.get_filterable_fields ¶
get_filterable_fields(index_name)
Get filterable field names for the given index.
Returns:
| Type | Description |
|---|---|
set[str] | Field names allowed for filtering for the index, including the synthetic |
set[str] |
|
Raises:
| Type | Description |
|---|---|
Exception | Errors from |
general_manager.search.registry.validate_filter_keys ¶
validate_filter_keys(index_name, filters)
Ensure the provided filter keys are allowed for the specified index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Index name whose configured filterable fields are used for validation. | required |
filters | Mapping[str, object] | Mapping of filter keys to arbitrary values. Values are not inspected. Keys may include lookup suffixes separated by | required |
Raises:
| Type | Description |
|---|---|
InvalidFilterFieldError | If a base filter field is not configured as filterable for the given index. |
Exception | Errors from |
general_manager.search.registry.InvalidFilterFieldError ¶
Bases: ValueError
Raised when a filter field is not configured as filterable.
__init__ ¶
__init__(field_name, index_name)
Initialize the error for a filter field not allowed on an index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field_name | str | Name of the filter field that is not allowed. | required |
index_name | str | Name of the index for which the filter field is invalid. | required |
The search registry reads manager classes from GeneralManagerMeta.all_classes and resolves each manager's SearchConfig. Helpers skip managers without a search config or without indexes and preserve GeneralManagerMeta.all_classes order while iterating. Index lookup helpers return the first matching IndexConfig for a manager/index pair; duplicate type labels in get_searchable_type_map() are resolved by the later registered manager overwriting the earlier one without a warning or error. collect_index_settings() preserves searchable field first-seen order, sorts filterable and sortable fields, always includes the synthetic "type" filter, and keeps the highest configured boost per searchable field. Missing boosts do not create boost entries, and boosts are collected only from fields yielded by IndexConfig.iter_fields(). validate_filter_keys() validates only filter mapping keys, not values; lookup suffixes after the first "__" are ignored for the filterability check. Aside from InvalidFilterFieldError, registry helpers do not wrap search-configuration errors: malformed SearchConfig declarations raise whatever resolve_search_config() raises.
general_manager.search.models.SearchIndexState ¶
Bases: Model
Durable reconciliation state for one searchable manager/index pair.
manager_path stores the dotted import path for the manager class, index_name stores the logical search index, and schema_fingerprint records the last known schema hash for that pair. The reconciliation planner creates and updates fingerprints; this model only stores the value. Dirty fields drive reconciliation scheduling; claim fields are used by worker helpers to avoid processing the same dirty state concurrently.
mark_dirty ¶
mark_dirty(reason)
Mark this state as needing reconciliation.
The first dirty timestamp is recorded with timezone.now() and preserved so repeated marks keep the original age of the pending work. dirty_generation advances once per call and dirty_reason is overwritten with the provided string; callers should pass one of SEARCH_INDEX_DIRTY_REASON_INITIALIZATION, SEARCH_INDEX_DIRTY_REASON_SCHEMA_CHANGED, SEARCH_INDEX_DIRTY_REASON_DATA_CHANGED, or SEARCH_INDEX_DIRTY_REASON_FORCED because this method does not validate choices before saving.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reason | str | Stored dirty reason string. | required |
Raises:
| Type | Description |
|---|---|
Error | Database update errors propagate unchanged. |
DoesNotExist | The row was deleted before the updated fields could be refreshed. |
clear_dirty ¶
clear_dirty(*, claim_token, dirty_generation)
Record successful reconciliation when the claim fence still matches.
A single conditional update matches this row, claim_token, and dirty_generation. On a match, timestamps use timezone.now(), first success initializes initialized_at, last_reconciled_at advances, and dirty, claim, and error fields are cleared. A stale claim or generation leaves the row unchanged.
Returns:
| Type | Description |
|---|---|
bool |
|
Raises:
| Type | Description |
|---|---|
Error | Database save errors propagate unchanged. |
SearchIndexState is the durable reconciliation row for one (manager_path, index_name) pair. It stores the schema fingerprint, dirty-marker fields, worker claim fields, the latest reconciliation error, and timestamps. Its operational index names are declared explicitly to match the checked-in 0004_search_index_state.py migration and avoid no-op generated index-rename migrations.
general_manager.search.backend.SearchDocument dataclass ¶
Normalized document payload sent to search backends.
id is the stable backend document identifier used by upsert and delete; uniqueness is scoped to one backend index unless a concrete adapter documents broader constraints. type is the manager type label. identification is the manager reconstruction payload. index records the logical index the document was built for; indexer-managed calls pass the same value as the index_name argument used for backend writes. The protocol does not require adapters to reject mismatches between document.index and an index_name argument. data contains searchable/stored fields. field_boosts and index_boost are hints for adapters that support weighted matching. identity_fields maps explicit identity names to native scalar types (int, str, or UUID), including nullable/collection element types. It never coerces document values. The payload mappings, including identification, are not copied by the model; callers should treat them as immutable after handing them to a backend. Dataclass field annotations are the validation boundary; this model does not coerce or validate runtime values. frozen=True prevents attribute reassignment but does not make nested mappings immutable or guarantee practical hashability when fields contain unhashable values.
general_manager.search.identity.SearchIdentityFilterGroup ¶
Bases: dict[str, object]
A native-valued AND group with explicit identity and owner metadata.
Existing mapping consumers see the original keys and values. Builtin adapters honor the metadata for exact/in identity comparisons. type_label scopes a group when multiple manager contracts share an index.
general_manager.search.identity.build_search_filters ¶
build_search_filters(manager_class, index_name, filters)
Bind explicit manager/index provenance while keeping filter values native.
Explicit identity provenance travels separately from native document/filter values. SearchIndexer inherits actual ORM PK/reference metadata and @graph_ql_property(is_identifier=True) declarations for configured fields, including terminal identity fields in configured relation paths. IndexConfig.identity_fields={"customer_alias": int} declares aliases supplied by custom document mappers. Supported scalar types are int, str, and UUID; nullable/collection identities use the scalar element type. Unsupported types, unconfigured alias names, and overrides conflicting with manager metadata fail with general_manager.search.identity.SearchIdentityConfigurationError.
build_search_filters(manager_class, index_name, filters) returns dict-compatible native filter groups carrying identity types and the manager's type label. Caller keys, values, AND/OR group boundaries, and permission constraints remain unchanged. Generated GraphQL search attaches this metadata after merging native user and permission filters. For manual documents, provide both SearchDocument.identity_fields and a SearchIdentityFilterGroup; the latter's optional type_label scopes a shared index. These helpers are also re-exported from general_manager.search.
Index settings carry native contracts separately from ordinary configured filter names. For manual documents, configure their filterability explicitly:
backend.ensure_index("owned", {
"filterable_fields": ["type", "customer_alias"],
"identity_fields": {"Record": {"customer_alias": int}},
})
identity_fields in settings is keyed by document type label, so shared indexes retain each owner's native kinds. Meilisearch derives its shadow fields from declared names that are also filterable. Other backends receive original filterable_fields and can consume or ignore the additional native contracts. Document and filter metadata must agree on the native kind.
Generated GraphQL search authorization¶
When at least one registered manager has search configuration, GraphQL adds a global search field with the following public contract:
search(
query: String!
index: String
types: [String]
filters: JSONString
orderBy: [SearchOrderBy!]
totalMode: String
page: Int
pageSize: Int
): SearchResult
The result exposes results, total, totalIsExact, pageInfo, and tookMs. Omitted index, page, and pageSize use global, 1, and 10; non-positive page or pageSize values are BAD_USER_INPUT. totalMode is exact by default for compatibility or bounded when selected per request or by GENERAL_MANAGER["GRAPHQL_SEARCH_TOTAL_MODE"]. Both modes raise SEARCH_SCAN_LIMIT_EXCEEDED when the server-owned GRAPHQL_SEARCH_TOTAL_SCAN_LIMIT is exhausted before source exhaustion is established, including a full final backend page at the boundary. Neither returns partial results. Compatibility change: bounded mode no longer returns a partial count or page; totalIsExact remains in the schema and is always true on success. The positive candidate budget defaults to 1000 and is shared across selected manager types; denied and stale hits consume it too. A backend can explicitly attest exhaustion even on a full final page. An explicitly incomplete short or empty page never establishes an exact result.
The environment variable GENERAL_MANAGER_GRAPHQL_SEARCH_TOTAL_SCAN_LIMIT provides a positive-integer fallback when no explicit Django scan-limit setting is present. Existing nested, prefixed and top-level Django settings retain their precedence over the environment; the default remains 1000. Invalid environment values raise BAD_USER_INPUT. Restart application workers after deployment environment changes. Meilisearch's per-index pagination.maxTotalHits is an independent provider cap and is not changed by this variable.
orderBy is present when the registered searchable managers expose sortable fields; its SearchOrderBy input uses the generated sortable-field enum and ASC/DESC directions.
Schema construction classifies each manager/index projection from immutable definitions. Proven absence of additional relevant field restrictions enables fast routing; extra field restrictions and unknown/custom executable permission rules retain thorough checks. Rebuild the schema after restarting with changed definitions. This classification caches no user or object decisions.
All serialized search/filter/sort keys are authorized, even if unused by request operands. Only native DatabaseBucket sources with standard id identification use fast hit-batch hydration; calculation and remote sources retain full-domain checks and remote completeness requirements. Hits must match canonical authorized native instances. Missing or out-of-domain identities, malformed identification, and unexpected types are skipped. On fast related hits, denial of a referenced object removes the whole owner projection before count, sorting, and pagination; the thorough route raises on denied required operand access.
Every hit must supply stored SearchHit.data with exactly the configured searchable, filterable, and sortable keys. Missing stored data raises an error; extra or missing keys skip the hit pending reindexing, preventing removed restricted fields from influencing search. The separate indexing/invalidation pipeline owns value freshness, including obsolete content from former relation targets. Search does not reserialize documents or compare their values with current source values. Custom projection filters are not native permission pushdown because declared sources need not equal mapped values.
The synthetic type filter is removed from operand authorization unless the manager exposes an actual field named type; an actual field remains checked. The types argument selects manager classes, while type filter matching retains the backend's native semantics. Invalid configured filter keys and ordering terms are GraphQL errors. Backend, source authorization, permission, and sort errors propagate.
DevSearch honors explicit groups without changing its existing scalar/list comparison rules; plain mappings keep raw comparisons. Meilisearch binds plain structured filters to registered index/manager contracts, and explicit groups also work without registration. Its declared identity exact/in filters use bounded tokens under the reserved gm_identity envelope, preserving adjacent large integers, UUIDs, opaque text case, and leading zeros. Original data stays stored for retrieval and sorting; UUID/set conversion occurs only in the JSON payload copy. Other lookups and unmarked business fields retain adapter behavior. Custom backends continue receiving mappings/native values and must honor identity metadata when their provider has lossy comparison semantics. A raw Meilisearch filter_expression bypasses structured identity transport.
Existing persistent documents require a full reindex. Rows lacking tokens are omitted from declared identity filters; mixed indexes never fall back to numeric equality. See the migration procedure.
general_manager.search.backend.SearchHit dataclass ¶
Search hit metadata returned by backends after a query.
id, type, and identification identify the matched manager document. score, index, and data are optional because not every backend returns a relevance score, index name, or stored data fields in every response. When data is present, ownership and copy semantics are adapter-defined; callers should treat returned mappings as read-only.
general_manager.search.backend.SearchResult dataclass ¶
Container for normalized search responses.
hits is the current page after applying limit and offset. total is the total number of matches before pagination when the backend can report it; when a backend cannot report a pre-pagination count, its adapter defines the best-effort value. raw may carry the backend-native response object for debugging or advanced callers and is not copied or normalized by this model; callers should treat it as read-only. exhausted=True is an adapter-proven guarantee that this page reaches the end of the matching result set. False means the adapter determined the page is incomplete or cannot make that guarantee. None preserves the legacy contract for adapters that do not report enumeration completeness. When exhausted is False, next_offset can attest that the hits cover one complete effective backend page, even when the provider returned fewer than the requested limit. It must equal the requested offset plus the number of returned hits, with positive progress and no raw hits discarded during normalization. It permits another page request; it does not prove that more hits exist or that enumeration is complete. None retains the existing paging contract.
general_manager.search.backend.SearchBackend ¶
Bases: Protocol
Protocol implemented by search backend adapters.
The portable contract is intentionally narrow: method shapes, document identity by index/name/id, object-valued payloads, basic structured filter transport, type restrictions, signed multi-field sorting, paginated results, and the broad error boundary below. Backend-specific behavior is part of the public adapter contract, not an omission from this protocol. That includes exact settings support and merge/replace behavior, duplicate IDs inside one batch, grouped-filter semantics, filter_expression precedence, non-DevSearch lookup/sort grammar, negative pagination values, batch atomicity, concurrency guarantees, runtime validation, and concrete exception classes. Adapters may validate inputs more strictly than these dataclasses do without violating the protocol. All protocol methods are synchronous.
ensure_index ¶
ensure_index(index_name, settings)
Ensure the named index exists and apply the given settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Name of the index to create or update. | required |
settings | Mapping[str, object] | Configuration settings to apply to the index. | required |
Raises:
| Type | Description |
|---|---|
SearchBackendError | Backend adapters may raise this for operational failures. Concrete adapters may also propagate client-library, validation, or configuration exceptions. |
upsert ¶
upsert(index_name, documents)
Upsert the provided search documents into the specified index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Name of the index where documents will be stored. | required |
documents | Sequence[SearchDocument] | Documents to insert or update; each document's | required |
Raises:
| Type | Description |
|---|---|
SearchBackendError | Backend adapters may raise this for operational failures. Concrete adapters may also propagate client-library, validation, or configuration exceptions. |
delete ¶
delete(index_name, ids)
Delete documents from the specified index by their document IDs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Name of the index to remove documents from. | required |
ids | Sequence[str] | Document IDs to delete. Missing IDs may be ignored by backends that support idempotent deletion. Duplicate IDs in one call and partial-delete behavior after a batch failure are adapter-defined. | required |
Raises:
| Type | Description |
|---|---|
SearchBackendError | Backend adapters may raise this for operational failures. Concrete adapters may also propagate client-library, validation, or configuration exceptions. |
list_document_ids ¶
list_document_ids(index_name, *, types=None)
Return all document IDs currently stored in an index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Name of the index to inspect. | required |
types | Sequence[str] | None | Optional document type labels to include. | None |
Returns:
| Type | Description |
|---|---|
set[str] | Backend document IDs in their original GeneralManager form, for |
set[str] | example the same strings passed as |
set[str] |
|
Raises:
| Type | Description |
|---|---|
SearchBackendError | Backend adapters may raise this for operational failures. Concrete adapters may also propagate client-library, validation, or configuration exceptions. |
search ¶
search(
index_name,
query,
*,
filters=None,
filter_expression=None,
sort=None,
limit=10,
offset=0,
types=None
)
Search for documents in an index that match the given query and optional filters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Name of the index to search. | required |
query | str | Query string used to match documents. | required |
filters | Mapping[str, object] | Sequence[Mapping[str, object]] | None | Optional structured filters applied to the query. A single mapping is an AND group; mapping keys use backend-supported field names or lookup expressions such as | None |
filter_expression | str | None | Optional backend-specific boolean expression. When provided, concrete backends define precedence relative to | None |
sort | Sequence[str] | None | Signed field names in precedence order; | None |
limit | int | Maximum number of hits to return. The protocol does not clamp or validate negative values; concrete backends define invalid-value behavior. | 10 |
offset | int | Number of hits to skip before returning results. Concrete backends define invalid-value behavior. | 0 |
types | Sequence[str] | None | Optional document type labels to restrict the search to. Unknown type labels and unknown indexes are handled by the concrete adapter. | None |
Returns:
| Type | Description |
|---|---|
SearchResult | Container with matching hits, the total number of matches, optional |
SearchResult | elapsed time in milliseconds, any raw backend response, and |
SearchResult | adapter-specific enumeration completeness. |
SearchResult | no completeness guarantee was supplied, not that the page is |
SearchResult | necessarily complete or incomplete. |
Raises:
| Type | Description |
|---|---|
SearchBackendError | Backend adapters may raise this for operational failures. Concrete adapters may also propagate client-library, validation, unsupported-feature, or configuration exceptions. The protocol intentionally does not define a closed exception taxonomy; unsupported |
general_manager.search.backend.SearchBackendError ¶
Bases: RuntimeError
Raised when a backend operation fails.
general_manager.search.backend.SearchBackendNotConfiguredError ¶
Bases: RuntimeError
Raised when a configured backend cannot be resolved.
general_manager.search.backend.SearchBackendNotImplementedError ¶
Bases: SearchBackendError
Raised when a backend implementation is not available.
__init__ ¶
__init__(backend_name)
Initialize the error indicating a specific search backend is not implemented.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend_name | str | Name of the backend used to compose the exception message. | required |
general_manager.search.backend.SearchBackendClientMissingError ¶
Bases: SearchBackendError
Raised when a backend client dependency is missing.
__init__ ¶
__init__(backend_name)
Initialize the exception indicating a backend client dependency is missing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend_name | str | Name of the missing backend client; used to construct the exception message advising installation of the required package. | required |
general_manager.search.backend_registry.configure_search_backend ¶
configure_search_backend(backend)
Set the active search backend instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend | SearchBackend | None | Instance to set as the process-local active search backend. Pass | required |
general_manager.search.backend_registry.configure_search_backend_from_settings ¶
configure_search_backend_from_settings(django_settings)
Configure the active search backend using values from Django settings.
GENERAL_MANAGER["SEARCH_BACKEND"] takes precedence over a top-level SEARCH_BACKEND setting, including explicit None to clear the configured backend. Values may be:
Noneor missing to clear the active backend.- A
SearchBackendinstance. - A dotted import path to a
SearchBackendinstance, class, or factory. - A zero-argument callable returning a
SearchBackend. - A mapping with
{"class": <path-or-callable>, "options": {...}}; options are passed as keyword arguments when constructing/calling the reference.
Import, factory, and constructor exceptions propagate. Resolved objects that do not satisfy SearchBackend raise SearchBackendNotConfiguredError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
django_settings | object | Django settings module or object to read configuration from. | required |
Raises:
| Type | Description |
|---|---|
TypeError | If a mapping configuration provides an |
SearchBackendNotConfiguredError | If a non- |
general_manager.search.backend_registry.get_search_backend ¶
get_search_backend()
Return the active search backend, configuring it from Django settings first.
If no backend has been configured, this function calls configure_search_backend_from_settings(django.conf.settings). If settings still leave the backend unset, it creates one DevSearchBackend, stores it as the process-local active backend, and returns that same fallback instance on later calls. The fallback enables first-search hydration when SEARCH_AUTO_REINDEX is enabled in Django settings.
Returns:
| Type | Description |
|---|---|
SearchBackend | The configured or development fallback search backend. |
Raises:
| Type | Description |
|---|---|
SearchBackendNotConfiguredError | If backend configuration cannot be resolved to a valid |
general_manager.search.indexer.SearchIndexer ¶
Indexer that writes manager instances to a search backend.
__init__ ¶
__init__(backend=None)
Initialize a SearchIndexer with a search backend.
If backend is None, the process-default backend is resolved through get_search_backend(). Backend objects must implement the documented SearchBackend protocol. Backend selection follows the process-local backend registry semantics from get_search_backend(); no additional cache or thread-safety behavior is added by the indexer. Backend configuration/import/constructor errors from registry resolution propagate.
index_instance ¶
index_instance(instance)
Index a GeneralManager instance across all configured search indexes.
Ensures each target index exists in the backend and upserts one document per IndexConfig configured on the instance manager's SearchConfig. Search configuration is discovered from the instance class through GeneralManager's search registry. Does nothing if the manager class has no search configuration. The default document id uses the same type label and instance.identification path as delete_instance().
Index configs are processed in configured order. The method is not atomic across indexes; earlier backend writes remain if a later index fails. Duplicate IndexConfig.name entries are not deduplicated. Duplicate names therefore repeat ensure/upsert work and use the first matching index config returned by the search registry when serializing that name. Passing a non-GeneralManager object is not runtime-validated and fails through normal attribute access.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance | GeneralManager | The manager instance to index. | required |
Raises:
| Type | Description |
|---|---|
MissingIndexConfigurationError | If a configured |
Exception | Backend |
index_instance_index ¶
index_instance_index(instance, index_name)
Index one instance into one named configured search index.
index_manager_index_batch ¶
index_manager_index_batch(
manager_class, index_name, identifications
)
Index a bounded identity batch for one exact manager/index pair.
Identifications are copied and canonically deduplicated in first-seen order. Standard single-id ORM managers are loaded with one public filter(pk__in=...) call; all other manager shapes are reconstructed individually. The backend write occurs only after every requested owner has been resolved and serialized.
delete_instance ¶
delete_instance(instance)
Delete an instance's search document from all configured indexes.
Determines the document id using the manager's configured document_id callable if present; otherwise builds the same default id used by index_instance() from the manager type label and the instance's identification. For each index configured for the manager, ensures the index exists in the backend and asks the backend to delete that one document id. Does nothing if the manager class has no search configuration.
Index configs are processed in configured order. The method is not atomic across indexes; earlier backend deletes remain if a later index fails. Missing backend documents are delegated to backend delete semantics. Passing a non-GeneralManager object is not runtime-validated and fails through normal attribute access.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance | GeneralManager | The manager instance whose document should be removed from the search indexes. | required |
Raises:
| Type | Description |
|---|---|
Exception | Backend |
delete_documents ¶
delete_documents(targets)
Delete captured immutable document IDs, grouping work by index.
reindex_manager ¶
reindex_manager(manager_class)
Rebuilds all search indexes for a given manager class by collecting every instance's documents and upserting them to the backend.
Ensures each configured index exists, iterates manager_class.all(), serializes one document per instance and IndexConfig, groups documents by index name, and calls backend upsert once per index that has current documents. If the manager class has no search configuration, the function returns without action.
This method does not delete stale backend documents. Use reindex_manager_index() when stale document cleanup is required for a single manager/index pair. Indexes are ensured even when manager_class.all() returns no instances. The method is not atomic across indexes; earlier ensures or upserts remain if a later index fails. Documents belonging to other manager type labels are preserved because no delete operation is issued. Upsert calls follow the first occurrence order of configured index names. Duplicate index names collapse into one backend upsert call for that name, but serialization still produces one document per duplicate config and instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
manager_class | type[GeneralManager] | The manager class whose instances will be reindexed. | required |
Raises:
| Type | Description |
|---|---|
MissingIndexConfigurationError | If a configured index name is missing while serializing an instance. |
Exception | Manager iteration, backend |
reindex_manager_index ¶
reindex_manager_index(manager_class, index_name)
Rebuild one manager's documents for one configured search index.
Returns 0 without action when the manager class has no search configuration. Otherwise, ensures the target index, serializes one document for every instance returned by manager_class.all(), upserts current documents when present, lists existing backend document ids using backend.list_document_ids(index_name, types=[get_type_label(manager_class)]), deletes stale ids for that type after successful upsert, and returns the number of current documents serialized. The backend's type filter and GeneralManager type-label/document-id convention define the id namespace that protects other manager classes.
The method is not atomic. If ensure, serialization, or upsert fails, the stale-delete phase is not reached. If stale deletion fails after an upsert, the new documents remain written. If duplicate index configs use the requested index_name, the first matching config is used, one document is serialized per manager instance, and the return value counts those serialized documents.
Raises:
| Type | Description |
|---|---|
MissingIndexConfigurationError | If |
Exception | Manager iteration, backend |
general_manager.search.reconciliation.SearchIndexTarget dataclass ¶
Configured manager/index pair that can be reconciled.
The dataclass is frozen and equality is value-based; ordering is not defined. Fields are not runtime-validated. manager_path uses manager_import_path(). Duplicate configured index names can yield multiple equal targets, while durable state rows still share the same manager/index key.
general_manager.search.reconciliation.SearchStateEnsureResult dataclass ¶
Counts produced while ensuring search reconciliation state rows.
updated includes both forced dirtying and schema-fingerprint changes. Counts are increments performed by the ensure loop, not necessarily unique database rows when duplicate index names are configured. Manual construction is not validated against negative or non-sensical counts.
general_manager.search.reconciliation.SearchReconcileResult dataclass ¶
Counts produced by one search reconciliation sweep.
claimed, reconciled, and failed count durable state rows. documents counts documents reported by successful reindex_manager_index() calls. skipped is populated only when no dirty states were claimed and counts currently clean rows; rows left unclaimed by max_states are not included. Manual construction is not validated against negative or non-sensical counts.
general_manager.search.reconciliation.InvalidSearchReconciliationManagerPathError ¶
Bases: TypeError
Raised by manager-path resolution when a stored path is not a manager class.
reconcile_search_indexes() catches this per state, records the message in SearchIndexState.last_error, increments failed, and continues.
general_manager.search.reconciliation.manager_import_path ¶
manager_import_path(manager_class)
Return the import path used to identify a searchable manager.
The format is <manager_class.__module__>.<manager_class.__name__>. The helper does not validate that the class is importable, concrete, or a GeneralManager subclass at runtime.
general_manager.search.reconciliation.build_search_schema_fingerprint ¶
build_search_schema_fingerprint(
manager_class, index_config
)
Build a stable fingerprint for one manager/index search configuration.
The fingerprint includes the manager import path, index fields, filters, sorts, boosts, min score, declared projection dependencies, resolved identity kinds and transport version, type label, update strategy, and import-like paths for custom document_id and to_document callables. It returns a SHA-256 hex digest. Field order follows index_config.iter_fields(), filters and sorts keep configured order, duplicate entries remain in the payload, and JSON object keys are sorted before hashing. Callable paths use <__module__>.<__qualname__> when present, then <__module__>.<__name__> when __name__ is used, then repr with the module prefix when a module is available. Defaults are whatever the resolved SearchConfigSpec exposes. JSON serialization errors from malformed config values propagate.
general_manager.search.reconciliation.iter_search_index_targets ¶
iter_search_index_targets()
Yield all configured searchable manager/index targets.
Managers come from the search registry. Managers without search config are skipped. Duplicate configured index names yield duplicate targets in configuration order. The generator is lazy and propagates errors from manager/config discovery.
general_manager.search.reconciliation.ensure_search_index_states ¶
ensure_search_index_states(*, force=False)
Ensure durable state rows exist and mark missing or changed targets dirty.
Creates one SearchIndexState per manager path and index name, marks new rows dirty for initialization, marks existing rows dirty when force=True, and marks rows dirty when the schema fingerprint changed. Existing unchanged rows are counted as unchanged. Obsolete rows for removed managers or indexes are not deleted. Each target is handled in its own transaction with select_for_update(). Duplicate configured index names address the same durable row repeatedly and increment loop counts per processed target. Dirty reasons are initialization, forced, or schema_changed; marking a row dirty preserves its first dirty_since timestamp and overwrites dirty_reason. Database errors propagate.
general_manager.search.reconciliation.mark_search_indexes_dirty ¶
mark_search_indexes_dirty(
manager_class,
*,
reason=SEARCH_INDEX_DIRTY_REASON_DATA_CHANGED
)
Mark all configured search indexes for a manager dirty.
Returns the number of configured index entries marked. Managers without search config return 0. State rows are created when missing as initialization work, while stored schema mismatches become schema-change work. Duplicate configured index names are processed once per config entry against the same durable row, preserving the wrapper's count semantics. Repeated processing preserves the first dirty_since, advances dirty_generation, and does not downgrade stronger work to a data-change reason. Database errors propagate.
general_manager.search.reconciliation.reconcile_search_indexes ¶
reconcile_search_indexes(*, force=False, max_states=None)
Reconcile dirty search index states.
Ensures state rows first, claims dirty states ordered by oldest dirty_since, optionally limits the claim count with max_states, and rebuilds each claimed manager/index pair with SearchIndexer.reindex_manager_index(). When no states are dirty, returns the ensure counts plus the number of clean rows as skipped.
force=True affects the ensure phase before claiming. max_states limits only how many dirty rows are claimed in the current sweep; unclaimed dirty rows remain dirty and are not counted as skipped. Claims use select_for_update() plus a claim token/expiry so concurrent reconcilers do not process the same unexpired claim; expired claims are eligible like unclaimed dirty rows. Ensure counts are included in the returned result on both skipped and claimed sweeps. Successful reconciliation clears last_error, while a new failure overwrites it. Backend writes inside reindex_manager_index() may have partial effects before that method raises.
Per-state import, validation, backend, and serialization failures are caught: the state claim is released, last_error is stored, and failed is incremented. Database errors while ensuring, claiming, releasing, or clearing states propagate.
general_manager.search.tasks.search_reconcile_enabled ¶
search_reconcile_enabled(django_settings=settings)
Return whether periodic search reconciliation is enabled.
GENERAL_MANAGER["SEARCH_RECONCILE_ENABLED"] takes precedence over the top-level setting. Missing values default to False; configured values use normal Python truthiness.
general_manager.search.tasks.search_reconcile_interval_seconds ¶
search_reconcile_interval_seconds(django_settings=settings)
Return the periodic reconciliation interval in seconds.
GENERAL_MANAGER["SEARCH_RECONCILE_INTERVAL_SECONDS"] takes precedence over the top-level setting. Missing or invalid values fall back to 60; valid integer-like values are clamped to at least one second.
general_manager.search.tasks.configure_search_reconcile_beat_schedule_from_settings ¶
configure_search_reconcile_beat_schedule_from_settings(
django_settings=settings,
)
Register periodic search reconciliation in Celery Beat.
Returns False when reconciliation is disabled, Celery is unavailable, or the module-level Celery current_app is None. When configured, this writes or replaces SEARCH_RECONCILE_BEAT_SCHEDULE_KEY with task path general_manager.search.tasks.reconcile_search_indexes_task, a float seconds schedule, no args or kwargs, and options={"queue": "search.reconciliation"}. Existing mapping schedule entries are preserved; malformed non-mapping schedule values are treated as an empty schedule.
Exceptions from Celery app configuration access or assignment propagate.
general_manager.search.tasks.reconcile_search_indexes_task ¶
reconcile_search_indexes_task()
Run one search reconciliation sweep.
Returns a dictionary with reconciled, failed, and documents counts from reconcile_search_indexes(). Exceptions from the reconciliation service propagate to the Celery worker or direct caller.
general_manager.search.async_tasks.SearchIndexAction module-attribute ¶
SearchIndexAction = Literal['index', 'delete']
general_manager.search.async_tasks.SearchIdentification module-attribute ¶
SearchIdentification = Mapping[str, object]
general_manager.search.async_tasks.InvalidSearchIndexActionError ¶
Bases: ValueError
Raised when async search indexing receives an unsupported action.
general_manager.search.async_tasks.InvalidSearchManagerPathError ¶
Bases: TypeError
Raised when a manager import path does not resolve to a manager class.
general_manager.search.async_tasks.index_instance_task ¶
index_instance_task(
manager_path, identification, index_name=None
)
Index the instance represented by the given manager path and identification in the configured search backend.
manager_path must resolve to a callable manager class. identification supplies keyword arguments for that class and must contain values accepted by the active Celery serializer when queued. Import, construction, backend lookup, and indexing errors propagate to the Celery worker or direct caller.
general_manager.search.async_tasks.delete_instance_task ¶
delete_instance_task(manager_path, identification)
Remove the search index document for an instance identified by a manager path and identification data.
manager_path must resolve to a callable manager class. identification supplies keyword arguments for that class and must contain values accepted by the active Celery serializer when queued. Import, construction, backend lookup, and deletion errors propagate to the Celery worker or direct caller.
general_manager.search.async_tasks.dispatch_index_update ¶
dispatch_index_update(
*,
action,
manager_path,
identification,
instance=None,
index_name=None
)
Dispatch one search index update or delete operation.
action must be "index" or "delete". When async indexing is enabled and Celery is available, a Celery task is enqueued and any provided instance is ignored. Otherwise, an explicit instance runs inline against the current backend. When no instance is supplied, the task function is called synchronously and reconstructs the manager from manager_path and identification. Task enqueue, import, construction, backend, and indexer errors propagate.
DevSearch compatibility and lifecycle notes¶
DevSearchBackend is the built-in process-local backend for development. Its existing no-argument construction remains inert and compatible with callers that manage indexes explicitly. The new keyword-only DevSearchBackend(*, auto_reindex: bool = False) option opts a directly constructed backend into first-search hydration. The public auto_reindex_enabled: bool property reports the current setting, and configure_auto_reindex(enabled: bool) -> None changes it for later searches.
When SEARCH_AUTO_REINDEX is truthy in the nested GENERAL_MANAGER mapping, or in the top-level setting when the nested key is absent, a selected DevSearchBackend hydrates each index on its first search. The setting is ignored for external backends and does not require Django DEBUG=True. Each configured manager is reindexed in the serving process; source and reindexing exceptions propagate to the triggering search, and a failed index remains retryable. Same-process synchronous invalidation continues to update a hydrated projection, while writes or search_index --reindex in another process cannot populate a running DevSearch instance.
Multi-term DevSearch queries now require every distinct lowercased query term to equal or prefix a token from at least one indexed field. Terms may match different fields, repeated terms do not inflate the score, and empty-query behavior is unchanged. External backend query semantics are unaffected.
general_manager.search.backends.dev.DevSearchBackend ¶
Process-local development search with optional lazy per-index hydration.
auto_reindex_enabled property ¶
auto_reindex_enabled
Return whether first-search hydration is enabled for this backend.
__init__ ¶
__init__(*, auto_reindex=False)
Initialize an empty in-memory registry and optional hydration lifecycle.
Automatic hydration is disabled for directly constructed backends unless explicitly opted in. When enabled, each index hydrates on its first search in this process. Failed hydration propagates and remains retryable. The lock coordinates only first-search hydration; ordinary reads and writes retain the backend's existing unsynchronized behavior.
configure_auto_reindex ¶
configure_auto_reindex(enabled)
Enable or disable first-search hydration for this backend instance.
ensure_index ¶
ensure_index(index_name, settings)
Ensure an index exists and update its settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Name of the index to create or retrieve. | required |
settings | Mapping[str, object] | Settings to assign to the index; replaces any existing settings. The dev backend stores the mapping but does not inspect it. | required |
upsert ¶
upsert(index_name, documents)
Insert or update the given documents in the named in-memory index.
Each document is stored by its id in the index's document map and a per-document token index is built and stored for use by searches; existing documents with the same id are replaced.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Name of the index to modify. | required |
documents | Sequence[SearchDocument] | Documents to insert or update. | required |
delete ¶
delete(index_name, ids)
Remove documents and their token indexes from the specified in-memory index.
This performs a best-effort removal: if an id is not present in the index, it is ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Name of the index to modify. | required |
ids | Sequence[str] | Document ids to remove from the index. | required |
list_document_ids ¶
list_document_ids(index_name, *, types=None)
Return stored document IDs, optionally restricted by document type.
search ¶
search(
index_name,
query,
*,
filters=None,
filter_expression=None,
sort=None,
limit=10,
offset=0,
types=None
)
Search an index for documents matching a query and return scored, optionally filtered and sorted hits.
When auto-reindex is enabled, the first search for an index lazily hydrates that index in this process before evaluating the query. The hydration guard coordinates concurrent and nested first searches only; a failed source error propagates and the next search can retry. The backend reads and writes documents under the index_name argument; SearchDocument.index is stored but not validated. Document IDs are unique only inside one in-memory index. Duplicate IDs inside one upsert() call are processed in order, so the last document wins. Deletes are best-effort and duplicate IDs are harmless. ensure_index() is idempotent and replaces the stored settings mapping for the index. Operations are not transactional; mutations completed before an exception remain in memory. Queries are lowercased and split on whitespace, with duplicate query tokens removed in first-seen order. Indexed tokens are built from every top-level SearchDocument.data value: None yields no tokens, strings split on whitespace, lists/tuples/sets are processed recursively, and all other values become str(value).lower().split(). Dict values are not traversed; they are tokenized from their string representation. A document matches when every distinct query token equals or prefixes a token extracted from any indexed field. Empty queries match every document that passes type and structured filters. The operation order is type filtering, structured filtering, query scoring/matching, sorting, and then pagination with results[offset:offset + limit]; negative values intentionally follow Python slice behavior. Scores sum matching field boosts, then multiply by index_boost when set. Results sort by score descending unless sort is provided. Sorting applies each signed document data field in sequence. None and missing fields are treated as missing and kept last for both ascending and descending sorts. bool values use Python's numeric ordering because bool is an int subclass. Other numeric values sort numerically, and every non-numeric, non-missing value is compared as str(value). Explicit sort ties use complete logical document identity (type and typed identification), then adapter document metadata, so page membership agrees with manager ordering. Source insertion order is preserved when no usable logical identity exists or identities are equal, including equal-score default ordering. The backend stores document and settings objects by reference, returns hit data from the stored SearchDocument.data mapping, is process-local memory only, and does not provide persistence or ordinary read/write synchronization beyond first-search hydration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Name of the index to search. | required |
query | str | Query string to tokenize and match against indexed documents. | required |
filters | Mapping[str, object] | Sequence[Mapping[str, object]] | None | Field-based filters to apply; may be a single mapping or a sequence of alternative filter groups. Mapping keys target | None |
filter_expression | str | None | Unsupported in this backend; passing a value raises NotImplementedError. | None |
sort | Sequence[str] | None | Signed document data field names. Prefix a field with | None |
limit | int | Maximum number of hits to return. Native slice semantics apply, including for negative values. | 10 |
offset | int | Number of matching results to skip before collecting hits. Native slice semantics apply, including for negative values. | 0 |
types | Sequence[str] | None | If provided, restrict results to documents whose type is in this sequence. | None |
Returns:
| Name | Type | Description |
|---|---|---|
SearchResult | SearchResult | Object containing |
SearchResult | data fields included), | |
SearchResult | pagination), and |
Raises:
| Type | Description |
|---|---|
NotImplementedError | If |
general_manager.search.backends.meilisearch.MeilisearchBackend ¶
Meilisearch implementation of the SearchBackend protocol.
The adapter stores the original GeneralManager document id in gm_document_id and uses a Meilisearch-safe deterministic id for the primary key. Every original id, including already-safe ids, empty strings, and Unicode strings, is converted to "gm_" + sha256(str(id)).hexdigest(). The mapping is stable and collision-resistant but not reversible. It accepts a preconfigured client for tests or advanced deployments, otherwise imports meilisearch.Client at runtime.
__init__ ¶
__init__(
url="http://127.0.0.1:7700",
api_key=None,
client=None,
task_timeout_in_ms=5000,
*,
metadata_client=None
)
Initialize the backend with a provided Meilisearch client or a new one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url | str | Base URL to use when creating a Meilisearch client if | 'http://127.0.0.1:7700' |
api_key | str | None | Optional API key to use when creating the client. | None |
client | _MeilisearchClient | None | Optional preconfigured Meilisearch client instance to use directly. If omitted, the constructor imports the | None |
task_timeout_in_ms | int | Timeout in milliseconds forwarded to the client | 5000 |
metadata_client | _MeilisearchClient | None | Optional read-only client used only to retrieve index settings and, when a cutoff setting is absent, the server version. It defaults to | None |
Raises:
| Type | Description |
|---|---|
SearchBackendClientMissingError | The |
ensure_index ¶
ensure_index(index_name, settings)
Ensure a Meilisearch index with the given name exists and apply searchable, filterable, and sortable field settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Name of the index to retrieve or create. | required |
settings | Mapping[str, object] | Index settings mapping. Recognized keys: - "searchable_fields": iterable of field names to set as searchableAttributes. - "filterable_fields": iterable of field names to set as filterableAttributes. - "sortable_fields": iterable of field names to set as sortableAttributes. - "identity_fields": contracts keyed by document type; each maps identity names to int/str/UUID. Shadow filterability is added only for names listed in "filterable_fields". | required |
Non-iterable setting values and strings/bytes are ignored; iterable values such as lists, tuples, and sets are converted to strings. This method creates the index with primary key id if it does not exist and compares current effective settings before writing changes. Ranking rules and searchable fields retain their order; plain filterable and sortable fields are compared by membership. Each submitted settings task completes before the next update or return.
Raises:
| Type | Description |
|---|---|
MeilisearchTaskFailedError | A create-index or settings task fails, is canceled, or times out while polling a client without |
upsert ¶
upsert(index_name, documents)
Ensure the index exists, then index or update the given documents and wait for the indexing task to complete.
The index is still ensured when documents is empty, but no add_documents task is submitted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Name of the Meilisearch index to upsert documents into. | required |
documents | Sequence[SearchDocument] | Sequence of documents to add or update in the index. | required |
Raises:
| Type | Description |
|---|---|
MeilisearchTaskFailedError | If the Meilisearch task completes with a failed or canceled status. |
delete ¶
delete(index_name, ids)
Delete documents from the specified index by their IDs.
An empty ids sequence is a no-op and does not access Meilisearch. Non-empty sequences are normalized element-by-element; an empty string inside the sequence is treated as a real document id and deleted using its deterministic normalized value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Name of the index to delete documents from. | required |
ids | Sequence[str] | Sequence of document IDs to remove; each ID will be normalized before deletion. If empty, no action is taken. | required |
Raises:
| Type | Description |
|---|---|
MeilisearchTaskFailedError | If the backend reports the deletion task failed or was canceled. |
list_document_ids ¶
list_document_ids(index_name, *, types=None)
Return stored GeneralManager document IDs from a Meilisearch index.
Reads pages of up to 1000 documents using fields id, gm_document_id, and type. types=None and types=[] both include every type. When a filter is present, matching is exact against the stored type value. gm_document_id is preferred; only legacy documents where it is missing or None fall back to id. An empty original id remains empty. Duplicate ids collapse into one set entry, and malformed document entries without either field are ignored.
search ¶
search(
index_name,
query,
*,
filters=None,
filter_expression=None,
sort=None,
limit=10,
offset=0,
types=None
)
Execute a search against the specified Meilisearch index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Name of the index to search. | required |
query | str | Full-text query string. | required |
filters | Mapping[str, object] | Sequence[Mapping[str, object]] | None | Field-based filter(s). May be a single mapping or a sequence of mappings representing OR groups; keys may include nested lookups (e.g., "field__lookup"). | None |
filter_expression | str | None | Raw Meilisearch filter expression to use instead of | None |
sort | Sequence[str] | None | Signed field names to sort in order. Prefix a field with | None |
limit | int | Maximum number of results to return. | 10 |
offset | int | Number of results to skip. | 0 |
types | Sequence[str] | None | Sequence of document type names to restrict results to the | None |
Returns:
| Name | Type | Description |
|---|---|---|
SearchResult | SearchResult | Object containing matched hits, total hits estimate, request processing time in milliseconds, and the raw Meilisearch response. |
Notes
filter_expression takes precedence over structured filters and types; when it is provided, types is ignored. Structured filters support equality and in semantics. Multiple fields inside one mapping are combined with AND, multiple filter mappings are combined with OR, and types are ORed together before being ANDed with structured filters. String rendering uses str(value) and escapes backslashes and double quotes; this also applies to numbers, booleans, and None. Empty in lists produce an empty parenthesized clause. Declared identity equality/membership uses separate versioned tokens without changing source values. Plain structured filters inherit registered manager/index contracts; SearchIdentityFilterGroup supports unregistered documents. Old documents without tokens require reindexing; raw filter_expression bypasses identity transport. sort is normalized as signed field names and forwarded as ordered Meilisearch field:direction entries. Every query reads index settings once through the authorized metadata client. A sorted query raises MeilisearchOrderingConfigurationError unless sort has the highest ranking-rule priority. The returned SearchResult sets exhausted=True only when a well-formed raw short page is below the configured pagination.maxTotalHits cap and either completed before the effective searchCutoffMs or is attested by a stable Meilisearch 1.7 server that predates cutoff support. A missing or malformed pagination cap or hit list yields exhausted=False; neither estimatedTotalHits nor totalHits proves completeness because Meilisearch caps both. An explicitly degraded response, missing/invalid cutoff or processing-time evidence, response reaching its cutoff, or raw page larger than the effective page limit raises SearchBackendError before hit normalization because it might omit hits. Malformed hit entries are skipped for normalized output but cannot prove a short page. When response pagination echoes are present, offset must exactly match the request and a lower limit becomes the effective page size; missing echoes retain compatibility with legacy client response shapes. Missing hit id/gm_document_id and type become empty strings, missing identification and data become empty mappings, and missing _rankingScore becomes None.
MeilisearchBackend.ensure_index(index_name, settings) -> None creates the index with primary key id when needed, then reads effective settings before submitting changes. Ranking rules and searchable fields compare in order; plain filterable and sortable fields compare by membership. Identity contracts add gm_identity.* shadow fields only for declared filterable identities. For each explicit searchable field, numeric aliases under gm_numeric_tokens.* are appended after the original searchable attributes, preserving their priority. An empty searchable list remains empty; ['*'] still searches all attributes. Omitted searchable, filterable, and sortable setting keys remain unmanaged, while explicit empty lists clear their setting; ranking rules are always normalized with sort first. Each submitted task is awaited before the next one. A settings-read, configuration, client, or task failure propagates; a later call can retry any settings that were not successfully applied. The method accepts the documented index_name: str and settings: Mapping[str, object] parameters and returns None. Malformed identity_fields contracts raise SearchIdentityConfigurationError; failed or canceled task results and timeouts in the fallback get_task() polling loop raise MeilisearchTaskFailedError. Exceptions from the client's wait_for_task() method, including its timeout errors, propagate unchanged.
upsert() derives complete ASCII digit runs from serialized string values, including collection and mapping values, and adds both the original and zero-stripped forms. For example, Porsche_P0375_Strangpressprofile gains 0375 and 375. Mapping keys and non-string scalars are not expanded. At most two aliases are produced per run, without integer conversion or substring enumeration. Shadow field names encode their source field, so filter-/sort-only fields do not become searchable. Source data, filter/sort values, identification and GraphQL read authorization are unchanged. This is Meilisearch-specific; the development backend and custom adapters retain their existing tokenization.
After upgrading, run python manage.py search_index --index global --reindex (repeat for other persistent indexes). Updating settings alone cannot add tokens to existing documents; reindexing is required for consistent numeric matching.
MeilisearchBackend.search() reads settings once per backend call, sharing the read between ordering validation and completeness checks. Its optional keyword-only metadata_client supplies that authoritative settings read; it defaults to client. Search, index hydration, and writes always remain on client, so deployments can use a search + indexes.get key there and a separate indexes.get + settings.get metadata key for metadata_client. Both clients must address the same trusted server and index. When searchCutoffMs is absent, the metadata client must also authorize get_version() and attest an exact stable 1.7.x pkgVersion; that is the supported pre-cutoff compatibility range. Unknown, malformed, or newer versions cannot establish completeness.
A short page is attested as exhausted only below pagination.maxTotalHits with valid response provenance. Reaching the cap cannot establish a complete authorized total. Degraded responses, responses reaching the search cutoff, missing timing proof and raw page overdelivery fail explicitly. This inspects backend pagination and response metadata; it does not check indexed content freshness.
A provider may return a smaller effective page than requested. When Meilisearch echoes a valid limit and the requested offset, and the raw response fills that effective page without discarded entries, the adapter attests its SearchResult.next_offset. GraphQL can then continue from that offset while counting every returned hit against the existing scan budget. A full effective page does not establish the final total; a later page must still prove exhaustion. Missing or inconsistent pagination evidence, unproven short pages and cap-boundary responses retain the existing fail-closed behavior.
Custom adapters can set SearchResult.exhausted to attest complete enumeration (True) or to prevent a short page being treated as complete (False). The compatibility default None retains the existing short-page contract. Adapters must reject a truncated intermediate page themselves: a later terminal page cannot repair an earlier incomplete response. An optional next_offset can accompany exhausted=False to prove that a nonempty page is complete at a smaller effective limit. It must be an integer (not a boolean) equal to the requested offset plus the number of normalized hits, with no raw entries omitted. It permits continuation without changing the exhaustion contract. The default None leaves legacy adapters unchanged.
general_manager.search.backends.opensearch.OpenSearchBackend ¶
OpenSearch/Elasticsearch backend placeholder.
The adapter is publicly importable for configuration compatibility, but it is not implemented. Construction and every backend operation raise SearchBackendNotImplementedError.
__init__ ¶
__init__(*_, **__)
Initialize the OpenSearch backend stub which always fails construction.
Raises:
| Type | Description |
|---|---|
SearchBackendNotImplementedError | Always raised with message "OpenSearch/Elasticsearch". |
ensure_index ¶
ensure_index(index_name, settings)
Ensure the named index exists with the provided settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | The name of the index to create or verify. | required |
settings | Mapping[str, object] | Index configuration, such as mappings, analyzers, and other OpenSearch/Elasticsearch settings. The value is accepted for protocol compatibility but never inspected. | required |
Raises:
| Type | Description |
|---|---|
SearchBackendNotImplementedError | Always raised because this backend is not implemented. |
upsert ¶
upsert(index_name, documents)
Placeholder to insert or update documents in the specified index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Name of the index where documents would be upserted. | required |
documents | Sequence[SearchDocument] | Documents to insert or update. | required |
Raises:
| Type | Description |
|---|---|
SearchBackendNotImplementedError | Always raised because the OpenSearch backend is not implemented. |
delete ¶
delete(index_name, ids)
Delete documents by ID from the specified index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Name of the index containing the documents. | required |
ids | Sequence[str] | Sequence of document IDs to delete. | required |
Raises:
| Type | Description |
|---|---|
SearchBackendNotImplementedError | Raised unconditionally because the OpenSearch backend is not implemented. |
list_document_ids ¶
list_document_ids(index_name, *, types=None)
List stored document IDs in the specified index.
Raises:
| Type | Description |
|---|---|
SearchBackendNotImplementedError | Always raised because the OpenSearch backend is not implemented. |
search ¶
search(
index_name,
query,
*,
filters=None,
filter_expression=None,
sort=None,
limit=10,
offset=0,
types=None
)
Execute a search query against the specified index using optional filters, sorting, pagination, and type constraints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Name of the index to search. | required |
query | str | Full-text query string to match documents. | required |
filters | Mapping[str, object] | Sequence[Mapping[str, object]] | None | Optional structured filters. Accepted for protocol compatibility but never inspected. | None |
filter_expression | str | None | Optional boolean-style filter expression string to further constrain results. | None |
sort | Sequence[str] | None | Signed fields accepted for protocol compatibility. | None |
limit | int | Maximum number of results to return. | 10 |
offset | int | Number of results to skip (for pagination). | 0 |
types | Sequence[str] | None | Optional sequence of document types to restrict the search to. | None |
Returns:
| Name | Type | Description |
|---|---|---|
SearchResult | SearchResult | The search result containing matching documents and metadata. |
Raises:
| Type | Description |
|---|---|
SearchBackendNotImplementedError | Always raised by this backend stub indicating OpenSearch is not implemented. |
general_manager.search.backends.typesense.TypesenseBackend ¶
Typesense backend placeholder.
The adapter is publicly importable for configuration compatibility, but it is not implemented. Construction and every backend operation raise SearchBackendNotImplementedError.
__init__ ¶
__init__(*_, **__)
Constructor for TypesenseBackend that indicates the backend is not implemented.
Raises:
| Type | Description |
|---|---|
SearchBackendNotImplementedError | Always raised with message "Typesense" to signal the backend is not implemented. |
ensure_index ¶
ensure_index(index_name, settings)
Ensure an index with the given name and settings exists in the backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Name of the index to create or ensure. | required |
settings | Mapping[str, object] | Index configuration to apply. The value is accepted for protocol compatibility but never inspected. | required |
Raises:
| Type | Description |
|---|---|
SearchBackendNotImplementedError | Always raised because the Typesense backend is not implemented. |
upsert ¶
upsert(index_name, documents)
Insert or update the given documents in the specified index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Name of the index where documents should be upserted. | required |
documents | Sequence[SearchDocument] | Documents to insert or update. | required |
Raises:
| Type | Description |
|---|---|
SearchBackendNotImplementedError | Always raised because the Typesense backend is not implemented. |
delete ¶
delete(index_name, ids)
Delete documents identified by their IDs from the specified index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Name of the index from which to delete documents. | required |
ids | Sequence[str] | Sequence of document IDs to remove. | required |
Raises:
| Type | Description |
|---|---|
SearchBackendNotImplementedError | Always raised because the Typesense backend is not implemented. |
list_document_ids ¶
list_document_ids(index_name, *, types=None)
List stored document IDs in the specified index.
Raises:
| Type | Description |
|---|---|
SearchBackendNotImplementedError | Always raised because the Typesense backend is not implemented. |
search ¶
search(
index_name,
query,
*,
filters=None,
filter_expression=None,
sort=None,
limit=10,
offset=0,
types=None
)
Perform a search against the specified index using the provided query and optional filtering, sorting, and pagination.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index_name | str | Name of the index to search. | required |
query | str | Query string to match documents. | required |
filters | Mapping[str, object] | Sequence[Mapping[str, object]] | None | Filter criteria as a single mapping or a sequence of mappings. Accepted for protocol compatibility but never inspected. | None |
filter_expression | str | None | A raw filter expression string to apply instead of or in addition to | None |
sort | Sequence[str] | None | Signed fields accepted for protocol compatibility. | None |
limit | int | Maximum number of results to return. | 10 |
offset | int | Number of results to skip (for pagination). | 0 |
types | Sequence[str] | None | Optional list of document types to restrict the search to. | None |
Returns:
| Name | Type | Description |
|---|---|---|
SearchResult | SearchResult | Search results including matched documents and metadata such as total hits and pagination info. |
Raises:
| Type | Description |
|---|---|
SearchBackendNotImplementedError | Always raised because the Typesense backend is not implemented. |