HogQL Parser

1.3.37 · active · verified Sun Apr 12

HogQL parser is an ANTLR4-based parser for HogQL and Hog, primarily developed for internal use within the PostHog analytics platform. HogQL itself is a SQL-like query language for PostHog, acting as a translation layer over ClickHouse SQL with custom enhancements for event and person data. The `hogql-parser` package provides a Python C++ extension to convert HogQL strings into Abstract Syntax Tree (AST) nodes. While available on PyPI at version 1.3.37, its development is tightly coupled with PostHog's rapid, often bi-weekly, release cadence, meaning its API can evolve with PostHog's internal needs.

Warnings

Install

Imports

Quickstart

Demonstrates parsing a HogQL expression, a full SELECT statement, and using placeholders with AST constants to build queries.

from posthog.hogql import ast
from posthog.hogql.parser import parse_expr, parse_select

# Parse a simple HogQL expression
expr_ast = parse_expr("event = 'pageview' AND properties.$browser = 'Chrome'")
print(f"Expression AST: {expr_ast}")

# Parse a full SELECT statement
select_ast = parse_select("SELECT event, timestamp FROM events WHERE timestamp > now() - INTERVAL 7 DAY LIMIT 10")
print(f"Select Statement AST: {select_ast}")

# Example with placeholders and constants (as shown in PostHog docs)
num_last_days = 2
stmt_with_placeholder = parse_select(
    "SELECT event, timestamp FROM events WHERE {where} LIMIT 100",
    {
        'where': parse_expr(
            'timestamp > now() - INTERVAL {days} DAY',
            {'days': ast.Constant(value=num_last_days)}
        )
    }
)
print(f"Select Statement with Placeholder AST: {stmt_with_placeholder}")

view raw JSON →