diff --git a/examples/quickstart_snowflake/README.md b/examples/quickstart_snowflake/README.md new file mode 100644 index 0000000000000..0f6165091eb42 --- /dev/null +++ b/examples/quickstart_snowflake/README.md @@ -0,0 +1,270 @@ +# Dagster + Snowflake starter kit + +This example builds a daily ETL pipeline that materializes tables in Snowflake. At a high level, this project shows how to ingest data from external sources to Snowflake, explore and transform the data, and materialize outputs that help visualize the data. + +*New to Dagster? Learn what Dagster is [in Concepts](https://docs.dagster.io/concepts) or [in the hands-on Tutorials](https://docs.dagster.io/tutorial).* + +This guide covers: +- [Dagster + Snowflake starter kit](#dagster--snowflake-starter-kit) + - [Introduction](#introduction) + - [Prerequisites](#prerequisites) + - [Using environment variables to handle secrets](#using-environment-variables-to-handle-secrets) + - [Getting started](#getting-started) + - [Option 1: Deploying it on Dagster Cloud](#option-1-deploying-it-on-dagster-cloud) + - [Option 2: Running it locally](#option-2-running-it-locally) + - [Step 1: Materializing assets](#step-1-materializing-assets) + - [Step 2: Viewing and monitoring assets](#step-2-viewing-and-monitoring-assets) + - [Step 3: Scheduling a daily job](#step-3-scheduling-a-daily-job) + - [(Optional) Running daemon locally](#optional-running-daemon-locally) + - [Learning more](#learning-more) + - [Changing the code locally](#changing-the-code-locally) + - [Adding new Python dependencies](#adding-new-python-dependencies) + - [Testing](#testing) + + +## Introduction + +This starter kit includes: +- Basics of creating, connecting, and testing [assets](https://docs.dagster.io/concepts/assets/software-defined-assets) in Dagster. +- Convenient ways to organize and monitor assets, e.g. [grouping assets](https://docs.dagster.io/concepts/assets/software-defined-assets#grouping-assets), [recording asset metadata](https://docs.dagster.io/concepts/assets/software-defined-assets#recording-materialization-metadata), etc. +- [Snowflake I/O manager](https://docs.dagster.io/_apidocs/libraries/dagster-snowflake) to load the datasets in Snowflake and read from it, which [uses environment variables](https://docs.dagster.io/guides/dagster/using-environment-variables-and-secrets) to handle credentials. +- A [schedule](https://docs.dagster.io/concepts/partitions-schedules-sensors/schedules) defined to run a job that generates assets daily. +- [Scaffolded project layout](https://docs.dagster.io/getting-started/create-new-project) that helps you to quickly get started with everything set up. + + +In this project, we're building an analytical pipeline that explores popular topics on HackerNews. + +

+ +

