{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Introduction\n", "\n", "Sometimes it doesn't matter whether your query is efficient or not. For example, you might write a query you expect to run only once, and it might be working on a small dataset. In this case, anything that gives you the answer you need will do.\n", "\n", "But what about queries that will be run many times, like a query that feeds data to a website? Those need to be efficient so you don't leave users waiting for your website to load.\n", "\n", "Or what about queries on huge datasets? These can be slow and cost a business a lot of money if they are written poorly.\n", "\n", "Most database systems have a **query optimizer** that attempts to interpret/execute your query in the most effective way possible. But several strategies can still yield huge savings in many cases.\n", "\n", "# Some useful functions\n", "\n", "We will use two functions to compare the efficiency of different queries:\n", "- `show_amount_of_data_scanned()` shows the amount of data the query uses.\n", "- `show_time_to_run()` prints how long it takes for the query to execute." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_kg_hide-input": true }, "outputs": [], "source": [ "#$HIDE_INPUT$\n", "from google.cloud import bigquery\n", "from time import time\n", "\n", "client = bigquery.Client()\n", "\n", "def show_amount_of_data_scanned(query):\n", " # dry_run lets us see how much data the query uses without running it\n", " dry_run_config = bigquery.QueryJobConfig(dry_run=True)\n", " query_job = client.query(query, job_config=dry_run_config)\n", " print('Data processed: {} GB'.format(round(query_job.total_bytes_processed / 10**9, 3)))\n", " \n", "def show_time_to_run(query):\n", " time_config = bigquery.QueryJobConfig(use_query_cache=False)\n", " start = time()\n", " query_result = client.query(query, job_config=time_config).result()\n", " end = time()\n", " print('Time to run: {} seconds'.format(round(end-start, 3)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Strategies\n", "\n", "### 1) Only select the columns you want. \n", "\n", "It is tempting to start queries with **SELECT * FROM ...**. It's convenient because you don't need to think about which columns you need. But it can be very inefficient.\n", "\n", "This is especially important if there are text fields that you don't need, because text fields tend to be larger than other fields." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "star_query = \"SELECT * FROM `bigquery-public-data.github_repos.contents`\"\n", "show_amount_of_data_scanned(star_query)\n", "\n", "basic_query = \"SELECT size, binary FROM `bigquery-public-data.github_repos.contents`\"\n", "show_amount_of_data_scanned(basic_query)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this case, we see a 1000X reduction in data being scanned to complete the query, because the raw data contained a text field that was 1000X larger than the fields we might need." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2) Read less data.\n", "\n", "Both queries below calculate the average duration (in seconds) of one-way bike trips in the city of San Francisco." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "more_data_query = \"\"\"\n", " SELECT MIN(start_station_name) AS start_station_name,\n", " MIN(end_station_name) AS end_station_name,\n", " AVG(duration_sec) AS avg_duration_sec\n", " FROM `bigquery-public-data.san_francisco.bikeshare_trips`\n", " WHERE start_station_id != end_station_id \n", " GROUP BY start_station_id, end_station_id\n", " LIMIT 10\n", " \"\"\"\n", "show_amount_of_data_scanned(more_data_query)\n", "\n", "less_data_query = \"\"\"\n", " SELECT start_station_name,\n", " end_station_name,\n", " AVG(duration_sec) AS avg_duration_sec \n", " FROM `bigquery-public-data.san_francisco.bikeshare_trips`\n", " WHERE start_station_name != end_station_name\n", " GROUP BY start_station_name, end_station_name\n", " LIMIT 10\n", " \"\"\"\n", "show_amount_of_data_scanned(less_data_query)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Since there is a 1:1 relationship between the station ID and the station name, we don't need to use the `start_station_id` and `end_station_id` columns in the query. By using only the columns with the station IDs, we scan less data.\n", "\n", "### 3) Avoid N:N JOINs.\n", "\n", "Most of the JOINs that you have executed in this course have been **1:1 JOINs**. In this case, each row in each table has at most one match in the other table.\n", "\n", "![JOIN](https://storage.googleapis.com/kaggle-media/learn/images/fp7oMLq.png)\n", "\n", "Another type of JOIN is an **N:1 JOIN**. Here, each row in one table matches potentially many rows in the other table. \n", "\n", "![JOIN](https://storage.googleapis.com/kaggle-media/learn/images/7PxE0Mr.png)\n", "\n", "Finally, an **N:N JOIN** is one where a group of rows in one table can match a group of rows in the other table. Note that in general, all other things equal, this type of JOIN produces a table with many more rows than either of the two (original) tables that are being JOINed.\n", "\n", "![JOIN](https://storage.googleapis.com/kaggle-media/learn/images/UsNZZoz.png)\n", "\n", "Now we'll work with an example from a real dataset. Both examples below count the number of distinct committers and the number of files in several GitHub repositories." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "big_join_query = \"\"\"\n", " SELECT repo,\n", " COUNT(DISTINCT c.committer.name) as num_committers,\n", " COUNT(DISTINCT f.id) AS num_files\n", " FROM `bigquery-public-data.github_repos.commits` AS c,\n", " UNNEST(c.repo_name) AS repo\n", " INNER JOIN `bigquery-public-data.github_repos.files` AS f\n", " ON f.repo_name = repo\n", " WHERE f.repo_name IN ( 'tensorflow/tensorflow', 'facebook/react', 'twbs/bootstrap', 'apple/swift', 'Microsoft/vscode', 'torvalds/linux')\n", " GROUP BY repo\n", " ORDER BY repo\n", " \"\"\"\n", "show_time_to_run(big_join_query)\n", "\n", "small_join_query = \"\"\"\n", " WITH commits AS\n", " (\n", " SELECT COUNT(DISTINCT committer.name) AS num_committers, repo\n", " FROM `bigquery-public-data.github_repos.commits`,\n", " UNNEST(repo_name) as repo\n", " WHERE repo IN ( 'tensorflow/tensorflow', 'facebook/react', 'twbs/bootstrap', 'apple/swift', 'Microsoft/vscode', 'torvalds/linux')\n", " GROUP BY repo\n", " ),\n", " files AS \n", " (\n", " SELECT COUNT(DISTINCT id) AS num_files, repo_name as repo\n", " FROM `bigquery-public-data.github_repos.files`\n", " WHERE repo_name IN ( 'tensorflow/tensorflow', 'facebook/react', 'twbs/bootstrap', 'apple/swift', 'Microsoft/vscode', 'torvalds/linux')\n", " GROUP BY repo\n", " )\n", " SELECT commits.repo, commits.num_committers, files.num_files\n", " FROM commits \n", " INNER JOIN files\n", " ON commits.repo = files.repo\n", " ORDER BY repo\n", " \"\"\"\n", "\n", "show_time_to_run(small_join_query)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The first query has a large N:N JOIN. By rewriting the query to decrease the size of the JOIN, we see it runs much faster." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Learn more\n", "\n", "These strategies and many more are discussed in [this thorough guide](https://www.oreilly.com/library/view/google-bigquery-the/9781492044451/) to Google BigQuery. If you'd like to learn more about how to write more efficient queries (or deepen your knowledge of all things BigQuery), you're encouraged to check it out!\n", "\n", "# Your turn\n", "Leverage what you've learned to **[improve the design](#$NEXT_NOTEBOOK_URL$)** of several queries." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.5" } }, "nbformat": 4, "nbformat_minor": 1 }