Yandex Cloud
Search
Discuss with expertTry it for free
  • Customer Stories
  • Documentation
  • Blog
  • All Services
  • System Status
  • Marketplace
    • Featured
    • Infrastructure & Network
    • Data Platform
    • AI for business
    • Security
    • DevOps tools
    • Serverless
    • Monitoring & Resources
  • All Solutions
    • By industry
    • By use case
    • Economics and Pricing
    • Security
    • Technical Support
    • Start testing with double trial credits
    • Cloud credits to scale your IT product
    • Gateway to Russia
    • Cloud for Startups
    • Center for Technologies and Society
    • Yandex Cloud Partner program
    • Price calculator
    • Pricing plans
  • Customer Stories
  • Documentation
  • Blog
© 2026 Direct Cursus Technology L.L.C.
Tutorials
    • All tutorials
    • Unassisted deployment of the Apache Kafka® web interface
    • Upgrading a Managed Service for Apache Kafka® cluster to migrate from ZooKeeper to KRaft
    • Migrating a database from a third-party Apache Kafka® cluster to Managed Service for Apache Kafka®
    • Moving data between Managed Service for Apache Kafka® clusters using Data Transfer
    • Delivering data from Managed Service for MySQL® to Managed Service for Apache Kafka® using Data Transfer
    • Delivering data from Managed Service for MySQL® to Managed Service for Apache Kafka® using Debezium
    • Delivering data from Managed Service for PostgreSQL to Managed Service for Apache Kafka® using Data Transfer
    • Delivering data from Managed Service for PostgreSQL to Managed Service for Apache Kafka® using Debezium
    • Delivering data from Managed Service for YDB to Managed Service for Apache Kafka® using Data Transfer
    • Delivering data from Managed Service for Apache Kafka® to Managed Service for ClickHouse® using Data Transfer
    • Delivering data from Managed Service for Apache Kafka® to Yandex MPP Analytics for PostgreSQL using Data Transfer
    • Delivering data from Managed Service for Apache Kafka® to Yandex StoreDoc using Data Transfer
    • Delivering data from Managed Service for Apache Kafka® to Managed Service for MySQL® using Data Transfer
    • Delivering data from Managed Service for Apache Kafka® to Managed Service for OpenSearch using Data Transfer
    • Delivering data from Managed Service for Apache Kafka® to Managed Service for PostgreSQL using Data Transfer
    • Delivering data from Managed Service for Apache Kafka® to Managed Service for YDB using Data Transfer
    • Delivering data from Managed Service for Apache Kafka® to Data Streams using Data Transfer
    • Delivering data from Data Streams to Managed Service for YDB using Data Transfer
    • Delivering data from Data Streams to Managed Service for Apache Kafka® using Data Transfer
    • YDB change data capture and delivery to YDS
    • Configuring Kafka Connect to work with a Managed Service for Apache Kafka® cluster
    • Synchronizing Apache Kafka® topics in Object Storage with no web access
    • Monitoring message loss in an Apache Kafka® topic
    • Automating Query tasks with Managed Service for Apache Airflow™
    • Sending requests to the Yandex Cloud API via the Yandex Cloud Python SDK
    • Configuring an SMTP server to send e-mail notifications
    • Adding data to a ClickHouse® DB
    • Migrating data to Managed Service for ClickHouse® using ClickHouse®
    • Migrating data to Managed Service for ClickHouse® using Data Transfer
    • Delivering data from Managed Service for MySQL® to Managed Service for ClickHouse® using Data Transfer
    • Asynchronously replicating data from PostgreSQL to ClickHouse®
    • Exchanging data between Managed Service for ClickHouse® and Yandex Data Processing
    • Configuring Managed Service for ClickHouse® for Graphite
    • Fetching data from Managed Service for Apache Kafka® to Managed Service for ClickHouse®
    • Fetching data from Managed Service for Apache Kafka® to ksqlDB
    • Fetching data from RabbitMQ to Managed Service for ClickHouse®
    • Saving a data stream from Data Streams to Managed Service for ClickHouse®
    • Asynchronous replication of data from Yandex Metrica to ClickHouse® using Data Transfer
    • Using hybrid storage in Managed Service for ClickHouse®
    • Sharding Managed Service for ClickHouse® tables
    • Loading data from Yandex Direct to a Managed Service for ClickHouse® data mart using Cloud Functions, Object Storage, and Data Transfer
    • Loading data from Object Storage to Managed Service for ClickHouse® using Data Transfer
    • Migrating data from Managed Service for OpenSearch to Managed Service for ClickHouse® with a storage change using Data Transfer
    • Loading data from Managed Service for YDB to Managed Service for ClickHouse® using Data Transfer
    • Yandex Managed Service for ClickHouse® integration with Microsoft SQL Server via ClickHouse® JDBC Bridge
    • Migrating databases from Google BigQuery to Managed Service for ClickHouse®
    • Yandex Managed Service for ClickHouse® integration with Oracle via ClickHouse® JDBC Bridge
    • Configuring Cloud DNS to access a Managed Service for ClickHouse® cluster from other cloud networks
    • Migrating a Yandex Data Processing HDFS cluster to a different availability zone
    • Importing data from Managed Service for MySQL® to Yandex Data Processing using Sqoop
    • Importing data from Managed Service for PostgreSQL to Yandex Data Processing using Sqoop
    • Mounting Object Storage buckets to the file system of Yandex Data Processing hosts
    • Working with Apache Kafka® topics using Yandex Data Processing
    • Automating operations with Yandex Data Processing using Managed Service for Apache Airflow™
    • Shared use of Yandex Data Processing tables through Apache Hive™ Metastore
    • Transferring metadata across Yandex Data Processing clusters using Apache Hive™ Metastore
    • Importing, processing, and exporting Object Storage data to Managed Service for ClickHouse®
    • Migrating collections from a third-party MongoDB cluster to Yandex StoreDoc
    • Migrating data to Yandex StoreDoc
    • Migrating Yandex StoreDoc cluster from version 4.4 to 6.0
    • Sharding Yandex StoreDoc collections
    • Yandex StoreDoc performance analysis and optimization
    • Managed Service for MySQL® performance analysis and optimization
    • Syncing data from a third-party MySQL® cluster to Managed Service for MySQL® using Data Transfer
    • Migrating a database from Managed Service for MySQL® to a third-party MySQL® cluster
    • Migrating a database from Managed Service for MySQL® to Object Storage using Data Transfer
    • Migrating data from Object Storage to Managed Service for MySQL® via Data Transfer
    • Delivering data from Managed Service for MySQL® to Managed Service for Apache Kafka® using Data Transfer
    • Delivering data from Managed Service for MySQL® to Managed Service for Apache Kafka® using Debezium
    • Migrating a database from Managed Service for MySQL® to Managed Service for YDB using Data Transfer
    • MySQL® change data capture and delivery to YDS
    • Migrating data from Managed Service for MySQL® to Managed Service for PostgreSQL using Data Transfer
    • Migrating data from AWS RDS for PostgreSQL to Managed Service for PostgreSQL using Data Transfer
    • Migrating data from Managed Service for MySQL® to Yandex MPP Analytics for PostgreSQL using Data Transfer
    • Configuring an index policy in Managed Service for OpenSearch
    • Configuring a cold storage policy in Managed Service for OpenSearch
    • Migrating data from a third-party OpenSearch cluster to Managed Service for OpenSearch using Data Transfer
    • Loading data from Managed Service for OpenSearch to Object Storage using Data Transfer
    • Migrating data from Managed Service for OpenSearch to Managed Service for YDB using Data Transfer
    • Copying data from Managed Service for OpenSearch to Yandex MPP Analytics for PostgreSQL using Yandex Data Transfer
    • Migrating data from Managed Service for PostgreSQL to Managed Service for OpenSearch using Data Transfer
    • Authenticating a Managed Service for OpenSearch cluster in OpenSearch Dashboards using Keycloak
    • Using the yandex-lemmer plugin in Managed Service for OpenSearch
    • Sending email notifications in Managed Service for OpenSearch
    • Connecting an MCP client to an OpenSearch cluster
    • Creating a PostgreSQL cluster for 1C:Enterprise
    • Troubleshooting Managed Service for PostgreSQL cluster performance
    • Managed Service for PostgreSQL performance analysis and optimization
    • Logical replication in PostgreSQL
    • Migrating a database from a third-party PostgreSQL cluster to Managed Service for PostgreSQL
    • Migrating a database from Managed Service for PostgreSQL
    • Migrating a Managed Service for PostgreSQL cluster to a different version
    • Delivering data from Managed Service for PostgreSQL to Managed Service for Apache Kafka® using Data Transfer
    • Delivering data from Managed Service for PostgreSQL to Managed Service for Apache Kafka® using Debezium
    • Delivering data from Managed Service for PostgreSQL to Managed Service for YDB using Data Transfer
    • Migrating a database from Managed Service for PostgreSQL to Object Storage
    • Migrating data from Object Storage to Managed Service for PostgreSQL via Data Transfer
    • PostgreSQL change data capture and delivery to YDS
    • Migrating data from Managed Service for PostgreSQL to Managed Service for MySQL® using Data Transfer
    • Migrating data from Managed Service for PostgreSQL to Managed Service for OpenSearch using Data Transfer
    • Fixing string sorting issues in PostgreSQL after a glibc upgrade
    • Using a Yandex Lockbox secret in a PySpark job to connect to Yandex Managed Service for PostgreSQL
    • Configuring permissions for access to a secret created by Connection Manager for a Managed Service for PostgreSQL user
    • Migrating a database from Greenplum® to ClickHouse®
    • Migrating a database from Greenplum® to PostgreSQL
    • Exporting Greenplum® data to a cold storage in Object Storage
    • Loading data from Object Storage to Yandex MPP Analytics for PostgreSQL using Data Transfer
    • Copying data from Managed Service for OpenSearch to Yandex MPP Analytics for PostgreSQL using Yandex Data Transfer
    • Creating an external table from a Object Storage bucket table using a configuration file
    • Getting data from external sources using named queries in Greenplum®
    • Migrating a database from a third-party Valkey™ cluster to Yandex Managed Service for Valkey™
    • Using a Yandex Managed Service for Valkey™ cluster as a PHP session storage
    • Loading data from Object Storage to Managed Service for YDB using Data Transfer
    • Loading data from Managed Service for YDB to Object Storage using Data Transfer
    • Processing Audit Trails events
    • Processing Cloud Logging logs
    • Processing Debezium CDC streams
    • Analyzing data with Jupyter
    • Processing usage detail files in Yandex Cloud Billing
    • Ingesting data into storage systems
    • Smart log processing
    • Data transfer in microservice architectures
    • Migrating data to Object Storage using Data Transfer
    • Migrating data from a third-party Greenplum® or PostgreSQL cluster to Yandex MPP Analytics for PostgreSQL using Data Transfer
    • Migrating Yandex StoreDoc clusters
    • Migrating MySQL® clusters
    • Migrating to a third-party MySQL® cluster
    • Migrating PostgreSQL clusters
    • Creating a schema registry to deliver data in Debezium CDC format from Apache Kafka®
    • Automating operations using Yandex Managed Service for Apache Airflow™
    • Working with an Object Storage table from a PySpark job
    • Integrating Yandex Managed Service for Apache Spark™ with Apache Hive™ Metastore
    • Running a PySpark job using Yandex Managed Service for Apache Airflow™
    • Using Yandex Object Storage in Yandex Managed Service for Apache Spark™
    • Yandex Managed Service for Apache Spark™ integration with DataSphere
    • Using a Yandex Lockbox secret in a PySpark job to connect to Yandex Managed Service for PostgreSQL
    • Running a PySpark job in Yandex Managed Service for YTsaurus