+ +This project: + +- Fetches data from [HackerNews](https://github.com/HackerNews/API) APIs and stores the data in [Snowflake](https://www.snowflake.com). +- Transforms the collected data using [Pandas](http://pandas.pydata.org/pandas-docs/stable/). +- Creates a [word cloud](https://github.com/amueller/word_cloud) based on trending HackerNews stories to visualize popular topics on HackerNews. + +## Prerequisites + +To complete the steps in this guide, you'll need: + +- A [Snowflake](https://www.snowflake.com) account. +- Set up secrets to connect to Snowflake. + +### Using environment variables to handle secrets + +To connect to Snowflake, you'll need to set up your credentials in Dagster. + +Dagster allows using environment variables to handle sensitive information. You can define various configuration options and access environment variables through them. This also allows you to parameterize your pipeline without modifying code. + +In this example, we use [snowflake_io_manager](https://docs.dagster.io/_apidocs/libraries/dagster-snowflake#dagster_snowflake.build_snowflake_io_manager) to write outputs to Snowflake and read inputs from it. The configurations of the Snowflake connection are defined [in `quickstart_snowflake/repository.py`](./quickstart_snowflake/repository.py), which requires the following environment variables: +- `SNOWFLAKE_ACCOUNT` +- `SNOWFLAKE_USER` +- `SNOWFLAKE_PASSWORD` +- `SNOWFLAKE_WAREHOUSE` +- `SNOWFLAKE_DATABASE` +- `SNOWFLAKE_SCHEMA` + +You can declare environment variables in various ways: +- **Local development**: [Using `.env` files to load env vars into local environments](https://docs.dagster.io/guides/dagster/using-environment-variables-and-secrets#declaring-environment-variables) +- **Dagster Cloud**: [Using the Dagster Cloud UI](https://docs.dagster.io/master/dagster-cloud/developing-testing/environment-variables-and-secrets#using-the-dagster-cloud-ui) to manage environment variables +- **Dagster Open Source**: How environment variables are set for Dagster projects deployed on your infrastructure depends on where Dagster is deployed. Read about how to declare environment variables [here](https://docs.dagster.io/master/guides/dagster/using-environment-variables-and-secrets#declaring-environment-variables). + +Check out [Using environment variables and secrets guide](https://docs.dagster.io/guides/dagster/using-environment-variables-and-secrets) for more info and examples. + +## Getting started + +### Option 1: Deploying it on Dagster Cloud + +The easiest way to spin up your Dagster project is to use [Dagster Cloud Serverless](https://docs.dagster.io/dagster-cloud/deployment/serverless). It provides out-of-the-box CI/CD and native branching that make development and deployment easy. + +Check out [Dagster Cloud](https://dagster.io/cloud) to get started. + +### Option 2: Running it locally + +First, install your Dagster repository as a Python package. By using the `--editable` flag, pip will install your repository in ["editable mode"](https://pip.pypa.io/en/latest/topics/local-project-installs/#editable-installs) so that as you develop, local code changes will automatically apply. Check out [Dagster Installation](https://docs.dagster.io/getting-started/install) for more information. + +```bash +pip install -e ".[dev]" +``` + +Then, start the Dagit web server: + +```bash +dagit +``` + +Open http://localhost:3000 with your browser to see the project. + +## Step 1: Materializing assets + +With the starter project loaded in your browser, click the icon in the top-left corner of the page to expand the navigation. You'll see both jobs and assets listed in the left nav. + +

+ +

+ +Click on the `hackernews` asset group to view the HackerNews assets and their relationship. + +An asset is a software object that models a data asset, which can be a file in your filesystem, a table in a database, or a data report. The assets in the `hackernews` asset group ingest the current trending 500 HackerNews stories and plots a word cloud out of the collected stories to visualize the popular topics on HackerNews. You'll see three assets with different tags: + +- `hackernews_topstory_ids` fetches a list of top story ids from a HackerNews endpoint. +- `hackernews_topstories` takes the list of ids and pulls the story details from HackerNews based on the ids. +- `hackernews_stories_word_cloud` visualizes the trending topics in a word cloud. + +Dagster visualizes upstream and downstream dependencies vertically. Assets below other assets connected by arrows implies a dependency relationship. So we can tell from the UI that the asset `hackernews_topstories` depends on `hackernews_topstory_ids` (i.e. `hackernews_topstories` takes `hackernews_topstory_ids`'s output as an input) and `hackernews_stories_word_cloud` depends on `hackernews_topstories`. + +All three assets are defined [in `quickstart_snowflake/assets/hackernews.py`](./quickstart_snowflake/assets/hackernews.py). Typically, you'll define assets by annotating ordinary Python functions with the [`@asset`](https://docs.dagster.io/concepts/assets/software-defined-assets#a-basic-software-defined-asset) decorator. + +This project also comes with ways to better organize the assets: + +- **Labeling/tagging.** You'll find the assets are tagged with different [labels/badges], such as `HackerNews API` and `Plot`. This is defined in code via the `compute_kind` argument to the `@asset` decorator. It can be any string value that represents the kind of computation that produces the asset and will be displayed in the UI as a badge on the asset. This can help us quickly understand the data logic from a bird's eye view. +- **Grouping assets**. We've also assigned all three assets to the group `hackernews`, which is accomplished by providing the `group_name` argument to the `@asset` decorator. Grouping assets can help keep assets organized as your project grows. Learn about asset grouping [here](https://docs.dagster.io/concepts/assets/software-defined-assets#assigning-assets-to-groups). +- **Adding descriptions.** In the asset graph, the UI also shows the description of each asset. You can specify the description of an asset in the `description` argument to `@asset`. When the argument is not provided and the decorated function has a docstring, Dagster will use the docstring as the description. In this example, the UI is using the docstrings as the descriptions. + + +Now that we've got a basic understanding of Dagster assets, let's materialize them. + +

+ +

+ +Click **Materialize all** to kick off a Dagster run which will pull info from the external APIs and move the data through assets. + +As you iterate, some assets may become outdated. To refresh them, you can select a subset of assets to run instead of re-running the entire pipeline. This allows us to avoid unnecessary re-runs of expensive computations, only re-materializing the assets that need to be updated. If assets take a long time to run or interact with APIs with restrictive rate limits, selectively re-materializing assets will come in handy. + +

+ +

+ +You'll see an indicator pop up with the launched run ID. Click **View** to monitor the run in real-time. This will open a new tab in your browser: + +

+ +

+ +The process will run for a bit. While it's running, you should see the real-time compute logs printed in the UI. *(It may take 1-2 minutes to fetch all top 500 stories from HackerNews in the `hackernews_topstories` step).* + +## Step 2: Viewing and monitoring assets + +When you materialize an asset, the object returned by your asset function is saved. Dagster makes it easy to save these results to disk, to blob storage, to a database, or to any other system. In this example the assets are saved to the file system. In addition to the asset materialization, your asset functions can also generate metadata that is directly visible in Dagster. To view the materialization details and metadata, click on the "ASSET_MATERIALIZATION" event. In this example, the `hackernews_stories_word_cloud` asset materializes a plot that is saved to disk, but we also add the plot as metadata to make it visible in Dagster. + +

+ +

+ +Click **Show Markdown**. You'll see a word cloud of the top 500 HackerNews story titles generated by the `hackernews_topstories_word_cloud` asset: + +

+ +

+ +The metadata is recorded in the `hackernews_topstories_word_cloud` asset [in `quickstart_snowflake/assets/hackernews.py`](./quickstart_snowflake/assets/hackernews.py). Dagster supports attaching arbitrary [metadata](https://docs.dagster.io/_apidocs/ops#dagster.MetadataValue) to asset materializations. This metadata is also be displayed on the **Activity** tab of the **Asset Details** page in the UI or in the **Asset Lineage** view after selecting an asset. From the compute logs of a run, you can click the **View Asset** to go to the **Asset Details** page. + +

+ +

+ +This metadata would be useful for monitoring and maintaining the asset as you iterate. Similarly, we've also recorded some metadata in the `hackernews_topstories` asset. You can filter the compute logs by typing the asset name (e.g. `hackernews_topstories`) or the event type (e.g. `type:ASSET_MATERIALIZATION`) in the **Log Filter** input box: + +

+ +

+ +In the results, you'll see that the `hackernews_topstories` asset has two metadata entries: `num_records` and `preview`. Both are defined [in `quickstart_snowflake/assets/hackernews.py`](./quickstart_snowflake/assets/hackernews.py), in which we record the first five rows of the output Pandas DataFrame in the `preview` metadata entry using the Markdown type. This could help debug and keep your assets easily monitored. Click **Show Markdown** to view a preview of the output data frame: + +

+ +

+ +Note: You'll find a `path` metadata attached to every asset. This is because assets are, by default, materialized to pickle files on your local filesystem. In most projects, your assets will be materialized to a production system and you can fully customize the I/O using [I/O managers](https://docs.dagster.io/concepts/io-management/io-managers). + +## Step 3: Scheduling a daily job + +Finally, let's refresh our plots every day so we can monitor popular topics over time. To do so, we can use [schedules](https://docs.dagster.io/concepts/partitions-schedules-sensors/schedules#schedules). + +We've defined a daily schedule and job in [`quickstart_snowflake/repository.py`](./quickstart_snowflake/repository.py) for all assets that are defined in the [`quickstart_snowflake/assets/`](./quickstart_snowflake/assets) module. + +Now, let's turn on the daily schedule within Dagster. + +1. In the left nav, it indicates the `all_assets_job` has a schedule associated with it but it's currently off. Clicking "all_assets_job" in the left nav will bring you to the job definition page. +2. Mouse over the schedule indicator on the top of the page to navigate to the individual schedule page for more info about the schedule. + +

+ +

+ +You can now turn on the schedule switch to set up the daily job we defined in [quickstart_snowflake/repository.py](./quickstart_snowflake/repository.py). + +

+ +

+ +### (Optional) Running daemon locally + +If you're running Dagster locally, you will see a warning that your daemon isn’t running. + +

+ +

+ +
πŸ‘ˆ Expand to learn how to set up a local daemon + +If you want to enable Dagster [schedules](https://docs.dagster.io/concepts/partitions-schedules-sensors/schedules) for your jobs, start the [Dagster daemon](https://docs.dagster.io/deployment/dagster-daemon) process in the same folder as your `workspace.yaml` file, but in a different shell or terminal. + +The `$DAGSTER_HOME` environment variable must be set to a directory for the daemon to work. Note: using directories within `/tmp` may cause issues. See [Dagster Instance default local behavior](https://docs.dagster.io/deployment/dagster-instance#default-local-behavior) for more details. + +In this case, go to the project root directory and run: +```bash +dagster-daemon run +``` + +Once your Dagster daemon is running, the schedules that are turned on will start running. + +

+ +

+ +
+ +
+
+ +Congratulations πŸŽ‰ You now have a daily job running in production! + +--- +## Learning more + +### Changing the code locally + +When developing pipelines locally, be sure to click the **Reload definition** button in the Dagster UI after you change the code. This ensures that Dagster picks up the latest changes you made. + +You can reload the code using the **Deployment** page: +
πŸ‘ˆ Expand to view the screenshot + +

+ +

+ +
+ +Or from the left nav or on each job page: +
πŸ‘ˆ Expand to view the screenshot + +

+ +

+ +
+ +### Adding new Python dependencies + +You can specify new Python dependencies in `setup.py`. + +### Testing + +Tests are in the `quickstart_snowflake_tests` directory and you can run tests using `pytest`: + +```bash +pytest quickstart_snowflake_tests +``` diff --git a/examples/quickstart_snowflake/pyproject.toml b/examples/quickstart_snowflake/pyproject.toml new file mode 100644 index 0000000000000..fed528d4a7a14 --- /dev/null +++ b/examples/quickstart_snowflake/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["setuptools"] +build-backend = "setuptools.build_meta" diff --git a/examples/quickstart_snowflake/quickstart_snowflake/__init__.py b/examples/quickstart_snowflake/quickstart_snowflake/__init__.py new file mode 100644 index 0000000000000..fc1fa6b8b22c1 --- /dev/null +++ b/examples/quickstart_snowflake/quickstart_snowflake/__init__.py @@ -0,0 +1 @@ +from .repository import quickstart_snowflake diff --git a/examples/quickstart_snowflake/quickstart_snowflake/assets/__init__.py b/examples/quickstart_snowflake/quickstart_snowflake/assets/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/examples/quickstart_snowflake/quickstart_snowflake/assets/hackernews.py b/examples/quickstart_snowflake/quickstart_snowflake/assets/hackernews.py new file mode 100644 index 0000000000000..6429396f4d4fb --- /dev/null +++ b/examples/quickstart_snowflake/quickstart_snowflake/assets/hackernews.py @@ -0,0 +1,86 @@ +import base64 +from io import BytesIO +from typing import List + +import matplotlib.pyplot as plt +import pandas as pd +import requests +from wordcloud import STOPWORDS, WordCloud + +from dagster import MetadataValue, OpExecutionContext, asset + + +@asset(group_name="hackernews", compute_kind="HackerNews API") +def hackernews_topstory_ids() -> pd.DataFrame: + """ + Get up to 500 top stories from the HackerNews topstories endpoint. + + API Docs: https://github.com/HackerNews/API#new-top-and-best-stories + """ + newstories_url = "https://hacker-news.firebaseio.com/v0/topstories.json" + top_500_newstories = requests.get(newstories_url).json() + return pd.DataFrame(top_500_newstories, columns=["item_ids"]) + + +@asset(group_name="hackernews", compute_kind="HackerNews API") +def hackernews_topstories( + context: OpExecutionContext, hackernews_topstory_ids: pd.DataFrame +) -> pd.DataFrame: + """ + Get items based on story ids from the HackerNews items endpoint. It may take 1-2 minutes to fetch all 500 items. + + API Docs: https://github.com/HackerNews/API#items + """ + + results = [] + for item_id in hackernews_topstory_ids["item_ids"]: + item = requests.get(f"https://hacker-news.firebaseio.com/v0/item/{item_id}.json").json() + results.append(item) + if len(results) % 20 == 0: + context.log.info(f"Got {len(results)} items so far.") + + df = pd.DataFrame(results) + + # Dagster supports attaching arbitrary metadata to asset materializations. This metadata will be + # shown in the run logs and also be displayed on the "Activity" tab of the "Asset Details" page in the UI. + # This metadata would be useful for monitoring and maintaining the asset as you iterate. + # Read more about in asset metadata in https://docs.dagster.io/concepts/assets/software-defined-assets#recording-materialization-metadata + context.add_output_metadata( + { + "num_records": len(df), + "preview": MetadataValue.md(df.head().to_markdown()), + } + ) + return df + + +@asset(group_name="hackernews", compute_kind="Plot") +def hackernews_topstories_word_cloud( + context: OpExecutionContext, hackernews_topstories: pd.DataFrame +) -> None: + """ + Exploratory analysis: Generate a word cloud from the current top 500 HackerNews top stories. + Embed the plot into a Markdown metadata for quick view. + + Read more about how to create word clouds in http://amueller.github.io/word_cloud/. + """ + stopwords = set(STOPWORDS) + stopwords.update(["Ask", "Show", "HN"]) + titles_text = " ".join([str(item) for item in hackernews_topstories["title"]]) + titles_cloud = WordCloud(stopwords=stopwords, background_color="white").generate(titles_text) + + # Generate the word cloud image + plt.figure(figsize=(8, 8), facecolor=None) + plt.imshow(titles_cloud, interpolation="bilinear") + plt.axis("off") + plt.tight_layout(pad=0) + + # Save the image to a buffer and embed the image into Markdown content for quick view + buffer = BytesIO() + plt.savefig(buffer, format="png") + image_data = base64.b64encode(buffer.getvalue()) + md_content = f"![img](data:image/png;base64,{image_data.decode()})" + + # Attach the Markdown content as metadata to the asset + # Read about more metadata types in https://docs.dagster.io/_apidocs/ops#metadata-types + context.add_output_metadata({"plot": MetadataValue.md(md_content)}) diff --git a/examples/quickstart_snowflake/quickstart_snowflake/repository.py b/examples/quickstart_snowflake/quickstart_snowflake/repository.py new file mode 100644 index 0000000000000..5edfcbcdf8168 --- /dev/null +++ b/examples/quickstart_snowflake/quickstart_snowflake/repository.py @@ -0,0 +1,40 @@ +from dagster_snowflake import build_snowflake_io_manager +from dagster_snowflake_pandas import SnowflakePandasTypeHandler + +from dagster import ( + ScheduleDefinition, + define_asset_job, + load_assets_from_package_module, + repository, + with_resources, +) + +from . import assets + +daily_refresh_schedule = ScheduleDefinition( + job=define_asset_job(name="all_assets_job"), cron_schedule="0 0 * * *" +) + + +@repository +def quickstart_snowflake(): + return [ + *with_resources( + load_assets_from_package_module(assets), + resource_defs={ + "io_manager": build_snowflake_io_manager([SnowflakePandasTypeHandler()]).configured( + # Read about using environment variables and secrets in Dagster: + # https://docs.dagster.io/guides/dagster/using-environment-variables-and-secrets + { + "account": {"env": "SNOWFLAKE_ACCOUNT"}, + "user": {"env": "SNOWFLAKE_USER"}, + "password": {"env": "SNOWFLAKE_PASSWORD"}, + "warehouse": {"env": "SNOWFLAKE_WAREHOUSE"}, + "database": {"env": "SNOWFLAKE_DATABASE"}, + "schema": {"env": "SNOWFLAKE_SCHEMA"}, + } + ), + }, + ), + daily_refresh_schedule, + ] diff --git a/examples/quickstart_snowflake/quickstart_snowflake_tests/__init__.py b/examples/quickstart_snowflake/quickstart_snowflake_tests/__init__.py new file mode 100644 index 0000000000000..8b137891791fe --- /dev/null +++ b/examples/quickstart_snowflake/quickstart_snowflake_tests/__init__.py @@ -0,0 +1 @@ + diff --git a/examples/quickstart_snowflake/quickstart_snowflake_tests/test_assets.py b/examples/quickstart_snowflake/quickstart_snowflake_tests/test_assets.py new file mode 100644 index 0000000000000..8b137891791fe --- /dev/null +++ b/examples/quickstart_snowflake/quickstart_snowflake_tests/test_assets.py @@ -0,0 +1 @@ + diff --git a/examples/quickstart_snowflake/setup.cfg b/examples/quickstart_snowflake/setup.cfg new file mode 100644 index 0000000000000..ab64bc16dd441 --- /dev/null +++ b/examples/quickstart_snowflake/setup.cfg @@ -0,0 +1,2 @@ +[metadata] +name = quickstart_snowflake diff --git a/examples/quickstart_snowflake/setup.py b/examples/quickstart_snowflake/setup.py new file mode 100644 index 0000000000000..6496b7d2028e1 --- /dev/null +++ b/examples/quickstart_snowflake/setup.py @@ -0,0 +1,21 @@ +from setuptools import find_packages, setup + +setup( + name="quickstart_snowflake", + packages=find_packages(exclude=["quickstart_snowflake_tests"]), + install_requires=[ + "dagster", + # snowflake-connector-python[pandas] is included by dagster-snowflake-pandas but it does + # not get included during pex dependency resolution, so we directly add this dependency + "snowflake-connector-python[pandas]", + "dagster-snowflake-pandas", + "dagster-cloud", + "boto3", + "pandas", + "matplotlib", + "textblob", + "tweepy", + "wordcloud", + ], + extras_require={"dev": ["dagit", "pytest"]}, +) diff --git a/examples/quickstart_snowflake/workspace.yaml b/examples/quickstart_snowflake/workspace.yaml new file mode 100644 index 0000000000000..d8e5020d704f9 --- /dev/null +++ b/examples/quickstart_snowflake/workspace.yaml @@ -0,0 +1,2 @@ +load_from: + - python_package: quickstart_snowflake diff --git a/python_modules/dagster/dagster/_generate/download.py b/python_modules/dagster/dagster/_generate/download.py index 8e1864189ad7c..67028e3c7d3f0 100644 --- a/python_modules/dagster/dagster/_generate/download.py +++ b/python_modules/dagster/dagster/_generate/download.py @@ -23,6 +23,7 @@ "quickstart_aws", "quickstart_etl", "quickstart_gcp", + "quickstart_snowflake", "tutorial_dbt_dagster", "tutorial_notebook_assets", "deploy_docker",