Add parameters to databricks notebook using widgets

Add parameters to databricks notebook using widgets

Add parameters to notebooks using widgets is a databricks programming solution on how to create parameters in databricks notebook using input widgets. 

Widget in databricks is an API call to create and remove Input widgets.

The input widgets in databricks are helpful to add parameters to notebooks. 
There are four types of input widgets currently supported by databricks.

1.textbox 
2.dropdown 
3.combobox 
4.multiselect


Create a dropdown widget in a Notebook

Below is the syntax for how to add the parameter using a dropdown widget

syntax:
dbutils.widgets.dropdown
("name of the parameter","initial value","value range")

Steps to add a parameter to the Notebook:

Step 1:
Enter Portal.Azure.com in a web browser.

Step 2:
Click on Azure Resources from the options

Step 3:
From the Azure resources, filter out the databricks workspaces if it's already created.

Step 4:
Once the workspace listed, select the same.

Step 5:
From the workspace, select the cluster i.e. attached to your Notebook.

Step 6:  
If the cluster is in OFF mode, start the cluster.

Step 7: 
Select your Notebook from the cluster menu.

Step 8: 
Once the notebook opened, try to create widget in any of the command cells.
For example, in any notebook cell add one input widget i.e. 'day' parameter dropdown to the notebook which is ranges from 1-31.

dbutils.widgets.dropdown("day","1",[str(x) for x in range(1, 32)]) 

In this example, the range is mentioned between 1-32, which means the dropdown values are shown as 1-31. As we already initiated the dropdown with '1', so we have to provide the range as 1-32.
Otherwise, we can see the range in the dropdown is 1-30.

Step 9: Now, run the cell

That's it, widget added successfully and you can see the widget top the notebook as a ribbon...

Conclusion

Once the widget added to the toolbar, add the below code to the cell to access the parameter value selected in the dropdown widget.

currentDay = dbutils.widgets.get("day")
Note: here 'currentDay' is a local variable declared using Python syntax.

if its 'Scala' use the below line of code

val currentDay = dbutils.widgets.get("day")

Success!!! Now you are able to access the value.

Happy Coding!!!👍


No comments:

Post a Comment