Skip to content

Search API

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 boost is not None and is less than or equal to zero.

__post_init__

__post_init__()

Validate the configured boost value after initialization.

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 FieldConfig entries, in priority order.

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

Raises:

Type Description
InvalidIndexBoostError

If boost is not None and is less than or equal to zero.

InvalidIndexMinScoreError

If min_score is not None and is less than zero.

__post_init__

__post_init__()

Validate index-level boost and minimum score after initialization.

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 FieldConfig entries have already been validated at construction time.

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 fields order.

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.

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.

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 attributes from config, using default values when attributes are missing. Missing indexes and invalidation_rules resolve to empty tuples.

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 None when config is None.

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 None.

required

Returns:

Type Description
Iterable[str]

A list of index names in the same order as config.indexes, or an empty

Iterable[str]

list when config is None.

FieldConfig and IndexConfig validate only numeric boost/min-score bounds 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.

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 standard id input;
  • 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 "type" field.

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 GeneralManagerMeta.all_classes whose resolved

Iterable[type[GeneralManager]]

SearchConfig is present and contains one or more IndexConfig values,

Iterable[type[GeneralManager]]

preserving GeneralManagerMeta.all_classes order.

Raises:

Type Description
Exception

Errors from resolve_search_config() propagate for malformed manager search configuration.

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 for the manager, or None if the

SearchConfigSpec | None

manager does not define SearchConfig.

Raises:

Type Description
Exception

Errors from resolve_search_config() propagate for malformed manager search configuration.

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, or None when the manager has no

IndexConfig | None

search config or no index with that name.

Raises:

Type Description
Exception

Errors from resolve_search_config() propagate through get_search_config() for malformed manager search configuration.

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]]

(manager_class, index_config) for each manager whose first matching

Iterable[tuple[type[GeneralManager], IndexConfig]]

IndexConfig has name == index_name, preserving searchable manager

Iterable[tuple[type[GeneralManager], IndexConfig]]

order.

Raises:

Type Description
Exception

Errors from resolve_search_config() propagate while searchable managers are discovered.

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 SearchConfig.type_label when configured; otherwise the

str

manager class name.

Raises:

Type Description
Exception

Errors from resolve_search_config() propagate through get_search_config() for malformed manager search configuration.

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]]

GeneralManagerMeta.all_classes overwrites the earlier one without a

dict[str, type[GeneralManager]]

warning or error.

Raises:

Type Description
Exception

Errors from resolve_search_config() propagate while searchable managers are discovered.

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 "type" filter is always included.

SearchIndexSettings

Duplicate boosts keep the highest configured value; missing boosts do

SearchIndexSettings

not create a field boost entry. Boosts are collected only from

SearchIndexSettings

IndexConfig.iter_fields() entries and therefore correspond to fields

SearchIndexSettings

included in searchable_fields.

Raises:

Type Description
Exception

Errors from resolve_search_config() propagate while searchable managers are discovered.

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 resolve_search_config() propagate while searchable managers are discovered.

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]

"type" field.

Raises:

Type Description
Exception

Errors from resolve_search_config() propagate while searchable managers are discovered.

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 "__"; only the portion before the first "__" is validated.

required

Raises:

Type Description
InvalidFilterFieldError

If a base filter field is not configured as filterable for the given index.

Exception

Errors from resolve_search_config() propagate while searchable managers are discovered.

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

True when exactly one row matched and was cleared.

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. 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.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.

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, one-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. None is not part of the protocol; pass an empty mapping for no settings. Backends decide which keys are supported, whether settings replace or merge with previous settings, and whether unknown keys are ignored.

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 id is used to identify and replace existing entries when present. Duplicate IDs in one call and partial-write behavior after a batch failure are adapter-defined. Backends may retain references to document payloads unless their adapter documents copy-on-write behavior.

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 includes every type stored in the index.

None

Returns:

Type Description
set[str]

Backend document IDs in their original GeneralManager form, for

set[str]

example the same strings passed as SearchDocument.id such as

set[str]

"Project:{'id': 1}".

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_by=None,
    sort_desc=False,
    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 field__in, where __ is the conventional suffix delimiter. The portable field namespace is SearchDocument.data; types handles type labels separately. Nested-field syntax, if any, is adapter-specific. A sequence of mappings represents backend-specific grouped filtering, typically OR between groups.

None
filter_expression str | None

Optional backend-specific boolean expression. When provided, concrete backends define precedence relative to filters and types. The portable protocol intentionally makes no precedence promise beyond passing all supplied values to the adapter.

None
sort_by str | None

Field name to sort results by.

None
sort_desc bool

If true, sort results in descending order.

False
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, and any raw backend response.

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 filter_expression may be reported as a backend-specific exception such as NotImplementedError. Adapters should normalize operational failures only when doing so does not hide useful backend-native context.

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.

