Getting Started with Keen IO

Keen IO is an analytics platform that enables developers to build analytics into their product, app, website, or company. The APIs allow you to stream, analyze, visualize and secure your data.

Track any event: signups, swipes, upgrades, purchases, powerups, errors, shares… Build on top of your data with Keen IO’s Compute API, Access API, and Visualization tools. Keen IO is your new, lovingly-crafted, massively scalable, event data backend in the cloud.

What are we doing in this guide?

We believe that getting started with Keen IO APIs should be quick and easy. For the technical wizards among you, this guide will take you 5 minutes. For the sorcerer’s apprentices, this shouldn’t take much more than 12 minutes. If it does, we’ve failed. Let us know!

There are three basic steps to using Keen IO:

  • Step 1: Stream Your Data

  • Step 2: Analyze Your Data

  • Step 3: Visualize Your Data

If you want to start analyzing data from your app right away, as well as see some visualizations, start using our JavaScript SDK. To make this quide as advertized, quick, we are going to suggest that you use your MASTER_KEY for all of the examples on this page. When you start thinking about building out a production implementation make sure that you check out Access Keys to follow data security best practices.

1 - Stream Your Data

Let’s get to the heart of it - event streaming. Events are the actions that are happening that you want to track. Events of a similar type are stored in event collections. Collections are created on-the-fly when you send your first event. In this example we’ll create a new Event Collection and call it purchases, but you can pick any name you want!

Let’s post a new purchase event into the purchases event collection. The event should be in JSON format and look like this example.

{
  "category": "magical animals",
  "animal_type": "pegasus",
  "username": "perseus",
  "payment_type": "head of medusa",
  "price": 4.50
}

You will send this event to Keen using one of our SDKs, or cURL.

Copy and modify the following code for the SDK you’re working with. Replace PROJECT_ID and MASTER_KEY with your specific values.

// npm install keen-js
// Put this in a web page, or run it using `node file_name.js`

// Configure an instance for your project
var client = new Keen({
  projectId: "PROJECT_ID",
  writeKey: "MASTER_KEY",
  readKey: "MASTER_KEY"
});

// Create a data object with the properties you want to send
var purchase = {
  category: "magical animals",
  animal_type: "pegasus",
  username: "perseus",
  payment_type: "head of medusa",
  price: 4.50
};

// Send it to the "purchases" collection
client.addEvent("purchases", purchase);
# gem install keen
# Put this in a file, and run `ruby file_name.rb`

# You can set these in your environment however you'd like
ENV['KEEN_PROJECT_ID'] = 'PROJECT_ID'
ENV['KEEN_READ_KEY'] = 'MASTER_KEY'
ENV['KEEN_WRITE_KEY'] = 'MASTER_KEY'


Keen.publish(:purchases, {
  category: "magical animals",
  animal_type: "pegasus",
  username: "perseus",
  payment_type: "head of medusa",
  price: 4.50
})
# pip install keen
# Save this in a file, and run `python file_name.py`

keen.project_id = "PROJECT_ID"
keen.write_key = "MASTER_KEY"
keen.read_key = "MASTER_KEY"

keen.add_event("purchases", {
  "category": "magical animals",
  "animal_type": "pegasus",
  "username": "perseus",
  "payment_type": "head of medusa",
  "price": 4.50
})
<?
// php composer.phar require keen-io/keen-io:~2.5
// Save this in a file on your web server, then open that page

use KeenIO\Client\KeenIOClient;

  $client = KeenIOClient::factory([
      'projectId' => 'PROJECT_ID',
      'writeKey'  => 'MASTER_KEY',
      'readKey'   => 'MASTER_KEY'
  ]);

  $event = [
    "category" => "magical animals",
    "animal_type" => "pegasus",
    "username" => "perseus",
    "payment_type" => "head of medusa",
    "price" => 4.50
  ]

  $client->addEvent('purchases', $event);
?>
// compile 'io.keen:keen-client-api-android:5.0.1@aar'
/* Save this in a file, then run:
javac file_name.java
java file_name
*/

KeenClient client = new JavaKeenClientBuilder().build();
KeenClient.initialize(client);

// The two master keys here are ordered readKey then writeKey
KeenProject project = new KeenProject(PROJECT_ID, MASTER_KEY, MASTER_KEY);
KeenClient.client().setDefaultProject(project);