In this article:

  • Getting started
  • Installing and configuring the yandex_query_magic package
  • Configuring the package
  • Testing the package
  • Query templating using Mustache syntax
  • Jinja2
  • Built-in Mustache templates
  • Jinja templates
  • Capturing command results
  1. Building a data platform
  2. Analyzing data with Jupyter

Analyzing data with Jupyter

Written by
Yandex Cloud
Updated at July 6, 2026
View in Markdown
  • Getting started
  • Installing and configuring the yandex_query_magic package
    • Configuring the package
    • Testing the package
  • Query templating using Mustache syntax
    • Jinja2
    • Built-in Mustache templates
    • Jinja templates
  • Capturing command results

Yandex Query supports integration with Jupyter and VSCode through the cell (%%yq) and line (%yq) Python magic commands. The integration allows you to streamline data collection and analysis for a more efficient and straightforward workflow.

jupyter-screenshot

To analyze Query data with Jupyter:

  1. Install and configure the yandex_query_magic package.
  2. Try creating query templates.
  3. Process the execution results.

Getting startedGetting started

  1. Sign up for Yandex Cloud and create a billing account:

    1. Navigate to the management console and log in to Yandex Cloud or create a new account.
    2. On the Yandex Cloud Billing page, make sure you have a billing account linked and it has the ACTIVE or TRIAL_ACTIVE status. If you do not have a billing account, create one and link a cloud to it.

    If you have an active billing account, you can create or select a folder for your infrastructure on the cloud page.

    Learn more about clouds and folders here.

  2. Get access to the JupyterLab or Jupyter Notebook environment.

