Sub topic 9
Querying Runs Programmatically
This chapter covers mlflow.search_runs and the lower-level client search. It assumes you can already create runs and log parameters, metrics and tags (see the earlier chapters on logging basics). It also assumes you know basic pandas, such as selecting columns and sorting a DataFrame.
Why query by code instead of the UI
The experiment UI is good for looking at a handful of runs. Code is better when you need to do any of the following:
- Pick the best run automatically, for example before registering a model.
- Apply the same filter every time, so results are repeatable.
- Pull hundreds of runs into a DataFrame for custom plots or statistics.
- Clean up or audit runs, such as finding failed runs or runs missing a tag.
The main tool is mlflow.search_runs. It returns a pandas DataFrame by default, with one row per run.
The basic call
The example below searches one experiment by name. It keeps only runs whose test_accuracy metric is above 0.9. It sorts them from best to worst and returns at most five.
import mlflow
runs = mlflow.search_runs(
experiment_names=["/Users/<your-email>/iris-tracking"],
filter_string="metrics.test_accuracy > 0.9",
order_by=["metrics.test_accuracy DESC"],
max_results=5,
)
print(runs[["run_id", "metrics.test_accuracy"]])Replace <your-email> with your own workspace user name. On Databricks, an experiment name is its workspace path, so it must be the absolute path you used in set_experiment.
The arguments work like this:
| Argument | Meaning |
|---|---|
| `experiment_names` | A list of experiment names (paths on Databricks). |
| `experiment_ids` | A list of experiment IDs, as strings. Use this instead of names if you have the ID. |
| `filter_string` | A SQL-like condition on metrics, params, tags and run attributes. |
| `order_by` | A list of columns, each optionally followed by `ASC` or `DESC`. |
| `max_results` | The maximum number of rows to return. |
| `run_view_type` | Which runs to include: active, deleted or all. |
| `output_format` | `"pandas"` (default) or `"list"` for a list of `Run` objects. |
If you leave out both experiment_names and experiment_ids, MLflow searches the currently active experiment. In a notebook, that is the notebook experiment unless you called set_experiment. Passing the experiment explicitly avoids surprises.
The shape of the result
Each run's data becomes columns, and the column names carry a prefix that shows where the value came from.
| Column pattern | Source |
|---|---|
| `run_id`, `experiment_id`, `status`, `start_time`, `end_time` | Run attributes |
| `metrics.<name>` | Logged metrics |
| `params.<name>` | Logged parameters |
| `tags.<name>` | Tags, including system tags such as `tags.mlflow.runName` |
Two details trip people up:
- Parameter values come back as strings, because MLflow stores parameters as strings. Convert them yourself before comparing numerically, for example
runs["params.C"].astype(float). - If a metric was logged many times in one run (for example, once per epoch), the DataFrame holds only the latest value. To see the full history, use
MlflowClient().get_metric_history(run_id, "metric_name").
Columns appear only if at least one matching run has that value. A run that lacks a metric gets NaN in that column.
Writing filter strings
A filter string is a set of comparisons joined with AND. Each comparison names a field with its prefix, an operator, and a value.
# Metric threshold and a specific parameter value
"metrics.test_accuracy > 0.9 AND params.C = '1.0'"
# Tag match
"tags.stage = 'exploration'"
# Run name pattern
"attributes.run_name LIKE 'C=%'"
# Only finished runs
"attributes.status = 'FINISHED'"Rules to remember:
- Metrics are numbers, so write them without quotes:
metrics.loss < 0.3. - Params and tags are strings, so quote the value:
params.C = '1.0'. Writingparams.C = 1.0fails or matches nothing. - Use single quotes around string values.
- Only
ANDis supported. There is noOR. To express an OR, run two searches and combine the DataFrames, or filter further in pandas. - Names with special characters need backticks, for example `
metrics.val acc> 0.8`. - Supported comparators for numbers are
=,!=,>,>=,<,<=. Strings support=,!=,LIKEandILIKE(case-insensitive).
Ordering and picking the best run
order_by takes a list, so you can break ties. Runs with a missing value for the ordering column sort last for descending order in most cases, but do not rely on this. Add a filter that requires the metric to exist, such as metrics.test_accuracy >= 0, when it matters.
A common use is selecting the best run and keeping its ID for the registration step:
import mlflow
best = mlflow.search_runs(
experiment_names=["/Users/<your-email>/iris-tracking"],
filter_string="attributes.status = 'FINISHED' AND metrics.test_accuracy >= 0",
order_by=["metrics.test_accuracy DESC", "attributes.start_time DESC"],
max_results=1,
)
if best.empty:
raise RuntimeError("No finished runs with test_accuracy found")
best_run_id = best.loc[0, "run_id"]
best_accuracy = best.loc[0, "metrics.test_accuracy"]
print(best_run_id, best_accuracy)The second order_by entry makes the choice deterministic when two runs have the same accuracy: the newer one wins. The best.empty check prevents an IndexError if the filter matches nothing.
Searching across experiments
experiment_names and experiment_ids accept lists, so one call can cover several experiments. The DataFrame includes an experiment_id column so you can tell the rows apart.
import mlflow
runs = mlflow.search_runs(
experiment_names=[
"/Users/<your-email>/iris-tracking",
"/Users/<your-email>/iris-tuning",
],
filter_string="tags.stage = 'exploration'",
)
print(runs.groupby("experiment_id")["run_id"].count())You can only search experiments you have permission to read. If you lack read access to one of the listed experiments, the call can fail rather than skip it, so keep the list to experiments you own or share.
Nested runs in search results
Searches return child runs and parent runs together. Child runs carry the tag mlflow.parentRunId. To list only the trials of one sweep, filter on that tag:
import mlflow
parent_id = "<parent-run-id>"
trials = mlflow.search_runs(
experiment_names=["/Users/<your-email>/iris-tracking"],
filter_string=f"tags.mlflow.parentRunId = '{parent_id}'",
order_by=["metrics.test_accuracy DESC"],
)
print(trials[["tags.mlflow.runName", "params.C", "metrics.test_accuracy"]])To exclude children and see only top-level runs, fetch all runs and keep rows where tags.mlflow.parentRunId is NaN:
top_level = runs[runs["tags.mlflow.parentRunId"].isna()]If no run in the results has a parent, that column does not exist, so check "tags.mlflow.parentRunId" in runs.columns first.
Deleted runs and pagination
By default, search_runs returns only active runs. To include runs that were deleted but not yet permanently removed, pass run_view_type:
from mlflow.entities import ViewType
all_runs = mlflow.search_runs(
experiment_names=["/Users/<your-email>/iris-tracking"],
run_view_type=ViewType.ALL,
)The values are ViewType.ACTIVE_ONLY, ViewType.DELETED_ONLY and ViewType.ALL.
search_runs fetches results page by page behind the scenes. In recent MLflow versions its max_results default is large (100,000), so a broad search on a busy experiment can be slow and use a lot of memory. Set max_results deliberately and filter on the server side instead of loading everything and filtering in pandas.
Using the client for finer control
MlflowClient.search_runs is the lower-level version. It takes experiment IDs only, returns a list of Run objects, and gives you pagination through a token.
import mlflow
from mlflow import MlflowClient
client = MlflowClient()
experiment = mlflow.get_experiment_by_name("/Users/<your-email>/iris-tracking")
page = client.search_runs(
experiment_ids=[experiment.experiment_id],
filter_string="metrics.test_accuracy > 0.9",
order_by=["metrics.test_accuracy DESC"],
max_results=10,
)
for run in page:
print(run.info.run_id, run.data.metrics["test_accuracy"], run.data.params)
next_token = page.token # None when there are no more pagesUse the client when you want typed objects (run.info, run.data), when you need to page through results, or when you need metric history. Use mlflow.search_runs when you want a DataFrame for analysis.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Empty DataFrame | Wrong experiment name, or filter too strict | Print `mlflow.get_experiment_by_name(...)`; test the search without a filter first. |
| `KeyError: 'metrics.test_accuracy'` | No matching run logged that metric | Check `runs.columns` before indexing. |
| Parameter filter matches nothing | Value not quoted | Use `params.C = '1.0'`. |
| Error parsing the filter | Used `OR` or double quotes | Use `AND` only; use single quotes. |
| Wrong experiment searched | Relied on the active experiment | Pass `experiment_names` explicitly. |
| Comparing params gives odd order | Params are strings | Cast with `astype(float)` first. |
Summary of the working model
A search is a server-side query over the run records in an experiment. The filter and ordering run on the tracking server, and the result is shaped into a DataFrame or a list of Run objects. Keep filters specific, name the experiments explicitly, quote string values, and cast parameters before doing numeric work.
Exercise
You want the three best finished runs in the experiment "/Users/me/iris-tracking" where the parameter C equals 1.0, ranked by test_accuracy. Write the call, and say why params.C = 1.0 would be a mistake in the filter.
Show answer
mlflow.searchruns(experimentnames=["/Users/me/iris-tracking"], filterstring="attributes.status = 'FINISHED' AND params.C = '1.0'", orderby=["metrics.testaccuracy DESC"], maxresults=3). Parameters are stored as strings, so their values must be quoted in the filter. An unquoted 1.0 is treated as a number and does not match the string parameter.
Exercise
A DataFrame from searchruns shows the column params.maxiter as text. You want the runs with max_iter above 100 in pandas. What do you do first?
Show answer
Convert the column to a number, for example runs["params.maxiter"].astype(int), and then filter with runs[runs["params.maxiter"].astype(int) > 100]. Comparing the raw strings would sort them alphabetically, so "20" would be greater than "100".