__init__

__init__(message=None)

Initialize the error with a message indicating no search backend is configured.

from_setting classmethod

from_setting(backend_setting)

Build an error message from a backend setting with secrets masked.

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 None to clear the configured backend so the next get_search_backend() call reads settings and may install the development fallback.

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:

  • None or missing to clear the active backend.
  • A SearchBackend instance.
  • A dotted import path to a SearchBackend instance, 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 options value that is not a mapping.

SearchBackendNotConfiguredError

If a non-None backend setting cannot be resolved to a SearchBackend.

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.

Returns:

Type Description
SearchBackend

The configured or development fallback search backend.

Raises:

Type Description
SearchBackendNotConfiguredError

If backend configuration cannot be resolved to a valid SearchBackend.

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 IndexConfig.name cannot be resolved again for the instance manager.

Exception

Backend ensure_index and upsert, custom document id, custom document mapping, and field extraction errors propagate.

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 ensure_index and delete, custom document id, and document id construction errors propagate.

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 ensure_index and upsert, custom document id, custom document mapping, and field extraction errors propagate.

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 manager_class has search configuration but index_name is not configured for that manager.

Exception

Manager iteration, backend ensure_index, upsert, list_document_ids, and delete, custom document id, custom document mapping, and field extraction errors propagate.

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.

__init__

__init__(manager_path)

Build the manager-path validation error message.

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, 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.

__init__

__init__(action)

Build the validation error message.

general_manager.search.async_tasks.InvalidSearchManagerPathError

Bases: TypeError

Raised when a manager import path does not resolve to a manager class.

__init__

__init__()

Build the validation error message.

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.

general_manager.search.backends.dev.DevSearchBackend

Simple process-local in-memory search backend intended for development.

__init__

__init__()

Initialize the backend with an empty registry that maps index names (str) to _IndexStore instances.

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_by=None,
    sort_desc=False,
    limit=10,
    offset=0,
    types=None
)

Search an index for documents matching a query and return scored, optionally filtered and sorted hits.

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. 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 each 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_by is provided. Sorting reads one raw document data field only. 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). Python's stable sort preserves insertion order for otherwise equal keys, 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 synchronization for concurrent reads/writes.

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 SearchDocument.data field names, optionally followed by one lookup suffix separated by __. Supported lookup suffixes are exact, lt, lte, gt, gte, contains, startswith, endswith, and in; no nested data traversal is supported. A key without a suffix uses exact. Within one mapping fields are ANDed; between mappings groups are ORed. Comparisons use the shared apply_lookup() helper: string operations are case-sensitive, missing fields behave like None, incompatible mixed-type comparisons and invalid lookup/value combinations return False, and None compares only through exact.

None
filter_expression str | None

Unsupported in this backend; passing a value raises NotImplementedError.

None
sort_by str | None

One document data field name to sort results by; if omitted results are sorted by score.

None
sort_desc bool

If True, sort results in descending order for the chosen sort key.

False
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 hits (the returned page with

SearchResult

data fields included), total (matching documents before

SearchResult

pagination), and took_ms (search time in milliseconds).

Raises:

Type Description
NotImplementedError

If filter_expression is not None. Other operational failures are not normalized and may surface as ordinary Python exceptions.

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. Already-safe ids are kept unchanged when they match ^[A-Za-z0-9_-]{1,511}$. All other ids, including empty strings and Unicode strings, are 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
)

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 client is not provided.

'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 meilisearch package and instantiates a client with url and api_key; if the package is not available, raises SearchBackendClientMissingError("Meilisearch").

None

Raises:

Type Description
SearchBackendClientMissingError

The meilisearch package is not installed and no client was provided.

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.

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 waits for each settings update task to complete before returning.

Raises:

Type Description
MeilisearchTaskFailedError

A create-index or settings task fails, is canceled, or times out while polling a client without wait_for_task.

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; legacy documents without it fall back to id. The fallback also applies when gm_document_id is falsey, such as an empty string. 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_by=None,
    sort_desc=False,
    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 filters.

None
sort_by str | None

Field name to sort results by.

None
sort_desc bool

If true, sort in descending order; otherwise ascending.

False
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 type field.

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. sort_by is treated as one raw field name and the adapter appends :asc or :desc; it does not validate, split, or escape the sort field. Malformed hit entries are skipped. Missing hit id/gm_document_id and type become empty strings, missing identification and data become empty mappings, and missing _rankingScore becomes None.

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_by=None,
    sort_desc=False,
    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_by str | None

Optional field name to sort results by.

None
sort_desc bool

If true, sort results in descending order; otherwise sort ascending.

False
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_by=None,
    sort_desc=False,
    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 filters.

None
sort_by str | None

Field name to sort results by.

None
sort_desc bool

If True, sort results in descending order; ascending otherwise.

False
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.