Querying Polypheny from Jupyter

The Polypheny IPython extension adds the %poly and %%poly magics to Jupyter notebooks with a Python kernel. Use the Python connector in notebook cells when you need parameter binding or transaction control over Prism. Polypheny also has a built-in notebook editor.

Install and connect

Install the extension into the Python environment used by your notebook kernel.

python -m pip install ipython-polypheny==0.1.3

Enable the HTTP query interface under Interfaces in Polypheny. In a Python notebook cell, load the extension and set the HTTP endpoint. The default HTTP port is 13137. Use an address reachable from the machine running the kernel.

%load_ext poly
%poly db: http://localhost:13137

Run queries

Start a cell with %%poly, followed by a language and an optional namespace. Put the query on the next line. The default namespace is public.

%%poly sql
SELECT CAST(1 AS INTEGER) AS ready

To query a document namespace, pass its name after mql. This example uses the notebook_demo namespace and a products collection with documents containing an in_stock field. Create the namespace, collection, and sample document in a development database from three separate notebook cells.

%poly sql: CREATE DOCUMENT NAMESPACE notebook_demo
%poly mql notebook_demo: db.createCollection("products")
%poly mql notebook_demo: db.products.insertOne({product_name: "Pencil", in_stock: true})
%%poly mql notebook_demo
db.products.find({in_stock: true})

When finished with the example, remove the namespace and its collection.

%poly sql: DROP NAMESPACE notebook_demo

Read results in Python

Use the line magic with a colon before the query to assign its result to a Python variable. Access individual cells by row and column or call dicts() to iterate over rows by column name.

result = %poly sql: SELECT CAST(1 AS INTEGER) AS ready
print(result[0][0])
for row in result.dicts():
    print(row["ready"])

The result_set attribute contains the raw HTTP response as a dictionary. With pandas installed, as_df() converts the result to a DataFrame. Values can remain strings, so check their types before doing numerical calculations. The extension returns identifiers for multimedia and other blob values.

Expand notebook variables

Use -t or --template to substitute notebook variables using ${name} syntax. Template expansion inserts the value directly into the query. Use it with trusted values and use bound parameters in the Python connector for runtime input.

example_value = 7
result = %poly sql -t: SELECT CAST(${example_value} AS INTEGER) AS sample
print(result[0][0])

Run %poly help to see the commands and flags available in the installed version.

© Polypheny GmbH. All Rights Reserved.