#!/usr/bin/env python # coding: utf-8 # Continuum Logo, # # Introduction to Blaze # ===================== # # In this tutorial we'll learn how to use Blaze to discover, migrate, and query data living in other databases. Generally this tutorial will have the following format # # 1. `odo` - Move data to database # 2. `blaze` - Query data in database # # # Install # ------- # # This tutorial uses many different libraries that are all available with the [Anaconda Distribution](http://continuum.io/downloads). Once you have Anaconda install, please run these commands from a terminal: # # ``` # $ conda install -y blaze # $ conda install -y bokeh # $ conda install -y odo # ``` # # nbviewer: http://nbviewer.ipython.org/github/ContinuumIO/pydata-apps/blob/master/Section-1_blaze.ipynb # # github: https://github.com/ContinuumIO/pydata-apps # #
# # # Goal: Accessible, Interactive, Analytic Queries # ----------------------------------------------- # # NumPy and Pandas provide accessible, interactive, analytic queries; this is valuable. # In[1]: import pandas as pd df = pd.read_csv('iris.csv') df.head() # In[2]: df.groupby(df.Species).PetalLength.mean() # Average petal length per species #
# # But as data grows and systems become more complex, moving data and querying data become more difficult. Python already has excellent tools for data that fits in memory, but we want to hook up to data that is inconvenient. # # From now on, we're going to assume one of the following: # # 1. You have an inconvenient amount of data # 2. That data should live someplace other than your computer # #
# Databases and Python # -------------------- # # When in-memory arrays/dataframes cease to be an option, we turn to databases. These live outside of the Python process and so might be less convenient. The open source Python ecosystem includes libraries to interact with these databases and with foreign data in general. # # Examples: # # * SQL - [`sqlalchemy`](http://sqlalchemy.org) # * Hive/Cassandra - [`pyhive`](https://github.com/dropbox/PyHive) # * Impala - [`impyla`](https://github.com/cloudera/impyla) # * RedShift - [`redshift-sqlalchemy`](https://pypi.python.org/pypi/redshift-sqlalchemy) # * ... # * MongoDB - [`pymongo`](http://api.mongodb.org/python/current/) # * HBase - [`happybase`](http://happybase.readthedocs.org/en/latest/) # * Spark - [`pyspark`](http://spark.apache.org/docs/latest/api/python/) # * SSH - [`paramiko`](http://www.paramiko.org/) # * HDFS - [`pywebhdfs`](https://pypi.python.org/pypi/pywebhdfs) # * Amazon S3 - [`boto`](https://boto.readthedocs.org/en/latest/) # # Today we're going to use some of these indirectly with `odo` (was `into`) and Blaze. We'll try to point out these libraries as we automate them so that, if you'd like, you can use them independently. # #
# Continuum Logo, # # `odo` (formerly `into`) # ======================= # # Odo migrates data between formats and locations. # # Before we can use a database we need to move data into it. The `odo` project provides a single consistent interface to move data between formats and between locations. # # We'll start with local data and eventually move out to remote data. # # [*odo docs*](http://odo.readthedocs.org/en/latest/index.html) # # #
# ### Examples # # # Odo moves data into a target from a source # # ```python # >>> odo(source, target) # ``` # # The target and source can be either a Python object or a string URI. The following are all valid calls to `into` # # ```python # >>> odo('iris.csv', pd.DataFrame) # Load CSV file into new DataFrame # >>> odo(my_df, 'iris.json') # Write DataFrame into JSON file # >>> odo('iris.csv', 'iris.json') # Migrate data from CSV to JSON # ``` # #
# ### Exercise # # Use `odo` to load the `iris.csv` file into a Python `list`, a `np.ndarray`, and a `pd.DataFrame` # In[3]: from odo import odo import numpy as np import pandas as pd # In[4]: odo("iris.csv", pd.DataFrame) #
# # # URI Strings # ----------- # # Odo refers to foreign data either with a Python object like a `sqlalchemy.Table` object for a SQL table, or with a string URI, like `postgresql://hostname::tablename`. # # URI's often take on the following form # # protocol://path-to-resource::path-within-resource # # Where `path-to-resource` might point to a file, a database hostname, etc. while `path-within-resource` might refer to a datapath or table name. Note the two main separators # # * `://` separates the protocol on the left (`sqlite`, `mongodb`, `ssh`, `hdfs`, `hive`, ...) # * `::` separates the path within the database on the right (e.g. tablename) # # [*odo docs on uri strings*](http://odo.readthedocs.org/en/latest/uri.html) # #
# ### Examples # # Here are some example URIs # # ``` # myfile.json # myfiles.*.csv' # postgresql://hostname::tablename # mongodb://hostname/db::collection # ssh://user@host:/path/to/myfile.csv # hdfs://user@host:/path/to/*.csv # ``` # #
# ### Exercise # # Migrate your CSV file into a table named `iris` in a new SQLite database at `sqlite:///my.db`. Remember to use the `::` separator and to separate your database name from your table name. # # [*odo docs on SQL*](http://odo.readthedocs.org/en/latest/sql.html) # In[5]: odo("iris.csv", "sqlite:///my.db::iris") # What kind of object did you get receive as output? Call `type` on your result. # In[6]: type(_) #
# # How it works # ------------ # # Odo is a network of fast pairwise conversions between pairs of formats. We when we migrate between two formats we traverse a path of pairwise conversions. # # We visualize that network below: # # ![](images/conversions.png) # # Each node represents a data format. Each directed edge represents a function to transform data between two formats. A single call to into may traverse multiple edges and multiple intermediate formats. Red nodes support larger-than-memory data. # # A single call to into may traverse several intermediate formats calling on several conversion functions. For example, we when migrate a CSV file to a Mongo database we might take the following route: # # * Load in to a `DataFrame` (`pandas.read_csv`) # * Convert to `np.recarray` (`DataFrame.to_records`) # * Then to a Python `Iterator` (`np.ndarray.tolist`) # * Finally to Mongo (`pymongo.Collection.insert`) # # Alternatively we could write a special function that uses MongoDB's native CSV # loader and shortcut this entire process with a direct edge `CSV -> Mongo`. # # These functions are chosen because they are fast, often far faster than converting through a central serialization format. # # This picture is actually from an older version of `odo`, when the graph was still small enough to visualize pleasantly. See [*odo docs*](http://odo.readthedocs.org/en/latest/overview.html) for a more updated version. # #
# Remote Data # ----------- # # We can interact with remote data in three locations # # 1. On Amazon's S3 (this will be quick) # 2. On a remote machine via `ssh` # 3. On the Hadoop File System (HDFS) # # For most of this we'll wait until we've seen Blaze, briefly we'll use S3. # # ### S3 # # For now, we quickly grab a file from Amazon's `S3`. # # This example depends on [`boto`](https://boto.readthedocs.org/en/latest/) to interact with S3. # # conda install boto # # [*odo docs on aws*](http://odo.readthedocs.org/en/latest/aws.html) # In[8]: odo('s3://nyqpug/tips.csv', pd.DataFrame) #
# # Continuum Logo, # # Blaze # ===== # # Blaze translates a subset of numpy/pandas syntax into database queries. It hides away the database. # # On simple datasets, like CSV files, Blaze acts like Pandas with slightly different syntax. In this case Blaze is just using Pandas. #
# # ### Pandas example # In[9]: import pandas as pd df = pd.read_csv('iris.csv') df.head(5) # In[10]: df.Species.unique() # In[11]: df.Species.drop_duplicates() #
# # ### Blaze example # In[12]: import blaze as bz d = bz.Data('iris.csv') d.head(5) # In[13]: d.Species.distinct() #
# # Foreign Data # ------------ # # Blaze does different things under-the-hood on different kinds of data # # * CSV files: Pandas DataFrames (or iterators of DataFrames) # * SQL tables: [SQLAlchemy](http://sqlalchemy.org). # * Mongo collections: [PyMongo](http://api.mongodb.org/python/current/) # * ... # # SQL # --- # # We'll play with SQL a lot during this tutorial. Blaze translates your query to SQLAlchemy. SQLAlchemy then translates to the SQL dialect of your database, your database then executes that query intelligently. # # * Blaze $\rightarrow$ SQLAlchemy $\rightarrow$ SQL $\rightarrow$ Database computation # # This translation process lets analysts interact with a familiar interface while leveraging a potentially powerful database. # # To keep things local we'll use SQLite, but this works with any database with a SQLAlchemy dialect. Examples in this section use the iris dataset. Exercises use the Lahman Baseball statistics database, year 2013. # # If you have not downloaded this dataset you could do so here - https://github.com/jknecht/baseball-archive-sqlite/raw/master/lahman2013.sqlite. # #
# In[14]: get_ipython().system('ls') # ### Examples # # Lets dive into Blaze Syntax. For simple queries it looks and feels similar to Pandas # In[15]: db = bz.Data('sqlite:///my.db') #db.iris #db.iris.head() # In[16]: db.iris.Species.distinct() # In[17]: db.iris[db.iris.Species == 'versicolor'][['Species', 'SepalLength']] #
# # ### Work happens on the database # # If we were using pandas we would read the table into pandas, then use pandas' fast in-memory algorithms for computation. Here we translate your query into SQL and then send that query to the database to do the work. # # * Pandas $\leftarrow_\textrm{data}$ SQL, then Pandas computes # * Blaze $\rightarrow_\textrm{query}$ SQL, then database computes # # If we want to dive into the internal API we can inspect the query that Blaze transmits. # #
# In[18]: # Inspect SQL query query = db.iris[db.iris.Species == 'versicolor'][['Species', 'SepalLength']] print bz.compute(query) # In[19]: query = bz.by(db.iris.Species, longest=db.iris.PetalLength.max(), shortest=db.iris.PetalLength.min()) print bz.compute(query) # In[20]: odo(query, list) #
# # ### Exercises # # Now we load the Lahman baseball database and perform similar queries # In[21]: # db = bz.Data('postgresql://postgres:postgres@ec2-54-159-160-163.compute-1.amazonaws.com') # Use Postgres if you don't have the sqlite file db = bz.Data('sqlite:///lahman2013.sqlite') db.dshape # In[ ]: # View the Salaries table # In[ ]: # What are the distinct teamIDs in the Salaries table? # In[ ]: # What is the minimum and maximum yearID in the Sarlaries table? # In[ ]: # For the Oakland Athletics (teamID OAK), pick out the playerID, salary, and yearID columns # In[ ]: # Sort that result by salary. # Use the ascending=False keyword argument to the sort function to find the highest paid players #
# # ### Example: Split-apply-combine # # In Pandas we perform computations on a *per-group* basis with the `groupby` operator. In Blaze our syntax is slightly different, using instead the `by` function. # In[23]: import pandas as pd iris = pd.read_csv('iris.csv') iris.groupby('Species').PetalLength.min() # In[24]: iris = bz.Data('sqlite:///my.db::iris') bz.by(iris.Species, largest=iris.PetalLength.max(), smallest=iris.PetalLength.min()) print(_) #
# # Store Results # ------------- # # By default Blaze only shows us the first ten lines of a result. This provides a more interactive feel and stops us from accidentally crushing our system. Sometimes we do want to compute all of the results and store them someplace. # # Blaze expressions are valid sources for `odo`. So we can store our results in any format. # In[25]: iris = bz.Data('sqlite:///my.db::iris') query = bz.by(iris.Species, largest=iris.PetalLength.max(), # A lazily evaluated result smallest=iris.PetalLength.min()) odo(query, list) # A concrete result #
# # ### Exercise: Storage # # The solution to the first split-apply-combine problem is below. Store that result in a list, a CSV file, and in a new SQL table in our database (use a uri like `sqlite://...` to specify the SQL table.) # In[26]: result = bz.by(db.Salaries.teamID, avg=db.Salaries.salary.mean(), max=db.Salaries.salary.max(), ratio=db.Salaries.salary.max() / db.Salaries.salary.min() ).sort('ratio', ascending=False) # In[27]: odo(result, list)[:10]