Showing posts with label Big Data. Show all posts
Showing posts with label Big Data. Show all posts

Tuesday, March 29, 2016

AWS Kinesis Firehose

What is Kinesis Firehose?

Kinesis Firehose accepts streaming data and logs the data into Amazon S3 and optionally into a Amazon Redshift table. Each data entry is a json object (name-value pairs). The data stored in S3 is a series of these objects. When uploading the data to Amazon Redshift, Firehose uses the names  to map data to Redshift table columns (names must be all lowercase since Redshift table column names are always lowercase).

Kinesis Firehose is built on Kinesis Streams. It adds the following benefits.
  • Firehose manages the underlying Kinesis Streams and the scaling thereof.
  • With mere configuration, the data can be logged into S3 and into Redshift. That is, no code needs to be written to get the data off the Kinesis Stream and put it in S3 and/Redshift.
Kinesis Firehose has the following disadvantages.
  • The underlying Kinesis stream is hidden from us so we can't write an additional Client (Kinesis Client Library) to read the stream and possibly publish to another destination such as a dashboard.
  • Although each data entry added to Kinesis Firehose Stream may compose of differing data fields, practically speaking each Kinesis Firehose Stream is really useful when dealing with a single type of data. Otherwise, how else would you map the data to columns in a Amazon Redshift table? In other words, each delivery stream loads into a single Redshift Cluster, and table. However, over time additional columns can be added to this data type and automatically mapped to expanded definition of the same Amazon Redshift table (because the data entry rows are stored as json objects). 

Setup

1) Create Kinesis Firehose Delivery Stream. This is where you specify where and how often you want to log data. This can be done from the AWS Console or through Firehose management APIs.

Useful Redshift COPY options
json 'auto' gzip timeformat 'auto' dateformat 'auto' truncatecolumns trimblanks blanksasnull emptyasnull acceptinvchars

2) Write a client or endpoint that places data into the Kinesis Stream. Each data record (also called data blob) can be a maximum of 1,000 KB. API: PutRecord (1MB) or PutRecordBatch (500 records, up to 5 MB total).

Note: There is special Java program called Kinesis Agent that can be deployed to running instance. The agent reads data logged to a file and submits to a Kinesis delivery stream per its configuration.

Data deposited in S3

  • Data is logged in the specified S3 bucket organized by date time. A top level folder can be pre-pended (example, mylog or mylog/, the second one will create a folder).
  • The S3 object names contain a version after the date time. The version corresponds to an increasing integer value (the value is incremented every time the delivery stream config is updated).
  • Data can be gzipped (only compression supported by Redshift COPY).

Data COPY to Redshift

  • Periodically copied from S3 to Redshift using COPY command. Uses manifest files to ensure proper COPY. A manifests folder is created that holds the manifest files.
  • An errors folder is created for failed COPY commands (contains manifest files containing the failed data files).
  • Retries: Try every 5 minutes for 60 minutes. After 60 minutes, skips the current batch and adds manifests to the errors folder. This data must then be manually COPY to Redshift table.

Troubleshooting S3 put

Reference: http://docs.aws.amazon.com/firehose/latest/dev/troubleshooting.html

1. Check data delivery metrics (see below). Is the data flowing?

2. Check the S3 bucket exists.

3. Check Firehose IAM role. Does it have permission to write to S3.

Troubleshooting COPY to Redshift

When COPY fails, Firehose retries every 5 minutes for 1 hour. After that it writes manifests to the "error" folder in S3. While this happening, all other traffic blocked!

1. Check configuration of Redshift config in Firehose

2. Check tracking tables in Redshift.

select * from stl_connection_log where remotehost like '52%' order by recordtime desc;

select * from stl_query order by endtime desc limit 100;

select tablename,
   HAS_TABLE_PRIVILEGE(tablename, 'select') as select,
   HAS_TABLE_PRIVILEGE(tablename, 'insert') as insert,
   HAS_TABLE_PRIVILEGE(tablename, 'update') as update,
   HAS_TABLE_PRIVILEGE(tablename, 'delete') as delete,
   HAS_TABLE_PRIVILEGE(tablename, 'references') as references
from pg_tables where schemaname='public' order by tablename;


select * from stl_load_errors  order by starttime desc;
select * from stl_error where userid!=0 order by recordtime desc;

Monitor Dataselect * from stl_query order by endtime desc limit 10; Delivery Metrics

Kinesis Firehose publishes CloudWatch metrics. The following are particularly useful.

Incoming.Records: Is the data being received in the delivery stream.

DeliveryToS3.Records: Records delivered to S3.

DeliveryToS3.DataFreshness: Maximum age in seconds of the oldest undelivered record in Firehose. Any data older than this has been delivered to S3.

DeliveryToRedshift.Records: Number of records copied to Redshift.

DeliveryToRedshift.Success: Sum  of Redshift COPY commands over sum of all COPY commands.



Tuesday, August 4, 2015

Delete old rows from very large SQL Tables

