Reference

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
Parameters
Parameter / typeMeaning and accepted values
*argsnot acceptedVariadicNo positional or keyword configuration is accepted. Use Q.from_metric(...) and build(mode=...).
**kwargsnot acceptedVariadicNo 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
Parameters
Parameter / typeMeaning and accepted values
modeQueryMode | strDefault: QueryMode.METRICSQL'promql' or 'metricsql' (default). Checks the entire expression, including dialect-specific argument forms.
max_output_bytesint | NoneDefault: NonePositive 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: NonePositive integer expression-occurrence budget; None uses 100,000. Repeated references count each time rendered, even when the tree shares storage.
experimental_functionsboolDefault: FalseOpt 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.
classmethod
QueryBuilder.from_duration(value: str) -> QueryBuilder
Parameters
Parameter / typeMeaning and accepted values
valuestrRequiredDuration 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.
classmethod
QueryBuilder.from_labels(**labels: str) -> QueryBuilder
Parameters
Parameter / typeMeaning and accepted values
**labelsstr, by keywordVariadicLabel-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.
classmethod
QueryBuilder.from_metric(name: str) -> QueryBuilder
Parameters
Parameter / typeMeaning and accepted values
namestrRequiredNonempty 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.
classmethod
QueryBuilder.from_numeric_literal(value: str) -> QueryBuilder
Parameters
Parameter / typeMeaning and accepted values
valuestrRequiredNumeric 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.
classmethod
QueryBuilder.from_scalar(value: Number) -> QueryBuilder

Native scalars use f64: Python integers outside exact IEEE-754 integer precision may round.

Parameters
Parameter / typeMeaning and accepted values
valueint | floatRequiredNumeric 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.
classmethod
QueryBuilder.from_string(value: str) -> QueryBuilder
Parameters
Parameter / typeMeaning and accepted values
valuestrRequiredLiteral 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.
classmethod
QueryBuilder.from_tuple(*values: QueryInput) -> QueryBuilder
Parameters
Parameter / typeMeaning and accepted values
*valuesint | float | str | QueryBuilder, ...VariadicNonempty 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.
classmethod
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.

Parameters
Parameter / typeMeaning and accepted values
namestrRequiredNonempty metric/function/binding name. It is validated by the relevant constructor, not inserted as raw query syntax.
*argsQueryBuilder | int | float | str, ...VariadicTyped 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
Parameters
Parameter / typeMeaning and accepted values
valueint | float | QueryBuilderRequiredNumeric 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.

Explore the docs

Find your next step

Search guides, examples and the Python API.