Installing and configuring the yandex_query_magic packageInstalling and configuring the yandex_query_magic package

Jupyter
Shell

Install the yandex_query_magic package by running this command in the notebook cell:

%pip install yandex_query_magic --upgrade
  1. Install the yandex_query_magic package using pip:

    pip install yandex_query_magic --upgrade
    
  2. Enable the Jupyter extension for the Jupyter Notebook UI controls:

    %jupyter contrib nbextension install --user
    

    If you get the "No module named 'notebook.base'" error, try upgrading to Jupyter Notebook 6.4.12:

    pip install --upgrade notebook==6.4.12
    

Configuring the packageConfiguring the package

To configure the yandex_query_magic package, you can use the yq_settings line command with the following arguments specified:

%yq_settings --folder-id <folder_ID> ...

Available parameters:

  • --folder-id <folder_id>: ID of the folder to run Query queries. The folder hosting a VM instance with Jupyter is used by default.
  • --vm-auth: Authentication with the VM account key. For more information, see Using Yandex Cloud from within a VM.
  • --env-auth <environment_variable>: Authentication with the authorized key kept in the environment variable. Use this mode when you cannot access the file system of the computer running Jupyter. For example, in Yandex DataSphere. In which case create a DataSphere secret and specify its name in the --env-auth parameter.
  • --sa-file-auth <authorized_key>: Authentication with authorized keys. For more information, see Creating an authorized key.

