Skip to content

String Filters

metaxy.models.filter_expression.parse_filter_string

parse_filter_string(filter_string: str) -> Expr

Parse a SQL WHERE-like string into a Narwhals expression.

The parser understands SQL WHERE clauses composed of comparison operators, logical operators, parentheses, dotted identifiers, and literal values (strings, numbers, booleans, NULL).

This functionality is implemented with SQLGlot.

Example
parse_filter_string("NOT (status = 'deleted') AND deleted_at = NULL")
# Returns: (~(nw.col("status") == "deleted")) & nw.col("deleted_at").is_null()
Source code in src/metaxy/models/filter_expression.py
def parse_filter_string(filter_string: str) -> nw.Expr:
    """Parse a SQL WHERE-like string into a Narwhals expression.

    The parser understands SQL `WHERE` clauses composed of comparison operators, logical operators, parentheses,
    dotted identifiers, and literal values (strings, numbers, booleans, ``NULL``).

    This functionality is implemented with [SQLGlot](https://sqlglot.com/).

    Example:
        ```python
        parse_filter_string("NOT (status = 'deleted') AND deleted_at = NULL")
        # Returns: (~(nw.col("status") == "deleted")) & nw.col("deleted_at").is_null()
        ```
    """
    return NarwhalsFilter.model_validate(filter_string).to_expr()