What you will be able to do
- Write a filter_string that narrows runs by metric, parameter or tag using the metrics., params. and tags. prefixes
- Choose ASC or DESC in order_by so the best run comes first, and use max_results=1 to return only that run
- Tell apart MlflowClient().search_runs, which returns a list of Run objects, and mlflow.search_runs, which returns a pandas DataFrame
- Turn the best run's ID into a runs:/ model URI, or rank MLflow 3 LoggedModels directly with search_logged_models
Key concept
Filter, then rank, then take one — To find the best run, ask the tracking server for it directly. filter_string keeps only the runs you care about, order_by sorts them on the metric that defines "best", and max_results=1 returns just the top run.
1.Searching an experiment instead of reading every run
A tuning job can leave dozens or hundreds of runs behind, and only one of them gets registered. Clicking through the experiment page works once. It does not work inside a scheduled job that has to pick the winner by itself every night. MlflowClient().search_runs lets your code ask the tracking server which run is best, and the server does the filtering and sorting itself.
A search always runs inside a scope: one or more experiment IDs. An experiment is the container your training code logged its runs into (see MLflow runs and experiments). If you point the search at the wrong experiment, you get a confident answer to the wrong question. A common case is a notebook experiment searched when the tuning job actually logged to a shared workspace experiment. So the first step is to resolve the experiment that holds your candidates and pass its ID as a list: experiment_ids=[exp_id].
expId = mlflow.get_experiment_by_name("/Shared/diabetes_experiment/").experiment_idSome approaches look like they work but are the wrong tools. One is calling get_run(run_id) for every run and comparing values in a Python loop. That makes one round trip per run and puts the ranking logic in your code, where it is easy to get wrong. Another is listing experiments and looking for a metric on the experiment object. That cannot work, because metrics belong to runs, not to experiments. A single search_runs call replaces both.
Checkpoint 1 of 8· Fill the gap
Your nightly job has to search the runs in the shared workspace experiment "/Shared/diabetes_experiment/". Search calls take the experiment's ID, not its name. Which attribute completes this line so that expId holds the value you pass as experiment_ids=[expId]?
expId = mlflow.get_experiment_by_name("/Shared/diabetes_experiment/"). ? get_experiment_by_name looks up the experiment by its workspace path. Its experiment_id is the scope that a search over that experiment's runs needs. A run_id belongs to a single run inside the experiment, and the name or artifact location cannot be used as a search scope.
Source: docs.databricks.com2.Narrowing candidates with filter_string
filter_string is a small query language. Each clause names a field by its namespace prefix, then an operator, then a value. The prefix tells MLflow where to look, and the same key under the wrong prefix matches nothing:
metrics.rmse < 0.8compares a logged metric as a number.params.max_depth = '5'compares a parameter. Parameters are stored as strings, so the value goes in quotes.tags.model_type = 'xgboost'compares a tag, also as a quoted string.attributes.status = 'FINISHED'filters on run attributes such as status.
Clauses combine with AND. Take a team that logs xgboost, random_forest and logistic_regression runs into one experiment, with each run tagged model_type. To compare only the xgboost runs, they filter with tags.model_type = 'xgboost'. The family label is a tag, not a metric, so metrics.model_type = 'xgboost' returns nothing useful. Sorting by the tag with order_by does not exclude the other families either. It only changes where they appear in the list, and the top result can still be a random forest.
The experiment page's search box accepts the same syntax, for example metrics.r2 > 0.3. You can try a filter in the UI before you put it in code. By default, a metric clause tests the run's last logged value of that metric, not its best value during training.
Checkpoint 2 of 8· Check yourself
A team logs xgboost, random_forest and logistic_regression runs into one experiment, and tags each run with model_type. The nightly job must pick the lowest-RMSE run, and only xgboost runs may take part. What should be added to the search_runs call?
The model family is stored as a tag, so the filter needs the tags. prefix. If the prefix is wrong, the filter matches nothing. Adding an order_by key only changes the order of the runs, so another family can still come out on top.
“To search for runs by tag, enter tags in the format: tags.<key>="<value>". String values must be enclosed in quotes as shown.”Source: docs.databricks.com
Sources3
3.Ranking with order_by and keeping one with max_results
order_by takes a list of strings, each a field name followed by ASC or DESC. MLflow only sorts in the direction you give it. It does not know whether a larger number means a better model. Error and loss metrics (RMSE, MAE, log loss) are best when low, so use ASC. Scores (accuracy, F1, AUC, R-squared) are best when high, so use DESC (see Metric direction: higher-is-better vs lower-is-better). The wrong direction does not raise an error. It quietly returns your worst model.
max_results=1 makes the server return only the top row after sorting. You get exactly the winner and transfer nothing else. Add a second sort key to make ties deterministic. 'start_time DESC' as the second key means that when two runs share the best score, the more recent run wins.
| Goal | order_by entry | Why |
|---|---|---|
| Lowest error wins | metrics.rmse ASC | Smallest value first |
| Highest score wins | metrics.test_auc DESC | Largest value first |
| Break ties by recency | start_time DESC | Second key, applied only when the first is equal |
Put together, the best xgboost run by accuracy is MlflowClient().search_runs(experiment_ids=[exp_id], filter_string="tags.model_type = 'xgboost'", order_by=["metrics.accuracy DESC"], max_results=1). Each argument does one job: the experiment ID sets the scope, the filter sets eligibility, the order sets the ranking, and max_results sets how many come back.
Checkpoint 3 of 8· Check yourself
A classifier tuning sweep logs test_auc on every run. The scheduled job calls search_runs with max_results=1. It must return the run with the highest AUC, and if two runs tie on AUC, the more recent one should win. Which order_by does that?
AUC is a score, so higher is better and DESC puts the best run first. start_time DESC goes second because it should only decide ties on the first key. Put it first and the newest run wins whatever its AUC. Make it ASC and the older run wins a tie.
“order_by=['metrics.test_auc DESC', 'start_time DESC'],”Source: docs.databricks.com
Checkpoint 4 of 8· Exam question
A data scientist logged 40 runs of a regression model to an MLflow experiment on Databricks, recording rmse as a metric on every run. They want the run with the lowest rmse value returned directly as a single result, without pulling all 40 runs into a DataFrame and sorting them in pandas. Which approach identifies that run using the MLflow Client API?
Correct answer: A — Call MlflowClient().search_runs(experiment_ids=[exp_id], order_by=["metrics.rmse ASC"], max_results=1) and read the first Run object returned in the list.
- A. Sorting with
order_by=["metrics.rmse ASC"]andmax_results=1asks the tracking server to rank runs from lowest to highest rmse and return only the top match, which is exactly the lowest-error run without any client-side sorting. - B.
DESCsorts from highest to lowest rmse, somax_results=1would return the run with the worst error instead of the best one. - C.
list_experiments()returns experiment-level metadata such as names and artifact locations; metrics likermseare logged per run, not stored as tags on the experiment itself. - D. This requires already knowing every run ID in advance and issuing one call per run, which is precisely the manual full-scan approach that
order_byandmax_resultsare designed to replace.
Checkpoint 5 of 8· Exam question
A team logged runs under three model families using a model_type tag with values xgboost, random_forest, and logistic_regression, all in the same MLflow experiment. A data scientist needs the single best xgboost run, ranked by accuracy, while ignoring the other two families entirely. Which call to search_runs returns exactly that run?
Correct answer: A — search_runs(experiment_ids=[exp_id], filter_string="tags.model_type = 'xgboost'", order_by=["metrics.accuracy DESC"], max_results=1)
- A. The filter string scopes the search to runs tagged
xgboostbefore any sorting happens, andDESCon accuracy then puts the highest-accuracy run in that scoped set first. - B.
model_typewas logged as a tag, not a metric, so referencing it asmetrics.model_typein the filter string will not match any run and the search returns an empty result. - C. Sorting by the tag first ranks runs alphabetically by model family before accuracy is even considered, and it never actually restricts the result set to only xgboost runs.
- D.
ASCordering ranks the lowest-accuracy xgboost run first, which is the opposite of the best-performing run the scenario asks for.
Sources4
4.List of Run objects or pandas DataFrame
MLflow has two search functions with nearly the same name, and they return different types. MlflowClient().search_runs returns a list of Run objects. Read the winner with runs[0], its ID with runs[0].info.run_id, and its metrics from the runs[0].data.metrics dictionary. The module-level mlflow.search_runs returns a pandas DataFrame, with one row per run and flattened columns such as run_id, metrics.f1 and params.max_depth.
Pick the one that fits the code around it. In production code that wants one object to pass on, use the client with max_results=1. For exploring in a notebook, where you want .sort_values(), .head() or a quick display, use mlflow.search_runs. It accepts the same filter_string and order_by arguments. Calling .sort_values() on the client's return value fails because a list is not a DataFrame. mlflow.get_experiment returns only experiment metadata, not a table of runs.
# Sort runs by their test auc. In case of ties, use the most recent run.
best_run = mlflow.search_runs(
order_by=['metrics.test_auc DESC', 'start_time DESC'],
max_results=10,
).iloc[0]
print('Best Run')
print('AUC: {}'.format(best_run["metrics.test_auc"]))| Call | Returns | Read the best run's ID |
|---|---|---|
| MlflowClient().search_runs(...) | List of mlflow.entities.Run | runs[0].info.run_id |
| mlflow.search_runs(...) | pandas DataFrame | best_run.run_id after .iloc[0] |
Checkpoint 6 of 8· Fill the gap
This notebook cell ranks tuning runs on the server and then reads the top row with .iloc[0]. Which caller belongs in the blank so that .iloc[0] works on what search_runs returns?
# Sort runs by their test auc. In case of ties, use the most recent run.
best_run = ? .search_runs(
order_by=['metrics.test_auc DESC', 'start_time DESC'],
max_results=10,
).iloc[0]
print('Best Run')
print('AUC: {}'.format(best_run["metrics.test_auc"]))The module-level mlflow.search_runs returns a pandas DataFrame, so .iloc[0] and the flattened column metrics.test_auc both work. MlflowClient().search_runs returns a list of Run objects, which has no .iloc and no metrics.* columns. mlflow.get_experiment returns only experiment metadata.
Source: docs.databricks.comCheckpoint 7 of 8· Exam question
A notebook already imports pandas, and the data scientist wants to quickly sort completed runs by validation F1 score inside a DataFrame using .sort_values() and .head(), rather than working with a list of Run objects. Which approach fits that exploratory workflow?
Correct answer: A — Call the module-level mlflow.search_runs(experiment_ids=[exp_id]) function, which returns a pandas DataFrame with rows per run and columns like metrics.f1.
- A. The module-level
mlflow.search_runsfunction is documented to return a pandas DataFrame with one row per run, which is exactly the shape needed for.sort_values()and.head()style exploration. - B. The
MlflowClientclass'ssearch_runsmethod returns a list ofRunobjects rather than a DataFrame, so pandas methods like.sort_values()cannot be called on it without extra conversion. - C.
get_experimentreturns a singleExperimentmetadata object describing the experiment itself, such as its name and artifact location, not a table of per-run metrics. - D.
list_run_infosreturns a list ofRunInfoobjects containing only run metadata like status and timestamps, not a DataFrame and not logged metric values.
Sources5
5.From the best run to its model
A run ID is usually not the end goal. The goal is the model that run produced. Prefix the ID to build a run-relative URI, runs:/<run_id>/model, which load and register calls both accept (see Logged models and model URIs (runs:/, models:/)). The model part is the artifact path the model was logged under. If training logged it under another name, the URI has to use that name.
MLflow 3 adds a second route. Models are first-class LoggedModel entities with their own metrics, so you can rank the models themselves with mlflow.search_logged_models instead of ranking runs. This matters when a single run produces several models. In a deep learning job that saves a checkpoint every few epochs, every checkpoint belongs to the same run, and ranking runs cannot tell them apart. Note the different order_by shape: a list of dictionaries with a boolean ascending, not strings ending in ASC/DESC.
ranked_checkpoints = mlflow.search_logged_models(
output_format="list",
order_by=[{"field_name": "metrics.accuracy", "ascending": False}]
)
best_checkpoint: mlflow.entities.LoggedModel = ranked_checkpoints[0]
print(best_checkpoint.metrics[0])Checkpoint 8 of 8· Fill the gap
A PyTorch job logs a checkpoint every 10 epochs inside one MLflow run, and each checkpoint is an MLflow 3 LoggedModel. Ranking runs can't tell the checkpoints apart, so you rank the models. Which value in the blank puts the most accurate checkpoint at ranked_checkpoints[0]?
ranked_checkpoints = mlflow.search_logged_models(
output_format="list",
order_by=[{"field_name": "metrics.accuracy", "ascending": ? }]
)
best_checkpoint: mlflow.entities.LoggedModel = ranked_checkpoints[0]
print(best_checkpoint.metrics[0])search_logged_models takes order_by as a list of dictionaries with a boolean ascending key, not strings ending in ASC or DESC. Higher accuracy is better, so ascending must be False to put the best checkpoint first. True would put the worst checkpoint at index 0.
Source: docs.databricks.comSources
(7)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://docs.databricks.com/aws/en/mlflow/trackingOfficial docs
“An experiment is a collection of related runs.”
↩︎ Searching an experiment instead of reading every run“In an experiment, you can compare and filter runs to understand how your model performs”
↩︎ Key concept - 2.
“any notebook can log a run to these experiments by using the experiment ID or the experiment name”
↩︎ Searching an experiment instead of reading every run - 3.https://docs.databricks.com/aws/en/mlflow/runsOfficial docs
“String values must be enclosed in quotes as shown.”
↩︎ Narrowing candidates with filter_string“By default, metric values are filtered based on the last logged value.”
↩︎ Narrowing candidates with filter_string“To search for runs by tag, enter tags in the format: tags.<key>=”
↩︎ Exam trap 2“To search for runs by tag, enter tags in the format: tags.<key>="<value>". String values must be enclosed in quotes as shown.”
↩︎ Checkpoint - 4.
“using the MLflow search runs API to find the tuning run with the highest test auc”
↩︎ Ranking with order_by and keeping one with max_results“order_by=['metrics.test_auc DESC', 'start_time DESC']”
↩︎ Exam trap 1“Sort runs by their test auc. In case of ties, use the most recent run.”
↩︎ Prediction“order_by=['metrics.test_auc DESC', 'start_time DESC'],”
↩︎ Checkpoint - 5.
“mlflow.search_runs() - Search and filter runs by criteria”
↩︎ List of Run objects or pandas DataFrame“mlflow.entities.Run - Run metadata, metrics, and parameters”
↩︎ Exam trap 3 - 6.https://docs.databricks.com/aws/en/mlflow/modelsOfficial docs
“a run-relative path (such as runs:/{run_id}/{model-path})”
↩︎ From the best run to its model - 7.
“The following code shows how to rank the checkpoint models by accuracy.”
↩︎ From the best run to its model