Testing the packageTesting the package

You can use the %yq line magic command with a single-line SQL query. In this case, the %yq keyword is used to run the query.

If Jupyter is running on a VM with an attached service account, upload the extension to Jupyter:

%load_ext yandex_query_magic
%yq SELECT "Hello, world!"

Where:

  • %yq: Jupyter magic name.
  • SELECT "Hello, world!": Text of the query to Query.

If the VM does not have any attached service accounts:

  1. Create a service account and assign the yq.viewer role to it.

  2. Create an authorized key for the service account.

  3. Run the following commands specifying the path to the authorized key file:

    %load_ext yandex_query_magic
    %yq_settings --sa-file-auth '<path_to_key_file>'
    %yq SELECT "Hello, world!"
    

    Here is an example:

    %load_ext yandex_query_magic
    %yq_settings --sa-file-auth '/home/test/authorized_key.json'
    %yq SELECT "Hello, world!"
    

    The path to the authorized_key.json file is specified relative to the directory the current Jupyter Notebook file is saved in.

To send multi-line SQL queries, you need to use %%yq cell magic. The query text must begin with the %%yq keyword:

%%yq --folder-id <folder_ID> --name "My query" --description "Test query" --raw-results

SELECT
    col1,
    COUNT(*)
FROM table
GROUP BY col1

Where:

  • --folder-id: ID of the folder to run Query queries. The default folder is the one specified earlier through %yq_settings. If not specified, the folder in which the VM is running is used.
  • --name: Query name.
  • --description: Query description.
  • --raw-results: Returns the unprocessed results of a query run in Query. For the format specification, refer to YQL to JSON type mapping.

Query templating using Mustache syntaxQuery templating using Mustache syntax

