Basics: Aggregation, filtering, limits

Now that you have ibis installed and connecting to your Impala, let’s get our feet wet.

import ibis
import os
hdfs_port = os.environ.get('IBIS_WEBHDFS_PORT', 50070)
hdfs = ibis.hdfs_connect(host='quickstart.cloudera', port=hdfs_port)
con = ibis.impala.connect(host='quickstart.cloudera', database='ibis_testing',

Accessing an Impala table

The optional database paramter allows to fully qualify the table.

table = con.table('functional_alltypes')
table = con.table('functional_alltypes', database='ibis_testing')

Column selection and basic expressions

Selecting columns from a table works just like pandas

col = table.double_col

# alternately
col2 = table['bigint_col']

Table columns are equipped with a variety of math operations and other methods to assist in writing your analytics. For example:

expr = col.log2() - 1

Some operations transform arrays to arrays, while others aggregate, like sum and mean:

expr2 = expr.sum()

The methods that are available on columns depend on the type of the column. For example, you won’t see the substr or upper methods for strings on numeric columns:

substr_expr = table.string_col.upper().substr(0, 2)

Notice that printing the expressions to the console does not actually do anything, and shows a graphical representation of the expression you’ve built.

Note: don’t worry too much about the details of the expression tree that’s outputted, it’s very likely to change over time


We can also execute an expression by calling execute on the Impala connection object


There’s a shortcut to make this a little more convenient in interactive use

Interactive mode

Many Ibis expressions can be immediately executed against the database, and it may improve your productivity to have the executed for you whenever you try to print the expression in the console / IPython notebook.

To do this, we have an interactive mode available, which can be turned on/off like so:

ibis.options.interactive = True

Now, any expressions you write will be executed right away


You can select a row range with slicing syntax:


Don’t worry about the syntax here, but expressions resulting in tabular output will come back as a pandas DataFrame by default:

metrics = [table.double_col.sum().name('total')]
expr = table.group_by('string_col').aggregate(metrics)

Verbose mode and logging

You may want to see or log all the Impala queries that Ibis executes under the hood. To do that, use the options.verbose option:

ibis.options.verbose = True

metrics = [table.double_col.sum().name('total')]
expr = table.group_by('string_col').aggregate(metrics)
SELECT `string_col`, sum(`double_col`) AS `total`
FROM ibis_testing.`functional_alltypes`
LIMIT 10000
queries = []
def logger(x):

ibis.options.verbose_log = logger


['SELECT `string_col`, sum(`double_col`) AS `total`\nFROM ibis_testing.`functional_alltypes`\nGROUP BY 1\nLIMIT 10000',
 'SELECT `string_col`, sum(`double_col`) AS `total`\nFROM ibis_testing.`functional_alltypes`\nGROUP BY 1\nLIMIT 10000']
from __future__ import print_function
ibis.options.verbose_log = lambda x: print(x)
ibis.options.verbose = False

Aggregation basics

One of the essential table API functions is aggregate. Aggregation involves the following

  • One or more named aggregate expressions, or reductions
  • Zero or more grouping expressions or column names

This ends up working very similarly to pandas’s groupby mechanism.

Let’s start with a simple reduction:

metric = table.double_col.sum()

As you saw above, you can execute this immediately and obtain a value:


The reduced column can be more complex; for example, you could count the number of null values in a column like so:


To aggregate a table, potentially with grouping keys, we have to give the reduction a name and call aggregate

metric ='double_total')
expr = table.aggregate([metric])
result = con.execute(expr)
0 331785.0

The result here is actually a pandas DataFrame with 1 row and just the one column. We can add another metric and add a grouping key

metric2 = (table.bigint_col + 1).log10().max().name('some_metric')

expr = table.aggregate([metric, metric2], by=['string_col'])

We provide a convenience group_by, a la pandas, to make this a little more composable:

expr = (table.group_by('string_col')
        .aggregate([metric, metric2]))

You can also group by named column expressions

keys = [table.timestamp_col.hour().name('hour'), 'string_col']

expr = table.group_by(keys).aggregate([metric])

# Top 10 by double_total, more on this later
expr.sort_by([('double_total', False)]).limit(10)

In most cases, an aggregation by itself can be evaluated:


This can also be done in simple cases along with group_by:


Many reduction functions have a default expression name, unlike many other Ibis expressions (for now!), to make some common analyses easier:

d = table.double_col

 .aggregate([d.sum(), d.mean(), d.min(), d.max()]))

Of course, for this particular case you can always use summary



Filtering tables works similarly to pandas

table[table.bigint_col > 50].count()

Filters can be composed using & (and), | (or), and other logical array operators

cond1 = table.bigint_col > 50
cond2 = table.int_col.between(2, 7)
table[cond1 | cond2].count()

There’s a filter function that allows you to pass a list of conditions (that are all required to hold):

table.filter([cond1, cond2]).count()

Note this is the same as &-ing the boolean conditions yourself:

table[cond1 & cond2].count()


Like in SQL, the limit function selects the indicated numbers of rows from the beginning of a table’s result set