Query System API¶
This section provides the complete API reference for QuantumEngine’s query system.
Base Query Classes¶
- class quantumengine.query.base.QuerySet(document_class, connection=None)[source]¶
Bases:
BaseQuerySet
,Generic
[T
]Query builder for SurrealDB with generic type safety.
This class provides a query builder for document classes with a predefined schema. It extends BaseQuerySet to provide methods for querying and manipulating documents of a specific document class.
- Type Parameters:
T: The document class type that this QuerySet operates on
- document_class¶
The document class to query
- connection¶
The database connection to use for queries
- async join(field_name, target_fields=None, dereference=True, dereference_depth=1)[source]¶
Perform a JOIN-like operation on a reference field using FETCH.
This method performs a JOIN-like operation on a reference field by using SurrealDB’s FETCH clause to efficiently resolve references in a single query.
- Parameters:
field_name (str) – The name of the reference field to join on
target_fields (List[str] | None) – Optional list of fields to select from the target document
dereference (bool) – Whether to dereference references in the joined documents (default: True)
dereference_depth (int) – Maximum depth of reference resolution (default: 1)
- Returns:
List of documents with joined data
- Raises:
ValueError – If the field is not a ReferenceField
- Return type:
- join_sync(field_name, target_fields=None, dereference=True, dereference_depth=1)[source]¶
Perform a JOIN-like operation on a reference field synchronously using FETCH.
This method performs a JOIN-like operation on a reference field by using SurrealDB’s FETCH clause to efficiently resolve references in a single query.
- Parameters:
field_name (str) – The name of the reference field to join on
target_fields (List[str] | None) – Optional list of fields to select from the target document
dereference (bool) – Whether to dereference references in the joined documents (default: True)
dereference_depth (int) – Maximum depth of reference resolution (default: 1)
- Returns:
List of documents with joined data
- Raises:
ValueError – If the field is not a ReferenceField
- Return type:
- async all(dereference=False)[source]¶
Execute the query and return all results asynchronously.
This method builds and executes the query, then converts the results to instances of the document class. Includes automatic retry on transient failures.
- all_sync(dereference=False)[source]¶
Execute the query and return all results synchronously.
This method builds and executes the query, then converts the results to instances of the document class. Includes automatic retry on transient failures.
- async count()[source]¶
Count documents matching the query asynchronously.
This method builds and executes a count query to count the number of documents matching the query. Includes automatic retry on transient failures.
- Returns:
Number of matching documents
- Return type:
- count_sync()[source]¶
Count documents matching the query synchronously.
This method builds and executes a count query to count the number of documents matching the query. Includes automatic retry on transient failures.
- Returns:
Number of matching documents
- Return type:
- async get(dereference=False, **kwargs)[source]¶
Get a single document matching the query asynchronously.
This method applies filters and ensures that exactly one document is returned.
- Parameters:
- Returns:
The matching document
- Raises:
DoesNotExist – If no matching document is found
MultipleObjectsReturned – If multiple matching documents are found
- Return type:
T
- get_sync(dereference=False, **kwargs)[source]¶
Get a single document matching the query synchronously.
This method applies filters and ensures that exactly one document is returned.
- Parameters:
- Returns:
The matching document
- Raises:
DoesNotExist – If no matching document is found
MultipleObjectsReturned – If multiple matching documents are found
- Return type:
T
- async create(**kwargs)[source]¶
Create a new document asynchronously.
This method creates a new document with the given field values. Includes automatic retry on transient failures.
- Parameters:
**kwargs (Any) – Field names and values for the new document
- Returns:
The created document
- Return type:
T
- create_sync(**kwargs)[source]¶
Create a new document synchronously.
This method creates a new document with the given field values. Includes automatic retry on transient failures.
- Parameters:
**kwargs (Any) – Field names and values for the new document
- Returns:
The created document
- Return type:
T
- async update(**kwargs)[source]¶
Update documents matching the query asynchronously with performance optimizations.
This method updates documents matching the query with the given field values. Uses direct record access for bulk ID operations for better performance.
- update_sync(**kwargs)[source]¶
Update documents matching the query synchronously with performance optimizations.
This method updates documents matching the query with the given field values. Uses direct record access for bulk ID operations for better performance.
- async delete()[source]¶
Delete documents matching the query asynchronously with performance optimizations.
This method deletes documents matching the query. Uses direct record access for bulk ID operations for better performance.
- Returns:
Number of deleted documents
- Return type:
- delete_sync()[source]¶
Delete documents matching the query synchronously with performance optimizations.
This method deletes documents matching the query. Uses direct record access for bulk ID operations for better performance.
- Returns:
Number of deleted documents
- Return type:
- async bulk_create(documents, batch_size=1000, validate=True, return_documents=True)[source]¶
Create multiple documents in a single operation asynchronously.
This method creates multiple documents in a single operation, processing them in batches for better performance. It can optionally validate the documents and return the created documents.
- Parameters:
- Returns:
List of created documents with their IDs set if return_documents=True, otherwise returns the count of created documents
- Return type:
- bulk_create_sync(documents, batch_size=1000, validate=True, return_documents=True)[source]¶
Create multiple documents in a single operation synchronously.
This method creates multiple documents in a single operation, processing them in batches for better performance. It can optionally validate the documents and return the created documents.
- Parameters:
- Returns:
List of created documents with their IDs set if return_documents=True, otherwise returns the count of created documents
- Return type:
- async explain()[source]¶
Get query execution plan for performance analysis.
This method appends EXPLAIN to the query to show how the database will execute it, helping identify performance bottlenecks.
Example
plan = await User.objects.filter(age__lt=18).explain() print(f”Query will use: {plan[0][‘operation’]}”)
- Raises:
NotImplementedError – If backend doesn’t support EXPLAIN queries
- suggest_indexes()[source]¶
Suggest indexes based on current query patterns.
Analyzes the current query conditions and suggests optimal indexes that could improve performance.
Example
>>> suggestions = User.objects.filter(age__lt=18, city="NYC").suggest_indexes() >>> for suggestion in suggestions: ... print(f"Consider: {suggestion}")
QuerySet¶
The main query interface for database operations.
- class quantumengine.query.base.QuerySet(document_class, connection=None)[source]¶
Bases:
BaseQuerySet
,Generic
[T
]Query builder for SurrealDB with generic type safety.
This class provides a query builder for document classes with a predefined schema. It extends BaseQuerySet to provide methods for querying and manipulating documents of a specific document class.
- Type Parameters:
T: The document class type that this QuerySet operates on
- document_class¶
The document class to query
- connection¶
The database connection to use for queries
- async join(field_name, target_fields=None, dereference=True, dereference_depth=1)[source]¶
Perform a JOIN-like operation on a reference field using FETCH.
This method performs a JOIN-like operation on a reference field by using SurrealDB’s FETCH clause to efficiently resolve references in a single query.
- Parameters:
field_name (str) – The name of the reference field to join on
target_fields (List[str] | None) – Optional list of fields to select from the target document
dereference (bool) – Whether to dereference references in the joined documents (default: True)
dereference_depth (int) – Maximum depth of reference resolution (default: 1)
- Returns:
List of documents with joined data
- Raises:
ValueError – If the field is not a ReferenceField
- Return type:
- join_sync(field_name, target_fields=None, dereference=True, dereference_depth=1)[source]¶
Perform a JOIN-like operation on a reference field synchronously using FETCH.
This method performs a JOIN-like operation on a reference field by using SurrealDB’s FETCH clause to efficiently resolve references in a single query.
- Parameters:
field_name (str) – The name of the reference field to join on
target_fields (List[str] | None) – Optional list of fields to select from the target document
dereference (bool) – Whether to dereference references in the joined documents (default: True)
dereference_depth (int) – Maximum depth of reference resolution (default: 1)
- Returns:
List of documents with joined data
- Raises:
ValueError – If the field is not a ReferenceField
- Return type:
- async all(dereference=False)[source]¶
Execute the query and return all results asynchronously.
This method builds and executes the query, then converts the results to instances of the document class. Includes automatic retry on transient failures.
- all_sync(dereference=False)[source]¶
Execute the query and return all results synchronously.
This method builds and executes the query, then converts the results to instances of the document class. Includes automatic retry on transient failures.
- async count()[source]¶
Count documents matching the query asynchronously.
This method builds and executes a count query to count the number of documents matching the query. Includes automatic retry on transient failures.
- Returns:
Number of matching documents
- Return type:
- count_sync()[source]¶
Count documents matching the query synchronously.
This method builds and executes a count query to count the number of documents matching the query. Includes automatic retry on transient failures.
- Returns:
Number of matching documents
- Return type:
- async get(dereference=False, **kwargs)[source]¶
Get a single document matching the query asynchronously.
This method applies filters and ensures that exactly one document is returned.
- Parameters:
- Returns:
The matching document
- Raises:
DoesNotExist – If no matching document is found
MultipleObjectsReturned – If multiple matching documents are found
- Return type:
T
- get_sync(dereference=False, **kwargs)[source]¶
Get a single document matching the query synchronously.
This method applies filters and ensures that exactly one document is returned.
- Parameters:
- Returns:
The matching document
- Raises:
DoesNotExist – If no matching document is found
MultipleObjectsReturned – If multiple matching documents are found
- Return type:
T
- async create(**kwargs)[source]¶
Create a new document asynchronously.
This method creates a new document with the given field values. Includes automatic retry on transient failures.
- Parameters:
**kwargs (Any) – Field names and values for the new document
- Returns:
The created document
- Return type:
T
- create_sync(**kwargs)[source]¶
Create a new document synchronously.
This method creates a new document with the given field values. Includes automatic retry on transient failures.
- Parameters:
**kwargs (Any) – Field names and values for the new document
- Returns:
The created document
- Return type:
T
- async update(**kwargs)[source]¶
Update documents matching the query asynchronously with performance optimizations.
This method updates documents matching the query with the given field values. Uses direct record access for bulk ID operations for better performance.
- update_sync(**kwargs)[source]¶
Update documents matching the query synchronously with performance optimizations.
This method updates documents matching the query with the given field values. Uses direct record access for bulk ID operations for better performance.
- async delete()[source]¶
Delete documents matching the query asynchronously with performance optimizations.
This method deletes documents matching the query. Uses direct record access for bulk ID operations for better performance.
- Returns:
Number of deleted documents
- Return type:
- delete_sync()[source]¶
Delete documents matching the query synchronously with performance optimizations.
This method deletes documents matching the query. Uses direct record access for bulk ID operations for better performance.
- Returns:
Number of deleted documents
- Return type:
- async bulk_create(documents, batch_size=1000, validate=True, return_documents=True)[source]¶
Create multiple documents in a single operation asynchronously.
This method creates multiple documents in a single operation, processing them in batches for better performance. It can optionally validate the documents and return the created documents.
- Parameters:
- Returns:
List of created documents with their IDs set if return_documents=True, otherwise returns the count of created documents
- Return type:
- bulk_create_sync(documents, batch_size=1000, validate=True, return_documents=True)[source]¶
Create multiple documents in a single operation synchronously.
This method creates multiple documents in a single operation, processing them in batches for better performance. It can optionally validate the documents and return the created documents.
- Parameters:
- Returns:
List of created documents with their IDs set if return_documents=True, otherwise returns the count of created documents
- Return type:
- async explain()[source]¶
Get query execution plan for performance analysis.
This method appends EXPLAIN to the query to show how the database will execute it, helping identify performance bottlenecks.
Example
plan = await User.objects.filter(age__lt=18).explain() print(f”Query will use: {plan[0][‘operation’]}”)
- Raises:
NotImplementedError – If backend doesn’t support EXPLAIN queries
- suggest_indexes()[source]¶
Suggest indexes based on current query patterns.
Analyzes the current query conditions and suggests optimal indexes that could improve performance.
Example
>>> suggestions = User.objects.filter(age__lt=18, city="NYC").suggest_indexes() >>> for suggestion in suggestions: ... print(f"Consider: {suggestion}")
Manager¶
Document manager providing query interface.
Query Operations¶
Filtering¶
Query filtering and lookup operations.
Ordering¶
Query ordering and sorting operations.
Limiting¶
Query limiting and pagination operations.
Query Expressions¶
Query expression system for QuantumEngine
This module provides a query expression system that allows building complex queries programmatically and passing them to objects() and filter() methods.
- class quantumengine.query_expressions.Q(**kwargs)[source]¶
Bases:
object
Query expression builder for complex queries.
This class allows building complex query expressions that can be used with filter() and objects() methods.
Example
# Complex AND/OR queries query = Q(age__gt=18) & Q(active=True) users = User.objects.filter(query)
# Complex queries with objects() query = Q(department=”engineering”) | Q(department=”sales”) users = User.objects(query)
- __init__(**kwargs)[source]¶
Initialize a query expression.
- Parameters:
**kwargs – Field filters to include in the query
- class quantumengine.query_expressions.QueryExpression(where=None)[source]¶
Bases:
object
Higher-level query expression that can include fetch, grouping, etc.
This class provides a more comprehensive query building interface that includes not just WHERE conditions but also FETCH, GROUP BY, etc.
- __init__(where=None)[source]¶
Initialize a query expression.
- Parameters:
where (Q | None) – Q object for WHERE clause conditions
- fetch(*fields)[source]¶
Add FETCH clause to resolve references.
- Parameters:
*fields (str) – Field names to fetch
- Returns:
Self for method chaining
- Return type:
- group_by(*fields)[source]¶
Add GROUP BY clause.
- Parameters:
*fields (str) – Field names to group by
- Returns:
Self for method chaining
- Return type:
- order_by(field, direction='ASC')[source]¶
Add ORDER BY clause.
- Parameters:
- Returns:
Self for method chaining
- Return type:
- limit(value)[source]¶
Add LIMIT clause.
- Parameters:
value (int) – Maximum number of results
- Returns:
Self for method chaining
- Return type:
Q Objects¶
Complex query construction with Q objects.
- class quantumengine.query_expressions.Q(**kwargs)[source]¶
Bases:
object
Query expression builder for complex queries.
This class allows building complex query expressions that can be used with filter() and objects() methods.
Example
# Complex AND/OR queries query = Q(age__gt=18) & Q(active=True) users = User.objects.filter(query)
# Complex queries with objects() query = Q(department=”engineering”) | Q(department=”sales”) users = User.objects(query)
- __init__(**kwargs)[source]¶
Initialize a query expression.
- Parameters:
**kwargs – Field filters to include in the query
Field References¶
Reference fields in queries and expressions.
Conditional Expressions¶
Conditional logic in queries.
Lookup Operations¶
Field lookup operations for filtering.
Aggregation¶
Aggregation pipeline for SurrealEngine.
This module provides support for building and executing aggregation pipelines in SurrealEngine. Aggregation pipelines allow for complex data transformations and analysis through a series of stages.
- class quantumengine.aggregation.AggregationPipeline(query_set)[source]¶
Bases:
object
Pipeline for building and executing aggregation queries.
This class provides a fluent interface for building complex aggregation pipelines with multiple stages, similar to MongoDB’s aggregation framework.
- __init__(query_set)[source]¶
Initialize a new AggregationPipeline.
- Parameters:
query_set (QuerySet) – The QuerySet to build the pipeline from
- group(by_fields=None, **aggregations)[source]¶
Group by fields and apply aggregations.
- Parameters:
by_fields – Field or list of fields to group by
**aggregations – Named aggregation functions to apply
- Returns:
The pipeline instance for method chaining
- project(**fields)[source]¶
Select or compute fields to include in output.
- Parameters:
**fields – Field mappings for projection
- Returns:
The pipeline instance for method chaining
- sort(**fields)[source]¶
Sort results by fields.
- Parameters:
**fields – Field names and sort directions (‘ASC’ or ‘DESC’)
- Returns:
The pipeline instance for method chaining
- limit(count)[source]¶
Limit number of results.
- Parameters:
count – Maximum number of results to return
- Returns:
The pipeline instance for method chaining
- skip(count)[source]¶
Skip number of results.
- Parameters:
count – Number of results to skip
- Returns:
The pipeline instance for method chaining
- with_index(index)[source]¶
Use the specified index for the query.
- Parameters:
index – Name of the index to use
- Returns:
The pipeline instance for method chaining
- build_query()[source]¶
Build the SurrealQL query from the pipeline stages.
- Returns:
The SurrealQL query string
Aggregate Functions¶
Statistical and mathematical aggregate functions.
Grouping Operations¶
Group by and annotation operations.
Relationship Queries¶
- class quantumengine.query.relation.RelationQuerySet(from_document, connection, relation=None)[source]¶
Bases:
object
Query set specifically for graph relations.
This class provides methods for querying and manipulating graph relations between documents in the database. It allows creating, retrieving, updating, and deleting relations between documents.
- from_document¶
The document class the relation is from
- connection¶
The database connection to use for queries
- relation¶
The name of the relation
- query_parts¶
List of query parts
- async relate(from_instance, to_instance, **attrs)[source]¶
Create a relation between two instances asynchronously.
This method creates a relation between two document instances in the database. It constructs a RELATE query with the given relation name and attributes.
- Parameters:
- Returns:
The created relation record or None if creation failed
- Raises:
ValueError – If either instance is not saved or if no relation name is specified
- Return type:
Any | None
- relate_sync(from_instance, to_instance, **attrs)[source]¶
Create a relation between two instances synchronously.
This method creates a relation between two document instances in the database. It constructs a RELATE query with the given relation name and attributes.
- Parameters:
- Returns:
The created relation record or None if creation failed
- Raises:
ValueError – If either instance is not saved or if no relation name is specified
- Return type:
Any | None
Get related documents asynchronously.
This method retrieves documents related to the given instance through the specified relation. It can return either the target documents or the relation records themselves.
- Parameters:
- Returns:
List of related documents or relation records
- Raises:
ValueError – If the instance is not saved or if no relation name is specified
- Return type:
Get related documents synchronously.
This method retrieves documents related to the given instance through the specified relation. It can return either the target documents or the relation records themselves.
- Parameters:
- Returns:
List of related documents or relation records
- Raises:
ValueError – If the instance is not saved or if no relation name is specified
- Return type:
- async update_relation(from_instance, to_instance, **attrs)[source]¶
Update an existing relation asynchronously.
This method updates an existing relation between two document instances in the database. If the relation doesn’t exist, it creates it.
- Parameters:
- Returns:
The updated relation record or None if update failed
- Raises:
ValueError – If either instance is not saved or if no relation name is specified
- Return type:
Any | None
- update_relation_sync(from_instance, to_instance, **attrs)[source]¶
Update an existing relation synchronously.
This method updates an existing relation between two document instances in the database. If the relation doesn’t exist, it creates it.
- Parameters:
- Returns:
The updated relation record or None if update failed
- Raises:
ValueError – If either instance is not saved or if no relation name is specified
- Return type:
Any | None
- async delete_relation(from_instance, to_instance=None)[source]¶
Delete a relation asynchronously.
This method deletes a relation between two document instances in the database. If to_instance is not provided, it deletes all relations from from_instance.
- Parameters:
- Returns:
Number of deleted relations
- Raises:
ValueError – If from_instance is not saved, if to_instance is provided but not saved, or if no relation name is specified
- Return type:
- delete_relation_sync(from_instance, to_instance=None)[source]¶
Delete a relation synchronously.
This method deletes a relation between two document instances in the database. If to_instance is not provided, it deletes all relations from from_instance.
- Parameters:
- Returns:
Number of deleted relations
- Raises:
ValueError – If from_instance is not saved, if to_instance is provided but not saved, or if no relation name is specified
- Return type:
Reverse Relationships¶
Handle reverse foreign key relationships.
Graph Traversal¶
SurrealDB-specific graph traversal operations.
Backend-Specific Query Features¶
SurrealDB Queries¶
SurrealDB-specific query features and optimizations.
ClickHouse Queries¶
ClickHouse-specific query features and optimizations.
Raw Queries¶
Execute raw database queries when needed.
Query Compilation¶
Query compilation and optimization.
Query Compiler¶
Base query compiler for all backends.
Backend Compilers¶
Backend-specific query compilation.
Query Optimization¶
Query analysis and optimization tools.
Query Analyzer¶
Analyze query performance and structure.
Performance Monitoring¶
Monitor query performance and statistics.
Transaction Support¶
Transaction management for queries.
Transaction Context¶
Atomic transaction operations.
Search Operations¶
Full-text search and indexing.
Text Search¶
Full-text search capabilities.
Vector Search¶
Vector similarity search operations.
Bulk Operations¶
Efficient bulk database operations.
Bulk Creation¶
Bulk insert operations.
Bulk Updates¶
Bulk update operations.
Bulk Deletion¶
Bulk delete operations.
Query Utilities¶
Utility functions for query operations.
Query Helpers¶
Helper functions for common query operations.
Field Validation¶
Query field validation utilities.
See Also¶
Query System - Comprehensive query system guide
Backends - Backend-specific query features
Fields - Field types and query compatibility
Exceptions - Exception handling for queries