Objective: Delete rows older a than a certain date/time (age in hours)

Assumptions: The row ids are in ascending order of their creation date

Algorithm:

Get the lowest_id in the table.
SELECT TOP 1 Id From table with(nolock) order by id asc option(maxdop 1)

Get upper_id for the batch by adding the batch size to the lowest_id.
SELECT top 1 id from table with(nolock) where id >= lowestId and id < lowestid+batchcount order by id DESC option (MAXDOP 1)

Get the date_created for the row with upper_id.
SELECT date_created from tablename with(nolock) where id=upper_id option (MAXDOP 1)

If the upperend_date_created older than the specified number of hours, delete all rows below the upper_id .

IF upperend_date_created  <= DATEADD(HOUR, - hours,  GETUTCDATE())
  delete from table where id <= upperendid option (maxdop 1)

Sunday, April 13, 2014

Why Big Data?

In the recent years the following significant events have brought about the notion of big data.
  1. The computational power has grown exponentially
  2. Data storage has become plentiful
  3. Many, many new ways have surfaced that facilitate collection of data. Not only Internet has become ubiquitous, but the ways to access the Internet have multiplied. 
Personal computers, tablets, smart phones, appliances, cars, wireless cameras, physical sensors (weather, radiation, traffic, electron microscopes, etc.), and numerous other devices are connected to the Internet. These devices are communicating and streaming large amounts of data over the Internet to the Servers, and to each other.

Collectively, this constitutes big data.

Why does the data get so big? 

Here's a trivial example. We have a web page that will be visited by 1 million users in a 24-hour period. On the average, the user interacts with the page for 5 minutes. Let's say on the average the user click 30 times on various parts of the Web page during the 5 minute interaction. We want to know what captures users' attention. We record mouse-clicks for all users. We aggregate and analyze mouse-click data to find which part of the web page do the users gravitate to. The data points collected will be roughly 30 * 1,000,000 = 30,000,000 for a single day. If we do this for several days, the amount of data can really add up.

Big data is largely unstructured data

With big data, the normal course is to collect data first and then ask questions later. For example, in the previous example we collect lots of mouse click data. Once this data is collected, we can ask many different kinds of questions by slicing and dicing this data. For example, we can calculate the mean time between mouse clicks to estimate how much time a user spends on a particular page.

The volume and the raw nature of data (mouse clicks) make the traditional fixed-schema relational databases unsuitable for data collection. NoSQL databases provide a more natural fit for accumulating and working on big data because they do not require a fixed-schema definition and scale automatically with increased volume. Tools such as Hadoop can then be run against this vast repository of data to summarize the results for further analysis and to draw conclusions.

Volume, Velocity, Variety

These are the three V's of big data.

Volume: The amount of data to be collected and analyzed is very large.

Velocity: The speed at which this data comes at us is very fast. Great amount of storage and computing power is needed to process this streaming data before it becomes irrelevant.

Variety: The data can be structured or unstructured. The challenge of big data analytics is to coalesce a variety of data inputs to draw useful conclusions and to come up actionable recommendations.

The promise of big data

The size of data recorded, accumulated, and streamed by all these devices is huge. But now we have equally enormous computing power and storage to store and analyze this data in various fields such as genomics, astronomy, physical and chemical sciences, law enforcement, security, and social media.

Analysis of big data that may contain millions or even billions of data  points can yield results and trends that cannot be predicted even with the best predictive models. Machine learning algorithms, statistical techniques, or even simply visualization of the big data as charts can provide deep insight into trends and behaviors behind the data.

Saturday, April 12, 2014

NoSQL Databases


NoSQL Features

  • Support large volumes of data
  • Can be used for data of record or big data analysis
  • Non-relational (tables cannot have foreign key constraints)
  • Easy to distribute data amongst multiple nodes (cluster-friendly)
  • No set schema - even within one table each row may contain data with different attributes (columns)
  • Popular database: mongoDB, Cassandra, CouchDB, RavenDB, Neo4j, HBASE, redis, riak, Project Voldermart, DynamoDB, Azure Tables

Data Models

Key-value

  • Given a key, give me the value. The value can be anything. Persistent hash map.
  • The value content cannot be queried directly but can store metadata and write queries against the metadata.
  • riak, redis, Project Voldemar, Dynamo

Document Data Model

  • Storage of large number of documents; each document is a data structure, usually JSON
  • The contents can be queried
  • mongoDB, RavenDB, couchDB

Column-family

  • Key mapped to a one or more column families. Each column family has key-value pairs. Multiple families (e.g. Invoice and InvoiceLineItems in one record).
  • Conducive to distribution of data amongst nodes (don't have to jump nodes to get one aggregate)
  • Entire aggregate in one record.
  • Cassandar, HBASE 

Graph 

  • NoSQL works well when accessing a pre-defined aggregate. To access (re-arrange) a different aggregate is more difficult in NoSQL than RDBMs
  • Special queries for graph structures
  • Node and arcs structure. Each to move from relation to relation.
  • Neo4j