Map<String, Object> event = new HashMap<String, Object>();
event.put("category", "magical animals");
event.put("animal_type", "pegasus");
event.put("username", "perseus");
event.put("payment_type", "head of medusa");
event.put("price", 4.50);

KeenClient.client().addEvent("purchases", event);
// PM> Install-Package KeenClient
// Put this in a new file in Visual Studio, and run it!

using Keen.Core; // Replace this with Keen.NET_35 for projects targeting .NET 3.5

var projectSettings = new ProjectSettingsProvider("PROJECT_ID", writeKey: "MASTER_KEY", readKey: "MASTER_KEY");
var keenClient = new KeenClient(projectSettings);

var purchase = new
{
  category = "magical animals",
  animal_type = "pegasus",
  username = "perseus",
  payment_type = "head of medusa",
  price = 4.50
};

keenClient.AddEvent("purchases", purchase);
echo '{
  "category": "magical animals",
  "animal_type": "pegasus",
  "username": "perseus",
  "payment_type": "head of medusa",
  "price": 4.50
}' > purchase1.json

curl "https://api.keen.io/3.0/projects/PROJECT_ID/events/purchases?api_key=MASTER_KEY" -H "Content-Type: application/json" -d @purchase1.json

There are a few things going on here:

  • We initialized the SDK Keen Client (unless you’re using cURL)
  • We send the request to Keen’s API with both the Project ID and the name of the event collection, where we store the event. In this example, the name of your EVENT_COLLECTION is purchases.
  • We’ve automatically created the purchases collection from the event you just sent. Now you have a place to stream all your future purchase events!
  • Third, we included the event JSON in the API Request.

The HTTP response should look like:

{
  "created": true
}

Ta-da!

Once the API acknowledges that your event has been stored, it may take up to 10 seconds before it will appear in query results.

2 - Analyze Your Data

Through our Compute API, you’ll have access to a number of different tools. For the moment, let’s just worry about one: counts. It does exactly what it sounds like it does; it counts the number of times an event has occurred.

To begin with we will try a very simple version of a count. The only parameter we need for a simple count is “event_collection” - this is the set of events we will be counting. Use the same client setup code from above, but replace the add event lines with this:

Simple Count Request

var count = new Keen.Query("count", {
  event_collection: "purchases",
  timeframe: "this_14_days"
});

client.run(count, function(err, response){
  // if (err) handle the error
  console.log(response.result);
});
Keen.count("purchases", :timeframe => "this_14_days")
keen.count("purchases", timeframe="this_14_days")
<?
  $totalPurchases = $client->count("purchases", ["timeframe" => "this_14_days"]);
?>
KeenQueryClient queryClient = new KeenQueryClient.Builder(project).build();

long count = queryClient.count("purchases", new RelativeTimeframe("this_14_days"));
var itemCount = keenClient.client().Query(QueryType.Count(), "purchases", null, QueryRelativeTimeframe.ThisNDays(14));
curl "https://api.keen.io/3.0/projects/PROJECT_ID/queries/count?api_key=MASTER_KEY&event_collection=purchases&timeframe=this_14_days"

This returns a response of:

{
    "result": 1
}

1, Victory! We only inserted one event, so we counted one event. You just got started!!

Here are three more simple examples to show off other compute analyses you can do:

Average Request

Change count to average and add a target_property parameter to let the API know which numeric property you want to average. Here’s how you can run an average on the “price” property.

var count = new Keen.Query("average", {
  event_collection: "purchases",
  target_property: "price",
  timeframe: "this_14_days"
});

client.run(count, function(err, response){
  // if (err) handle the error
  console.log(response.result);
});
Keen.average("purchases", :target_property => "price", :timeframe => "this_14_days")
keen.average("purchases", target_property="price", timeframe="this_14_days")
<?
  $totalPurchases = $client->average("purchases", [
    "target_property" => "price",
    "timeframe" => "this_14_days"
  ]);
?>
KeenQueryClient queryClient = new KeenQueryClient.Builder(project).build();

