CertSafari
    Databricks Certified Machine Learning Associate· Lessons

    Domain 1 · Lesson 11/48

    Find the best MLflow run with search_runs

    Identify the best run using the MLflow Client API.

    13 min read
    2.11% of exam
    7 sources
    Published 22 Oct 2026
    Docs as of 17 Oct 2026

    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].

    Resolving a workspace experiment's name to the ID that search calls needpython
    expId = mlflow.get_experiment_by_name("/Shared/diabetes_experiment/").experiment_id

    Some 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/"). ? 

    Sources12

    2.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.8 compares 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?

    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.

    How a ranking query is assembled
    Goalorder_by entryWhy
    Lowest error winsmetrics.rmse ASCSmallest value first
    Highest score winsmetrics.test_auc DESCLargest value first
    Break ties by recencystart_time DESCSecond 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?

    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?

    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?

    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.

    The DataFrame variant: rank on the server, then take the first row with .iloc[0]python
    # 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"]))
    The two search entry points side by side
    CallReturnsRead the best run's ID
    MlflowClient().search_runs(...)List of mlflow.entities.Runruns[0].info.run_id
    mlflow.search_runs(...)pandas DataFramebest_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"]))

    Checkpoint 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?

    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.

    Ranking MLflow 3 checkpoint models by accuracy, best firstpython
    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])

    Sources67

    Sources

    (7)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “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. 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. 3.
      “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. 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. 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. 6.
      “a run-relative path (such as runs:/{run_id}/{model-path})”
      ↩︎ From the best run to its model
    7. 7.
      “The following code shows how to rank the checkpoint models by accuracy.”
      ↩︎ From the best run to its model

    Ready to test yourself?

    Practise Databricks Certified Machine Learning Associate in quiz mode.

    Spotted a mistake, or was something unclear? Tell us.