如何为单个图形调用多个Keen IO集合?

时间:2015-01-08 04:56:26

标签: javascript keen-io

我可以为单个可视化图调用多个Keen IO集合吗?

假设我有一个名为orders的集合:

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

我有另一个名为adjustments的集合:

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

现在我想显示一个条形图,显示“每周的总订单价格”和“每周的总调整价格”。沿x轴的周数和y轴的价格。不同颜色的订单和调整价格。

我可以像这样对Keen IO进行嵌套调用吗?

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

2 个答案:

答案 0 :(得分:5)

keen-js支持按this example中所述将查询数组传递给client.run()。您的设置可能如下所示:

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
}

诀窍是理解查询的结果在数组中以与通过client.run()变量传递给response的数组相同的顺序返回(如果您愿意,可以this.data )。数组中第一个查询的结果将返回response[0],第二个response[1],依此类推。与this.data类似,您使用this.data[0]this.data[1]

示例中显示的图表是折线图,但可以轻松配置为通过chartType属性显示为bar chart

答案 1 :(得分:4)

我认为共享导致可视化的代码示例可能也会有所帮助,该可视化结合了两个集合中的查询,如下所示:

// use a variable to ensure timeframe & interval for both queries match
var interval = "daily"
var timeframe = "last_30_days"

var pageviews = new Keen.Query("count", { // first query
    eventCollection: "pageviews",
    interval: interval,
    timeframe: timeframe
});

var uniqueVisitors = new Keen.Query("count_unique", { // second query
    eventCollection: "pageviews",
    targetProperty: "uuid",
    interval: interval,
    timeframe: timeframe
});

var chart = Keen.Dataviz()
  .chartType("linechart")
  .chartOptions({
    hAxis: {
      format:'MMM d',
      gridlines:  {count: 12}
    }
  })
  .prepare();

client.run([pageviews, uniqueVisitors], function(response){ // run the queries

    var result1 = response[0].result  // data from first query
    var result2 = response[1].result  // data from second query
    var data = []  // place for combined results
    var i=0

    while (i < result1.length) {

        data[i]={ // format the data so it can be charted
            timeframe: result1[i]["timeframe"],
            value: [
                { category: "Pageviews", result: result1[i]["value"] },
                { category: "Visitors", result: result2[i]["value"] }
            ]
        }
        if (i == result1.length-1) { // chart the data
      chart
        .parseRawData({ result: data })
        .render();
        }
        i++;
    }
});

您可以在此处查看图表的图像:https://github.com/keen/keen-js/blob/master/docs/visualization.md#combine-two-line-charts