You can use query templates shared between Jupyter and Query to work with queries and perform routine operations without writing any code. For this, Query comes with built-in Mustache syntax support. You can use it to write queries, placing all template keywords and directives inside double curly brackets ({{}}). You can use Mustache syntax either with Jinja2 or with the built-in Mustache interpreter.

Built-in mustache templates {{ yq-name }} allow you to insert Jupyter runtime variables into SQL queries. Such variables will be automatically converted into required Query data structures. Here is an example:

myQuery = "select * from Departments"
%yq {{myQuery}}

The system will interpret the {{myQuery}} Mustache string as the name of the variable containing the required text and will send select * from Departments to Query for execution.

Mustache templates streamline Jupyter and Query integration. Suppose you have a Python list lst=["Academy", "Physics"] containing the names of departments whose data you want to process. If Query did not support Mustache syntax, you would need to convert the Python list into a string first and then insert it into your SQL query. Query example:

var lstStr = ",".join(lst)
sqlQuery = f'select "Academy" in ListCreate({lstStr});
%yq {{sqlQuery}}

This example showcases how working with complex data types requires you to understand the specifics of Query SQL syntax. With Mustache syntax, the query becomes simpler:

%yq select "Academy" in {{lst}}

Here, the system will automatically recognize lst as a Python list, insert the SQL fragment required for list processing, and send the following query text to Query:

%yq select "Academy" in ListCreate("Academy", "Physics") as lst

Jinja2Jinja2

We recommend using the built-in Mustache syntax for routine tasks in Jupyter and Query. For advanced templating, use Jinja2.

To install Jinja2, run this command:

%pip install Jinja2

Example of using a Jinja template with the for loop:

{% for user in users %}
    command = "select * from users where name='{{ user }}'"
{% endfor %}

You can also use Jinja templates for data processing operations. In the following example, the operations performed on the department name vary based on the student’s department:

{% if student.department == "Academy" %}
    {{ student.department|upper }}
{% elif upper(student.department) != "MATHS DEPARTMENT" %}
    {{ student.department|capitalize }}
{% endif %}

To make Jinja convert data according to Query rules, use the to_yq filter. Here is how the Python list from the previous example (lst=["Academy", "Physics"]) looks in a Jinja template:

%%yq --jinja2
select "Academy" in {{lst|to_yq}}

To disable templating, use the --no-var-expansion argument:

%%yq --no-var-expansion
...

Built-in Mustache templatesBuilt-in Mustache templates

Built-in mustache templates are enabled by default in Yandex Query to streamline basic operations with Jupyter variables:

lst=["Academy", "Physics"]
%yq select "Academy" in {{lst}}

Using Pandas DataFrame variablesUsing Pandas DataFrame variables

Here is an example of using yandex_query_magic and Mustache syntax with Pandas DataFrame:

  1. Define a variable in Jupyter:

    df = pandas.DataFrame({'_float': [1.0],
                        '_int': [1],
                        '_datetime': [pd.Timestamp('20180310')],
                        '_string': ['foo']})
    

You can use the df variable when querying Yandex Query. During query execution, the system uses the df value to create a temporary table also named df. This table can then be used within the Yandex Query query.

  1. Retrieve the data:

    %%yq
    SELECT
        *
    FROM mytable
    INNER JOIN {{df}}
        ON mytable.id=df._int
    

Pandas to Query type mapping:

Pandas type YQL type Note
int64 Int64 Exceeding the int64 limit will result in a query error.
float64 Double
datetime64[ns] Timestamp Microsecond precision. Entering nanoseconds in the nanosecond field will raise an exception.
str String

Using Python dict variablesUsing Python dict variables

Here is an example of using yandex_query_magic with Mustache syntax and a Python dict:

  1. Define a variable in Jupyter:

    dct = {"a": "1", "b": "2", "c": "test", "d": "4"}
    

    Now you can use the dct variable in Query queries. At query runtime, the system will convert dct into the relevant YQL Dict object:

    Key Value
    a "1"
    b "2"
    c "test"
    d "4"
  2. Retrieve the data:

    %%yq
    SELECT "a" in {{dct}}
    

