Cover Image for How to use GraphQL Alias and Aggregation?

How to use GraphQL Alias and Aggregation?

Product

This article is a continuation of our GraphQL basics series. In this article, we will talk about how to use alias and aggregation with GraphQL queries.

GraphQL Alias

Client-side GraphQL aliasing helps in increasing the readability of APIs and avoid confusion.

Let’s understand this with an example.

The query below provides the DEX trading volume over the years on the Ethereum blockchain.

{
   ethereum {
    dexTrades(options: {asc: ["date.year","date.month"]}) {
      count
      tradeAmount(in: USD)
      date {
        year
        month
      }
    }
  }
}

When you run this query, you will get the following result.

{
  "data": {
    "ethereum": {
      "dexTrades": [
        {
          "count": 26025471,
          "tradeAmount": 79630600909.80501,
          "date": {
            "year": 2020
          }
        },
        {
          "count": 4839824,
          "tradeAmount": 2352564161.2578993,
          "date": {
            "year": 2019
          }
        },
        {
          "count": 6059070,
          "tradeAmount": 4742543997.574773,
          "date": {
            "year": 2018
          }
        },

However, following this result is easy, but the count parameter can create confusion, such as “What does this count represent?”. Let’s make it better.

{  
   ethereum {  
    dexTrades(options: {desc: ["date.year"]}) {  
      numberOfTrades: count  
      tradeAmount(in: USD)  
      date {  
        year  
      }  
    }  
  }  
}

As you can see, we have changed count to numberOfTrades: count . It is now more understandable for anyone looking at API results. Additionally, you can give it any name you want.

Sometimes alias becomes necessary for queries to work. For example, check out the query below.

{
  ethereum {
    transactions(options: {desc: "date.date", limit: 10}) {
      activeAddress: count(uniq: senders)
      date: date {
        date(format: "%Y-%m")
      }
    }
  }
  binanceSmartChain: ethereum(network: bsc) {
    transactions(options: {desc: "date.date", limit: 10}) {
      activeAddress: count(uniq: senders)
      date: date {
        date(format: "%Y-%m")
      }
    }
  }
}

This query is getting active addresses over the years from Ethereum and Binance smart chain. However, if we don’t provide an alias for ethereum(network: bsc), it will throw an error. Therefore, sometimes it is necessary to use an alias to avoid name resolution problems.

Note: Only in GraphQL, you have the power to use aliases in API parameters. It is possible in the Rest APIs.

There are many benefits of using aliases, for example, increasing readability, replacing exiting APIs, etc.

GraphQL Aggregation

Aggregation is critical for performing data analytics. GraphQL technology doesn’t have any pre-build support for aggregation; it only responds to Types. Therefore, you need to define the Types which allow aggregations for your users, and this is exactly what we did. ?

For example, check out the query below, in which we will get Gas related analytics for the Binance smart chain.

query {
  ethereum(network: bsc) {
    transactions(options: {desc: "date.date"},
    date: {since:"2023-06-14"}) {
      date {
        date:startOfInterval(unit: week, offset: 4)
      }
      totalGasUsed: gasValue
      totalGasUsedInUSD: gasValue (in: USD)
      gasValueAvgPerTx: gasValue(calculate: average)
      gasValueAvgPerTxInUSD: gasValue(calculate: average in:USD)
      gasPrice
      avgGasPrice: gasPrice(calculate: average)
      medGasPrice: gasPrice(calculate: median)
      maxGasPrice: gasPrice(calculate: maximum)
      Txs: count 
      Senders: count(uniq: senders)
    }
  }
}

In which, we are performing multiple aggregation functions such as average, median, maximum, count, etc. In addition, we are also performing aggregation on the USD value of Gas for every transaction. gasValue(calculate: average in:USD)

Let’s see another example in which we will sum all the input values of Bitcoin transactions.

​query {
  bitcoin{
    transactions(options: {desc: "date.date"}, 
      date: {since: "2023-05-30", till: "2023-06-29"}, ) {
   txVolUSD: inputValue(calculate: sum in: USD)      
      date{date}
    }
  }
}

Aggregating with limitBy

We recently added an option called limitBy to aggregate data for any arbitrary field used in the query. For example, let’s say we want to know, “what are the top addresses with most transactions daily on the Binance smart chain?

For this, we can use the following query.

query{
  ethereum(network: bsc){
    transactions(
      date: {since: "2023-06-14"}
      options: {desc: "Txs" asc: "date.date"
      limitBy: {each: "date.date" limit: 10}}
    
    ){
      date{
        date
      }
      
      sender{
        address
      }
      
      gasValue
      Txs: count
    }
  }
}

Here we are using limitBy option to perform our aggregation on every date. You can also perform this for any timeframe, such as hour, week, minute, etc.

limitBy option takes 3 parameters.

  • each — each is the field name. The query will return the first “limit” rows for each distinct combination of “each”
  • limit — number of records
  • offset — number of records to skip, starts with 0

As you can see, you can perform different types of aggregation functions using our GraphQL APIs. If you have any questions please, join our Telegram group and let us know.

You might also be interested in:

About Bitquery

Bitquery is a set of software tools that parse, index, access, search, and use information across blockchain networks in a unified way. Our products are:

  • Coinpath® APIs provide blockchain money flow analysis for more than 24 blockchains. With Coinpath’s APIs, you can monitor blockchain transactions, investigate crypto crimes such as bitcoin money laundering, and create crypto forensics tools. Read this to get started with Coinpath®.

  • Digital Assets API provides index information related to all major cryptocurrencies, coins, and tokens.

  • DEX API provides real-time deposits and transactions, trades, and other related data on different DEX protocols like Uniswap, Kyber Network, Airswap, Matching Network, etc.

If you have any questions about our products, ask them on our Telegram channel or email us at sales@bitquery.io. Also, subscribe to our newsletter below, we will keep you updated with the latest in the cryptocurrency world.

Subscribe to our newsletter

Subscribe and never miss any updates related to our APIs, new developments & latest news etc. Our newsletter is sent once a week on Monday.