long count = queryClient.average("purchases", "price", new RelativeTimeframe("this_14_days"));
var itemCount = keenClient.client().Query(QueryType.Average("price"), "purchases", "price", QueryRelativeTimeframe.ThisNDays(14));
curl "https://api.keen.io/3.0/projects/PROJECT_ID/queries/average?api_key=MASTER_KEY&event_collection=EVENT_COLLECTION&target_property=price&timeframe=this_14_days"

And the response will be:

{
    "result": 4.5
}

Request with Interval

You can also add an interval parameter in order to break the results into buckets. Here’s an example with an average of the previous_5_minutes and a “minutely” Interval.

var count = new Keen.Query("count", {
  event_collection: "purchases",
  timeframe: "previous_5_minutes"
  interval: 'minutely'
});

client.run(count, function(err, response){
  // if (err) handle the error
  console.log(response.result);
});
Keen.count("purchases", :interval => 'minutely', :timeframe => "previous_5_minutes")
keen.count("purchases", interval='minutely', timeframe="previous_5_minutes")
<?
  $totalPurchases = $client->count("purchases", [
      "timeframe" => "previous_5_minutes",
      "interval" => "minutely"
    ]);
?>
KeenQueryClient queryClient = new KeenQueryClient.Builder(project)
  .withEventCollection("purchases")
  .withInterval("minutely")
  .withTimeframe(new RelativeTimeframe("previous_5_minutes"))
  .build();

QueryResult result = queryClient.execute(query);
var timeframe = QueryRelativeTimeframe.PreviousNMinutes(5);
var interval = QueryInterval.Minutely();

var itemCount = keenClient.client().QueryInterval(QueryType.Count(), "purchases", null, timeframe, interval);
curl "https://api.keen.io/3.0/projects/PROJECT_ID/queries/count?api_key=MASTER_KEY&event_collection=purchases&timeframe=previous_5_minutes&interval=minutely"

This returns a response of:

{
  "result": [
    {
      "value": 0,
      "timeframe": {
        "start": "2014-03-29T22:44:00.000Z",
        "end": "2014-03-29T22:45:00.000Z"
      }
    },
    {
      "value": 1,
      "timeframe": {
        "start": "2014-03-29T22:45:00.000Z",
        "end": "2014-03-29T22:46:00.000Z"
      }
    },
    {
      "value": 0,
      "timeframe": {
        "start": "2014-03-29T22:46:00.000Z",
        "end": "2014-03-29T22:47:00.000Z"
      }
    },
    {
      "value": 0,
      "timeframe": {
        "start": "2014-03-29T22:47:00.000Z",
        "end": "2014-03-29T22:48:00.000Z"
      }
    },
    {
      "value": 0,
      "timeframe": {
        "start": "2014-03-29T22:48:00.000Z",
        "end": "2014-03-29T22:49:00.000Z"
      }
    }
  ]
}

That’s just the beginning. You’ll find a lot more analysis tools on our website and our API Reference.

Next Steps

Congratulations! You’ve graduated from the Keen Getting Started guide. Admittedly, we’ve just scratched the surface, but hopefully you’ve got some context on what you can build.

Now you can move onto the good stuff and build analytics into your own app! You’ll follow the same basic three steps to using Keen, but now you’ll select from our full range of SDK’s, analysis, and visualization tools.

1. Send Your Data

You can stream data into Keen IO in a variety of ways. The most common is what we did above, sending events via the API, but there’s plenty of other ways:

2. Analyze Your Data

  • Run counts, sums, averages, medians, build funnels, and more using our Analysis APIs!
  • Now that you’ve sent at least one sample event, you might want to try checking out our query builder, Explorer, in Keen IO. Notice that all of the custom properties you send are immediately available for analysis, and you can do a lot more than counts! The Explorer has some query types, but there are even more available by API. Check out filters, funnels, and more in our analysis API docs.

3. Visualize Your Data

  • Ready to see some charts and graphs of your data? Head over to the visualization documentation to learn how to embed charts into dashboards or web pages!

Configure Your Access

Last but not least, make sure to configure your Access Keys. Access Keys can do all sorts of things, like:

  • Separate reading and writing data to specific keys
  • Only allow your customers to see their specific data
  • Automatically add data to your events

Questions? Reach out to us anytime at team@keen.io or chat with us on Keen Community Slack! If you’d like to learn more about how to get the most out of your data, reach out to Schedule a free data consultation with our data science team.