Python dict to Query type mapping:

Python type YQL type Note
int Int64 Exceeding the int64 limit will result in a query error.
float Double
datetime Timestamp
str String

Another way to convert a dictionary to a Pandas DataFrame is by using a constructor:

df = pandas.DataFrame(dct)

Using Python list variablesUsing Python list variables

Here is an example of using yandex_query_magic with Mustache syntax and a Python dict:

  1. Define a variable in Jupyter:

    lst = [1,2,3]
    

    Now you can use the lst variable in Query queries. At query runtime, the system will convert lst into the relevant YQL Dict object:

  2. Retrieve the data:

    %%yq
    SELECT 1 IN {{lst}}
    

Python list to Query type mapping:

Python type YQL type Note
int Int64 Exceeding the int64 limit will result in a query error.
float Double
datetime Timestamp
str String

Another way to convert a dictionary to a Pandas DataFrame is by using a constructor:

df = pandas.DataFrame(lst,
                      columns =['column1', 'column2', 'column3'])

Jinja templatesJinja templates

Jinja templates make it easy to build SQL queries, allowing you to automatically insert search conditions and other data. This way, you don’t need to write each query from scratch. It can help you streamline your workflow, avoid mistakes, and create more readable code.

You can also use Jinja templates to automate building queries with repetitive parts. For example, you can use template loops to write multiple queries that check different values from a list. This adds even more flexibility, speeding up the process of writing complex queries when you need to handle large amounts of data.

The steps below explain how to filter Yandex Query data using a Python variable.

  1. Define a variable in Jupyter:

    name = "John"
    
  2. Before you run the following code in a Jupyter cell, set the jinja2 flag. It will tell the system to treat SQL queries as Jinja2 templates:

    %%yq <other_parameters> --jinja2
    
    SELECT "{{name}}"
    

    Settings:

    • --jinja2: Enables Jinja template rendering for the query text. To use this flag, you need to install the Jinja2 package (%pip install Jinja2).

filterto_yq filter

Jinja2 is a general-purpose templating engine. When handling variables, it uses a standard string representation of data types.

For example, if you have a Python list lst=["Academy", "Physics"], here is how you can use it in a Jinja template:

%%yq --jinja2
select "Academy" in {{lst}}

Running this code will result in the Unexpected token '[' error. This error occurs because Jinja converts the lst variable to the ["Academy", "Physics"] string using Python rules and ignores Yandex Query-SQL specifics.

To tell Jinja that it should follow Yandex Query rules, use the to_yq filter. In this case, the previous query in the Jinja syntax will look like this:

%%yq --jinja2
select "Academy" in {{lst|to_yq}}

The to_yq Jinja filter converts data to the Yandex Query syntax in the exact same way as built-in Mustache templates.

Capturing command resultsCapturing command results

You can capture the output of a line magic command using an assignment:

varname = %yq <query>

To capture a cell magic command’s output, start the query with the target variable name and the << operator:

%%yq
varname << <query>

From there, you can treat the result as any other Jupyter variable.

For example, let’s use a cell magic to capture the result in the output variable:

output = %yq SELECT 1 as column1

And here we use a line magic to capture the result in the output2 variable:

%%yq
output2 << SELECT 'Two' as column2, 3 as column3

Now, you can use these variables just like any other IPython variable. For example, you can print them:

output

By default, %yq and %%yq commands return a Pandas DataFrame. Its columns match SQL column names, and its rows contain query results. You can disable Pandas DataFrame conversion using the --raw-results argument.

In our example, the output variable has the following structure:

column1
0 1

The output2 variable has the following structure:

column2 column3
0 Two 3

If your query does not return any results (for example, it is insert into table select * from another_table), the return value will be None. If a query returns multiple results, they will be presented as a list.

When you run a query, yandex_query_magic outputs extra details, e.g., query ID, start time, and query duration:

jupyter_query_info

To hide the progress output for a cell, you can use the %%capture command.

%%capture
%%yq
<query>

This will suppress progress output in the console.

Was the article helpful?

Previous
Processing Debezium CDC streams
Next
Processing usage detail files in Yandex Cloud Billing
© 2026 Direct Cursus Technology L.L.C.