Serializer
Serializers convert a query object into a string representation. This enables the query to be rendered for human inspection, logging, or submission to search engines.
Each serializer implements a function that takes a Query object and returns a string. This supports various output formats including debugging views and platform-specific syntaxes.
Interface
Serializers are typically implemented as standalone functions. The core interface is:
#!/usr/bin/env python3
"""Example serializer template for a custom platform."""
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from search_query.query import Query
def to_string_custom(query: Query) -> str:
# Leaf node (no children)
if not query.children:
field = query.search_field.value if query.search_field else ""
return f"{field}{query.value}"
# Composite node (operator with children)
serialized_children = [to_string_custom(child) for child in query.children]
joined_children = f" {query.value} ".join(serialized_children)
# Add parentheses to clarify grouping
if len(query.children) > 1:
joined_children = f"({joined_children})"
# Prefix with field if applicable
if query.search_field:
return f"{query.search_field.value}{joined_children}"
return joined_children
Serializers follow a shared conceptual pattern:
Accept a Query object.
Recursively traverse the query tree.
Render each node (logical operator, term, field) into a string.
Combine child nodes with appropriate formatting and syntax.
Note
Avoid embedding platform-specific validation logic (use linters for that).