Query Anyblock ElasticSearch Blockchain Data API with Python

Image for post
Image for post
Featured image: Source code example

Welcome! In this tutorial, you will learn how to use Python to query the Anyblock ElasticSearch blockchain data API. First you will learn to initiate your ElasticSearch Python client. Then we will show you different queries to retrieve data from the Anyblock Index and how to work with Pandas Dataframes to analyze Ethereum Blockchain data. It is obviously possible to do all the query experiments in Python, but we recommend you to test your queries with cURL, or in Postman, and then copy those over to your Python code.

You will learn:

  • How to install and import the necessary libraries
  • Initiate a ElasticSearch client in Python to query the Anyblock Index API
  • How to write basic queries to get Blockchain data
  • How to use aggregation functions in ElasticSearch
  • Working with Bool and Range queries

Useful Resources for using Python with ElasticSearch

Installing the ElasticSearch library in Python

Before being able to use the power of ElasticSearch, we first have to install the ElasticSearch library via pip. Just execute the following command in your shell.

For anaconda users it is also possible to install ElasticSearch via anaconda prompt with this command:

After installing ElasticSearch you can import the library and start working with it:

Connecting to the ElasticSearch Anyblock API is quite simple. We just need to specify the host and the authentication details. The API Keys are listed on your Anyblock Analytics account dashboard. Go to your account and either create a new API key, or copy the already created key.

Initiating a ElasticSearch client is as easy as:

An ElasticSearch client requires a host, in this case we want to interact with the interface of the Ethereum Mainnet. Furthermore we need our HTTP authentication details. Namely the email address of our Anyblock account and our API key.

But there is also another option to initiate the ElasticSearch client. If you don’t want to use HTTP authentication, it is possible to use bearer tokens.

Create blockchain data API queries to Anyblock Index

After all the prerequisites we can start to query the ElasticSearch API. Let’s start with some basic examples and gradually increase and expand our queries. First we are going to use the low level Elasticsearch-py library.

Let’s start with the most basic query. We want to get the latest mined block in the Ethereum Blockchain. So we have to write a query, in which the number of the blocks are in descending order and the output is limited to 1. Why to 1? We want to get the latest Block, not the latest 3, neither the latest 100. The basic structure of a search query is:


  • es is your ElasticSearch client,
  • index is your data structure and database we want to query
  • and body is where we specify our query details.

So if we want to search for the latest Block in the block data structure, we have to sort the results descending by the block number “number.num”. We limit the results to size:1 and pass the variable “query” to the search method parameter “body”. The code would look like this:

The query results are saved in the variable “response”. The body of the results, without the metadata-information about the processing of the query, can be printed with:

We will save the content of response["hits"]["hits"] in the variable elastic_docs. Then we create an empty dictionary source_data. After this we use an enumerate loop, where the key is the number of the single result, and the value is the content of the block which is saved in _source.

After withstanding the first difficulties of our first query, let’s try to create a more complex query. Now we want to query by date. Let’s get the data for all blocks mined between 01.01.2020 00:00:00 and 01.01.2020 06:00:00 UTC. The timestamp for the first date is 1577836800 and 1577858400 for the second date interval. Visit unixtimestamp.com to convert unix timestamps to datetime. We shouldn’t forget to limit the output size of the query. With from-size it is possible to configure the maximum amount of results. From defines the offset from the latest value. It defaults to zero.

What are we doing in this query?

We use ElasticSearch’s range query. With the range query we can get documents that contain the terms with the specified range. In this case we get documents (blocks), which contain the term (timestamp), in the specified range:

  • gte / greater than equal to 1577836800 (01.01.2020 00:00:00)
  • lte / less than equal to 1577858400 (01.01.2020 06:00:00)

The documents which are returned are blocks that are created in the range between these two dates. In a timespan of 6 hours. Between these timestamps, 1185 blocks were mined. We get the results and data for each block mined in this time interval.

After querying the block data, let’s create a query for transactions in the same timespan. Let’s see how many transactions were executed in the same timespan.

What are we doing in this query?

In this query, we combine multiple ElasticSearch queries in a boolean manner. Here we use a bool query, which is a way to combine multiple queries. We are filtering for all documents, which are containing the value “transfer” in events.raw. So we are looking for transfers. Furthermore we use “must” in the bool query, which means that the condition in the query must be satisfied to consider a match. All documents with a match, have to be in the requested timespan. We set the size limit to 50000, but we still only get 5000 results. This is the case, because one query can only return 5000 results. There are different methods for obtaining more results. One way is to work with scroll_ids.

Here you can find a minimal working example of working with the scroll parameter. This tutorial explains the concepts behind iterating over the entire ElasticSearch index.

Looking at the results, we have more than 5000 transactions in the timeframe of six hours.

Now let’s try to build aggregation queries. In this first aggregation example, we want to know in which block the most gas was used. There are many different aggregation functions and in the useful resources chapter you can find the link to the ElasticSearch documentation which is quite detailed in describing the different aggregation methods.

This query returns the amount of gas used for the block in which the “gasUsed” value is the largest.

This basic aggregation query is pretty straight-forward. Let’s do a bucket aggregation in the next step.

Once again we want to look at the timespan (six hours) which was introduced earlier. Now we want to aggregate the amount of transactions per block in the timespan of six hours.

Again we filter for transactions in the given timespan. Furthermore we use the aggregation function to aggregate into buckets based on the field blockNumber.raw which contains the blockNumber in integer format.

We can see that each block contains different amounts of transactions. The block with the most transactions has 126 transactions. The block with the fewest transactions has 90 transactions.

Image for post
Image for post
Image: Source code example. Click to enlarge.


In this tutorial we learned to install ElasticSearch-py, initiate a ElasticSearch client with python and worked with a few basic query examples. We worked with range and bool queries and dipped our toes into ElasticSearch’s powerful aggregation functions. There are many resources for ElasticSearch aggregations which can teach you more complex aggregation functions.

There are many options to work with the results obtained from the Anyblock API. It is possible to import the results into a Pandas DataFrame and start analyzing and visualizing Blockchain data. Furthermore there is ElasticSearch-DSL, which is a high-level library that was built on top of Elasticsearch-py to write and run queries against ElasticSearch more conveniently. If you had troubles working with the low-level library I would recommend checking out the ElasticSearch DSL documentation and the Anyblock API documentation.

Image for post
Image for post
Sascha Göbel — Co-Founder of Anyblock

Sascha Göbel
+49 6131 3272372

Follow us:
Twitter, LinkedIn,
Medium, YouTube

Originally published at https://www.anyblockanalytics.com on November 3, 2020.

Anyblock Analytics is a German blockchain solution provider. We offer consulting, tools and data to integrate business processes with blockchain.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store