Query your own data

FeatureMesh translates FeatureQL to SQL and runs that SQL through a function you give it, the SQL executor. To query your own tables, give the client an executor bound to your connection. FeatureMesh never copies your data: the SQL runs where the tables are.

DuckDB tables and pandas DataFrames

Without an executor, BatchClient() runs SQL on a fresh in-memory DuckDB that holds none of your tables. Pass your own connection instead. A DataFrame registered on that connection is a table like any other:

import duckdb
import pandas as pd
from featuremesh import BatchClient
from featuremesh.utils.duckdb_sql import run_duckdb_script

con = duckdb.connect("shop.duckdb")         # or duckdb.connect() for memory only
orders = pd.DataFrame({"order_id": [10, 11, 12], "customer_id": [1, 1, 2], "amount": [20.0, 5.5, 12.0]})
con.register("orders", orders)              # the DataFrame is now the table `orders`

client = BatchClient(sql_executor=lambda sql: run_duckdb_script(con, sql))
python

run_duckdb_script keeps DECIMAL values exact and SQL NULL as None. A plain lambda sql: con.sql(sql).df() also works, but turns decimals into floats and NULL into NaN.

A first query on your tables

With a customers table (customer_id, name) next to orders, this returns each customer's name, number of orders and total spent:

result = client.query("""
DEFINE
    CUSTOMERS := ENTITY(),
    CUSTOMER_ID := INPUT(BIGINT#CUSTOMERS),
    CUSTOMER := EXTERNAL_COLUMNS(customer_id BIGINT#CUSTOMERS BIND TO CUSTOMER_ID, name VARCHAR
        FROM TABLE(customers)),
    ORDER_KEYS := ENTITY(),
    ORDER_ID := INPUT(BIGINT#ORDER_KEYS),
    ORDERS := EXTERNAL_COLUMNS(order_id BIGINT#ORDER_KEYS BIND TO ORDER_ID,
        customer_id BIGINT#CUSTOMERS, amount DOUBLE
        FROM TABLE(orders)),
    NUM_ORDERS := CUSTOMER_ID.RELATED(COUNT() GROUP BY (ORDERS[customer_id])),
    TOTAL_SPENT := CUSTOMER_ID.RELATED(SUM(ORDERS[amount]) GROUP BY (ORDERS[customer_id]))
RETURN
    CUSTOMER_ID, CUSTOMER[name] AS NAME, NUM_ORDERS, TOTAL_SPENT
FOR
    CUSTOMER_ID := BIND_COLUMNS(customer_id FROM TABLE(customers)),
    NESTED ORDER_ID := BIND_COLUMNS(order_id FROM TABLE(orders))
ORDER BY CUSTOMER_ID;
""")
print(result.dataframe)
python
  CUSTOMER_ID   NAME NUM_ORDERS TOTAL_SPENT
0           1  Alice          2        25.5
1           2    Bob          1        12.0
2           3  Chloe          0        None
text

What each part does:

  • EXTERNAL_COLUMNS(… FROM TABLE(orders)) declares the columns FeatureQL reads from a table, with their types. BIND TO names the column that identifies a row.
  • ENTITY() and #CUSTOMERS say which columns hold the same kind of key, so RELATED(… GROUP BY (ORDERS[customer_id])) can sum each customer's orders.
  • FOR says which keys to compute: every customer in customers, over every order in orders. A customer without orders gets 0 orders and a NULL total.

The model behind this, one entity and its related tables, is in For the impatient and Entities .

Other databases

backend says which SQL dialect to write, and the executor runs it. The executor takes a SQL string and returns a pandas DataFrame. A query can run in several steps that must share one connection, so keep one connection per thread:

import threading
import pandas as pd
import psycopg
from featuremesh import BatchClient

_local = threading.local()

def run_on_postgres(sql: str) -> pd.DataFrame:
    if not hasattr(_local, "conn"):
        _local.conn = psycopg.connect("postgresql://user@db:5432/shop", autocommit=True)
    with _local.conn.cursor() as cur:
        cur.execute(sql)
        if cur.description is None:
            return pd.DataFrame()
        return pd.DataFrame(cur.fetchall(), columns=[c.name for c in cur.description])

client = BatchClient(backend="postgres", sql_executor=run_on_postgres)
python

Tables are named as your database names them: FROM TABLE(sales.orders). The backends are duckdb, postgres, mysql, trino, snowflake, databricks, bigquery and clickhouse. Without an executor, client.translate(...) still writes the SQL for any of them, for you to run yourself.

Where definitions are kept

Feature definitions you persist with CREATE FEATURES go to the registry, not to your database. In local mode that is a SQLite file, featuremesh.db in the current folder, created on first use. Change it with set_default("local.db_path", "/path/to/project.db").

Next