javascriptkeen-io

How to call multiple collections of Keen IO for a single graph?


Can I call multiple collections of Keen IO for a single visualization graph?

Let's say I have a collection named orders:

{
  "order_number": "dfdfd2323",
  "order_price": 21.00,
} 

And I have another collection named adjustments:

{
  "adjustment_id": "34ss3432",
  "adjustment_price": 2.00,
}

Now I want to display a bar graph which shows "total order price for every week" and "total adjustment price for every week". Weeks along x-axis and price on y-axis. Orders and adjustment price in different colors.

Can I make a nested call to Keen IO like this?

client.run(query1, function(){
.....
   client.run(query2, function(){
   }
}

Solution

  • keen-js supports passing an array of queries to client.run() as outlined in this example. Your setup could look something like:

    var orders = new Keen.Query("sum", {
      eventCollection: "orders",
      targetProperty: "order_price",
      interval: "weekly",
      timeframe: "this_month"
    });
    
    var adjustments = new Keen.Query("sum", {
      eventCollection: "adjustments",
      targetProperty: "adjustment_price",
      interval: "weekly",
      timeframe: "this_month"
    });
    
    client.run([orderTotals,priceAdjustments],function(response) {
      var orderTotals = response[0].result;
      var adjustmentTotals = response[1].result;
    
      // code that draws the chart
    }
    

    The trick is understanding that the results of the queries are returned in an array in the same order as the array passed to client.run() via the response variable (or this.data if you prefer). The result of the first query in your array is returned as response[0], the second response[1], and so on and so forth. Likewise with this.data, you'd use this.data[0] and this.data[1].

    The chart shown in the example is a line chart, but could just as easily be configured to be displayed as a bar chart via the chartType property.