Factories & building
Start a typed expression and render it with explicit dialect and resource limits.
Every expression starts with a factory. Import QueryBuilder as Q; a Python string passed to function() is a literal, never a parsed query. Building returns text and does not perform I/O.
from metricraft import QueryBuilder as Q
base = Q.from_metric("http_requests_total").where_eq("job", "api")
query = base.rate("5m").sum().by("job")
print(query.build(mode="promql"))
The default dialect is MetricsQL. Select PromQL explicitly for Prometheus. Type checks can happen during construction; dialect and output-budget checks also inspect the complete expression at build time. TypeError signals incompatible Python inputs; ValueError reports invalid native construction or build constraints.
Methods and parameters
QueryBuilder
QueryBuilder()Create a stateless factory. Prefer the class-level from_* factories to start an expression.
QueryBuilder(*args: object, **kwargs: object) -> None
| Parameter / type | Meaning and accepted values |
|---|---|
*argsnot acceptedVariadic | No positional or keyword configuration is accepted. Use Q.from_metric(...) and build(mode=...). |
**kwargsnot acceptedVariadic | No positional or keyword configuration is accepted. Use Q.from_metric(...) and build(mode=...). |
Returns QueryBuilder — a stateless factory; start a from_* expression before building.
build()Validate the complete expression for a dialect and render query text. This does not send a request or evaluate data.
QueryBuilder.build(mode: BuildMode=QueryMode.METRICSQL, *, max_output_bytes: Optional[int]=None, max_expanded_nodes: Optional[int]=None, experimental_functions: bool=False, features: Iterable[str]=()) -> str
| Parameter / type | Meaning and accepted values |
|---|---|
modeQueryMode | strDefault: QueryMode.METRICSQL | 'promql' or 'metricsql' (default). Checks the entire expression, including dialect-specific argument forms. |
max_output_bytesint | NoneDefault: None | Positive integer byte budget; None uses the native 1 MiB default. bool and zero are rejected. Applies to UTF-8 output, not character count. |
max_expanded_nodesint | NoneDefault: None | Positive integer expression-occurrence budget; None uses 100,000. Repeated references count each time rendered, even when the tree shares storage. |
experimental_functionsboolDefault: False | Opt into Prometheus experimental functions. The backend must also enable the corresponding feature; this flag does not configure the server. |
featuresIterable[str]Default: () | Explicit feature names: 'promql-experimental-functions', 'promql-duration-expr', 'promql-extended-range-selectors', 'promql-binop-fill-modifiers'. Each requires matching server support. Pass a collection, not one string. |
Returns str — validated query text, ready for storage or a client request.
Example
from metricraft import QueryBuilder as Q
Q.from_metric("up").build(mode="promql", max_output_bytes=4096)from_duration()Create a typed scalar duration, expressed in seconds when rendered. MetricsQL step-relative units remain query-time expressions.
QueryBuilder.from_duration(value: str) -> QueryBuilder
| Parameter / type | Meaning and accepted values |
|---|---|
valuestrRequired | Duration literal such as '5m'. MetricsQL supports fractional and interval-relative units (for example '1.5i'); dialect checks apply at build. |
Returns QueryBuilder — a new immutable expression sharing unchanged native subtrees. The receiver is unchanged; no data is queried.
Example
from metricraft import QueryBuilder as Q
Q.from_duration("5m").build(mode="metricsql")from_labels()Start an unnamed selector from equality matchers. In PromQL, at least one matcher must exclude the empty label value.
QueryBuilder.from_labels(**labels: str) -> QueryBuilder
| Parameter / type | Meaning and accepted values |
|---|---|
**labelsstr, by keywordVariadic | Label-name/string-value pairs, e.g. job='api'. Use **mapping for names that are not Python identifiers. |
Returns QueryBuilder — a new immutable expression sharing unchanged native subtrees. The receiver is unchanged; no data is queried.
Example
from metricraft import QueryBuilder as Q Q.from_labels(job="api").build(mode="promql")
from_metric()Start an instant-vector selector for a metric. The name is encoded as data, including names that require quoting.
QueryBuilder.from_metric(name: str) -> QueryBuilder
| Parameter / type | Meaning and accepted values |
|---|---|
namestrRequired | Nonempty metric/function/binding name. It is validated by the relevant constructor, not inserted as raw query syntax. |
Returns QueryBuilder — a new immutable expression sharing unchanged native subtrees. The receiver is unchanged; no data is queried.
Example
from metricraft import QueryBuilder as Q
Q.from_metric("http_requests_total").where_eq("job", "api").build(mode="promql")from_numeric_literal()Parse and normalize numeric notation, including MetricsQL SI and binary suffixes; arbitrary query text is rejected.
QueryBuilder.from_numeric_literal(value: str) -> QueryBuilder
| Parameter / type | Meaning and accepted values |
|---|---|
valuestrRequired | Numeric notation such as '1.25', '2K' or '4Mi'. Supported suffixes are K/M/G/T and Ki/Mi/Gi/Ti (case-sensitive); underscores are removed. Values normalize to ordinary scalars and can build in either dialect. Extra query tokens and suffix overflow are rejected. |
Returns QueryBuilder — a new immutable expression sharing unchanged native subtrees. The receiver is unchanged; no data is queried.
Example
from metricraft import QueryBuilder as Q
Q.from_numeric_literal("2K").build(mode="promql")from_scalar()Create a scalar numeric literal. Python booleans are rejected even though bool inherits from int.
QueryBuilder.from_scalar(value: Number) -> QueryBuilder
Native scalars use f64: Python integers outside exact IEEE-754 integer precision may round.
| Parameter / type | Meaning and accepted values |
|---|---|
valueint | floatRequired | Numeric literal, including IEEE NaN/infinity. bool is rejected; values use the native floating-point representation. |
Returns QueryBuilder — a new immutable expression sharing unchanged native subtrees. The receiver is unchanged; no data is queried.
Example
from metricraft import QueryBuilder as Q Q.from_scalar(42).build(mode="promql")
from_string()Create an escaped string literal for function arguments. This never parses a string as a query.
QueryBuilder.from_string(value: str) -> QueryBuilder
| Parameter / type | Meaning and accepted values |
|---|---|
valuestrRequired | Literal string contents. Quotes, backslashes and control characters are escaped; arbitrary query text is never parsed. |
Returns QueryBuilder — a new immutable expression sharing unchanged native subtrees. The receiver is unchanged; no data is queried.
from_tuple()Create a nonempty MetricsQL tuple of uniformly scalar or uniformly string expressions.
QueryBuilder.from_tuple(*values: QueryInput) -> QueryBuilder
| Parameter / type | Meaning and accepted values |
|---|---|
*valuesint | float | str | QueryBuilder, ...Variadic | Nonempty uniformly scalar or uniformly string tuple. Comparison tuples must have the appropriate numeric type. |
Returns QueryBuilder — a new immutable expression sharing unchanged native subtrees. The receiver is unchanged; no data is queried.
function()Call a function in the Rust signature catalog with typed arguments. Unknown functions and incompatible argument types are rejected.
QueryBuilder.function(name: str, *args: QueryInput) -> QueryBuilder
Strings are literals. Use Q.from_metric('up') for an expression; function('rate', 'up[5m]') does not parse the argument as a query.
| Parameter / type | Meaning and accepted values |
|---|---|
namestrRequired | Nonempty metric/function/binding name. It is validated by the relevant constructor, not inserted as raw query syntax. |
*argsQueryBuilder | int | float | str, ...Variadic | Typed function arguments in upstream order. Strings become literals; numeric/vector/range types and arity are checked by Rust. |
Returns QueryBuilder — a new immutable expression sharing unchanged native subtrees. The receiver is unchanged; no data is queried.
Example
from metricraft import QueryBuilder as Q
Q.function("rate", Q.from_metric("requests_total").range("5m")).build(mode="promql")vector()Convert one scalar expression into an instant vector with an empty label set.
QueryBuilder.vector(value: ScalarInput) -> QueryBuilder
| Parameter / type | Meaning and accepted values |
|---|---|
valueint | float | QueryBuilderRequired | Numeric scalar or scalar expression; Python bool is rejected. Computed values are evaluated by the backend. |
Returns QueryBuilder — a new immutable expression sharing unchanged native subtrees. The receiver is unchanged; no data is queried.