Tuesday, July 18, 2017

JAVA and Scala Errors

1. For maven build errors:

In POM.xml add
 <build>
    <sourceDirectory>src</sourceDirectory>
    <resources>
      <resource>
        <directory>src</directory>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

2. For the error:

Exception in thread "main" java.lang.UnsupportedClassVersionError: Sparkjobs/Wordcount : Unsupported major.minor version 52.0


In Ecllipse,
Window -> Preferences -> Scala ->Compiler -> target Lower to jvm-1.7

3. In case of class not found exception for scala JAR,

In Ecllipse,
Window -> Preferences -> JAVA->Compiler -> compiler compliance level to jvm-1.7

4. In case of,

Unable to locate the Javac Compiler in:   C:\Program Files\Java\jre1.8.0_101\..\lib\tools.jar Please ensure you are using JDK 1.4 or above and not a JRE (the com.sun.tools.javac.Main class is required)

See if JDK 1.8.0 is installed if not install it.

Try updating the JDK Eclipse is using, as follows:
Add and set the JRE in Window->Preferences...->Java->Installed JREs:
JRE type: Standard VM JRE 
Name: jdk1.6.0_18
JRE home directory: C:\Program Files (x86)\Java\jdk1.6.0_18
https://stackoverflow.com/questions/2222560/maven-build-failed-unable-to-locate-the-javac-compiler-in-jre-or-jdk-issue

5. In spark streaming job, if encountered the below error:

ERROR streaming.StreamingContext: Error starting the context, marking it as stopped
org.apache.kafka.common.config.ConfigException: Missing required configuration "bootstrap.servers" which has no default value.

Then modify metadata.broker.list to "bootstrap.servers"

in case of similar errors like "value.deserializer" or "key.deserializer" 

    val kafkaParams = Map("bootstrap.servers" -> brokers,
                        "key.deserializer" -> classOf[StringDeserializer],
                        "value.deserializer" -> classOf[StringDeserializer])

6. To run a JAR:
2 Options:
1. Add main class in Manifest file
2. Include Manifest in POM.xml
https://stackoverflow.com/questions/9689793/cant-execute-jar-file-no-main-manifest-attribute

Run using command:
java -cp consumerTest-0.0.1-SNAPSHOT.jar consumerTest.KafkaConsumer

7. To configure settings for compiling maven via command prompt:
configure java for windows https://stackoverflow.com/questions/1672281/environment-variables-for-java-installation
MVN clean install

8. To include all the dependencies in the Jar file, follow 
In case of error,
 Exception in thread "PollableSourceRunner-KafkaSource-kafka-source" java.lang.NoSuchMethodError: scala.Predef$.ArrowAssoc(Ljava/lang/Object;)Ljava/lang/Object;

This occurred because of missing dependencies on the machine JAR is being executed.
Package all the Jars into the deployed jar.
https://stackoverflow.com/questions/1729054/including-dependencies-in-a-jar-with-maven. This would PACKAGE all the dependant jars inside single JAR


9. In case of any function call giving error because of mismatched input arguments then look for the appropriate imports.

10. Java Decompiler can be installed in Ecllipse follow: http://jd.benow.ca/

Monday, July 17, 2017

Data Modelling

ER Diagram is the first step to build datawarehouse model

Entity Relation model

Data Modelling: An archirects job. 


Tables that makeup the warehouse are mentioned, the relationship between the tables is mentioned. the primary and foriegn keys are also mentioned.

3 Types of data models:


1. Conceptual Data model: 

First step, High level overview of datawarehouse.
Primarly for business consumers, very less technical details and not useful for developers.
Just gives information about the related tables. No primary and foriegn key specification.
2. Logical Data model; an extension to conception data model.
Specifies the keys/attributes in the tables relation. 
primary and foriegn keys are specified.
columns involved in each table.

3. Physical data model: Datatypes for each column, Not NULLS
Views procedures and Indexes will also be specified.



Types of datawarehouse designs:

Agile Datawarehouse design

Dimentional modelling

Sunday, July 16, 2017

Database Denormalization

Denormalization:


Constraints:Constraints in DBMS. Constraints enforce limits to the data or type of data that can be inserted/updated/deleted from a table. The whole purpose of constraints is to maintain the data integrity during an update/delete/insert into a table

Denormalization techniques:

1. Materialized views

2. Star schema:

Fact and Dimension tables: https://www.youtube.com/watch?v=6k3nwXXpnMY

Fact tables:
Defined by related dimensions
Resolves many to many relations
Does not contain granular information.
Provides Foreign keys to relate to Dimension tables to pull granular information.

Dimension tables:
Table containing actual business elements
Filelds contain element descriptions
Referenced by multiple fact tables


Example: 

3. Snowflake schema: Extension to Star schema - https://en.wikipedia.org/wiki/Snowflake_schema
The snowflake schema is similar to the star schema. However, in the snowflake schema, dimensions are normalized into multiple related tables, whereas the star schema's dimensions are denormalized with each dimension represented by a single table. A complex snowflake shape emerges when the dimensions of a snowflake schema are elaborate, having multiple levels of relationships, and the child tables have multiple parent tables ("forks in the road").

Data Normalization

or simply normalization, is the process of organizing the columns (attributes) and tables (relations) of a relational database to reducedata redundancy and improve data integrity.

Questions:

1. Differences between views and materialized views?

Materialized views are disk based and are updated periodically based upon the query definition.

Views are virtual only and run the query definition each time they are accessed.

A materialized view takes a different approach: the query result is cached as a concrete ("materialized") table (rather than a view as such) that may be updated from the original base tables from time to time. This enables much more efficient access, at the cost of extra storage and of some data being potentially out-of-date. Materialized views find use especially in data warehousing scenarios, where frequent queries of the actual base tables can be expensive.

Friday, July 14, 2017

Redshift Part 3 - Copying and loading Data, Table creation, Determining Dist and sort keys and Troubleshooting

To see tables in the database.


select distinct(tablename) from pg_table_def where schemaname = 'public';


To see all the errors, use the statement,


select query, substring(filename,22,25) as filename,line_number as line,
substring(colname,0,12) as column, type, position as pos, substring(raw_line,0,30) as line_text,
substring(raw_field_value,0,15) as field_text,
substring(err_reason,0,45) as reason
from stl_load_errors
order by query desc
limit 10;

To delete a table use,


drop table dwdate;

or

drop table dwdate cascade;    //cascade keyword will remove this tables relationships with other tables.

To get table schema:


select "column", type, encoding, distkey, sortkey
from pg_table_def where tablename = 'myevent';

Points to remember before copying data from a source:


1. Data source


You can use the COPY command to load data from an Amazon S3 bucket, an Amazon EMR cluster, a remote host using an SSH connection, or an Amazon DynamoDB table. For this tutorial, you will load from data files in an Amazon S3 bucket. When loading from Amazon S3, you must provide the name of the bucket and the location of the data files, by providing either an object path for the data files or the location of a manifest file that explicitly lists each data file and its location.

Key prefix

An object stored in Amazon S3 is uniquely identified by an object key, which includes the bucket name, folder names, if any, and the object name. A key prefix refers to a set of objects with the same prefix. The object path is a key prefix that the COPY command uses to load all objects that share the key prefix. For example, the key prefix custdata.txt can refer to a single file or to a set of files, including custdata.txt.001, custdata.txt.002, and so on.
Manifest file
If you need to load files with different prefixes, for example, from multiple buckets or folders, or if you need to exclude files that share a prefix, you can use a manifest file. A manifest file explicitly lists each load file and its unique object key. You will use a manifest file to load the PART table later in this tutorial.

2. To improve query performance set distkey and sortkeys especially when doing join operations.

3. 'diststyle all' keyword will make the table distributed.

Copying CSV data :

CREATE TABLE part
(
  p_partkey     INTEGER NOT NULL,
  p_name        VARCHAR(22) NOT NULL,
  p_mfgr        VARCHAR(6),
  p_category    VARCHAR(7) NOT NULL,
  p_brand1      VARCHAR(9) NOT NULL,
  p_color       VARCHAR(11) NOT NULL,
  p_type        VARCHAR(25) NOT NULL,
  p_size        INTEGER NOT NULL,
  p_container   VARCHAR(10) NOT NULL
);

copy part from 's3://sample-redshift-data/Sample1/part-csv.tbl'
credentials 'aws_access_key_id=AKIAJR65X2FNTIQPLZVQ;aws_secret_access_key=UACFV4mzBdssys9eJDRdGOSUPO4l6nbMb9fH8/Px'
csv
null as '\000';

Note: when null as '\000' is specified then, The table column that receives the NULL value must be configured as nullable. That is, it must not include the NOT NULL constraint in the CREATE TABLE specification.

Copying data to dwdate table:


copy dwdate from 's3://sample-redshift-data/Sample1/dwdate-tab.tbl'
credentials 'aws_access_key_id=AKIAJR65X2FNTIQPLZVQ;aws_secret_access_key=UACFV4mzBdssys9eJDRdGOSUPO4l6nbMb9fH8/Px'
gzip
delimiter '\t'
dateformat 'auto';
Note: You can specify only one date format. If the load data contains inconsistent formats, possibly in different columns, or if the format is not known at load time, you use DATEFORMAT with the 'auto' argument. When 'auto' is specified, COPY will recognize any valid date or time format and convert it to the default format. The 'auto' option recognizes several formats that are not supported when using a DATEFORMAT and TIMEFORMAT string.

Copying data to customer table:

copy customer from 's3://sample-redshift-data/Sample1/customer-fw-manifest'
credentials 'aws_access_key_id=AKIAJR65X2FNTIQPLZVQ;aws_secret_access_key=UACFV4mzBdssys9eJDRdGOSUPO4l6nbMb9fH8/Px'
fixedwidth 'c_custkey:10, c_name:25, c_address:25, c_city:10, c_nation:15, c_region :12, c_phone:15,c_mktsegment:10'
maxerror 10
acceptinvchars as '^'
manifest;

Note: The ACCEPTINVCHARS option is usually a better choice for managing invalid characters. ACCEPTINVCHARS instructs COPY to replace each invalid character with a specified valid character and continue with the load operation
For this step, you will add the ACCEPTINVCHARS with the replacement character '^'.

Copying data to supplier table.


copy supplier from 's3://awssampledbuswest2/ssbgz/supplier.tbl'
credentials 'aws_access_key_id=AKIAJR65X2FNTIQPLZVQ;aws_secret_access_key=UACFV4mzBdssys9eJDRdGOSUPO4l6nbMb9fH8/Px'
delimiter '|'
gzip
region 'us-west-2';

Note: gzip keyword is used to specify that the data to be loaded in s3 source is compressed in gzip format.

Copying data to lineorder table.


copy lineorder from 's3://awssampledb/load/lo/lineorder-multi.tbl'
credentials 'aws_access_key_id=AKIAJR65X2FNTIQPLZVQ;aws_secret_access_key=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'
gzip
compupdate off
region 'us-east-1';

Note: Compare the time consumed to load data from a single large file and the same file splitted to multiple files.
loading using Multiple files is faster because multiple nodes runs in parallel to load split data.


Video 31 - Best practices to load data


1. Highest throughput can be obtained when loaded data from S3. DynamoDB,EMR comes next.
2. Can use CTAS when copying from internal table. Even this is faster as this makes use of internal cluster resources.
eg: "CREATE TABLE AS" OR "INSERT INTO SELECT"
3. If need to use Insert INTO TABLE values(..), then the best way is to use multi-row inserts. Possibly use batch loading methodology.
4. Redshift links 1 core for 1 slice of the file. Ideal load is 1S3 file per core, however this is an ideal case and is not possible always as ideal slice size is between 1MB-1GB.
   consider, if we have 10 DC1.large nodes of 2 cores each, 10 * 2 cores = 20 cores. vCPU column specifies the number of cores.
   So, 20 slices are ideal for even load distribution.
5. USE the linux command to split a large data file to multiple files "split -[#] N". Eg: "split -500N", this command will split the file into 500 equal sized files.
6. Even amount of data per split enhances speed.
7. If we know the sortkey name in advance, then pre sort it before loading to s3. The will reduce the burden of sorting on Redshift.
8. Recommended to split files in the multiples of 32 like 32,64,96 ...
9. Consider on going loads of daily, weekly data coming in that has to be inserted into a main table that has historical data. In addition, this recent data
needs to be accessed frequently. So, create another table and insert data as per the timestamp. This will allow users to fetch data quickly.
10.There is an overhead in using sortkey option as the data has to be ordered as per the sortkeys. The more the sortkeys the longer the time would be
consumed for copying the data.
11. Use Vaccum when copy command was not used. need to use when large set of data operation was performed post INSERT, UPDATE and DELETE.
12. Work load manager can be used to setup priorities on queries. wlm_query_slot_count controls memory allocation and maximum upto 50 resources can be configured
for a single query. Default is 5.

eg: if bydefault the memory allocation is 50% each for 2 queries, and 1 query priority can be increased to 75% and the 2nd query will get 25%.
this can be brought back to default after the completion of 1st query execution.

This can speedup COPY & VACCUM operations.


Few points for table creation:


1. By default Redshift does compression for each column and stores the data. Compression not applied for the columns specified in 'sortkey'.
   default compression is lzo.
 
Eg:   Create table:
 
   create table customer2 (
  c_custkey     integer        not null,
  c_name         varchar(25)    not null,
  c_address     varchar(25)    not null,
  c_city         varchar(10)    not null,
  c_nation       varchar(15)    not null)
compound sortkey (c_custkey, c_city);

Get table schema:

select "column", type, encoding, distkey, sortkey
from pg_table_def where tablename = 'customer2';

column type encoding distkey  sortkey
-----------------------------------------------------------------
c_custkey integer none false 1
c_name character varying(25) lzo false 0
c_address character varying(25) lzo false 0
c_city character varying(10) none false 2
c_nation character varying(15) lzo false 0

2. A Foreign Key is a column or a combination of columns whose values match a Primary Key in a different table.

The relationship between 2 tables matches the Primary Key in one of the tables with a Foreign Key in the second table.

references is the keyword that links Primary key and Foriegn key.

Eg:
CUSTOMERS table

CREATE TABLE CUSTOMERS(
   ID   INT              NOT NULL,
   NAME VARCHAR (20)     NOT NULL,
   AGE  INT              NOT NULL,
   ADDRESS  CHAR (25) ,
   SALARY   DECIMAL (18, 2),    
   PRIMARY KEY (ID)
);
ORDERS table

CREATE TABLE ORDERS (
   ID          INT        NOT NULL,
   DATE        DATETIME,
   CUSTOMER_ID INT references CUSTOMERS(ID),
   AMOUNT     integer,
   PRIMARY KEY (ID)
);

3. 2 types of sorting is available Compound and Interleaved.

COMPOUND
Specifies that the data is sorted using a compound key made up of all of the listed columns, in the order they are listed. A compound sort key is most useful when a query scans rows according to the order of the sort columns. The performance benefits of sorting with a compound key decrease when queries rely on secondary sort columns. You can define a maximum of 400 COMPOUND SORTKEY columns per table.

INTERLEAVED
Specifies that the data is sorted using an interleaved sort key. A maximum of eight columns can be specified for an interleaved sort key.

An interleaved sort gives equal weight to each column, or subset of columns, in the sort key, so queries do not depend on the order of the columns in the sort key. When a query uses one or more secondary sort columns, interleaved sorting significantly improves query performance. Interleaved sorting carries a small overhead cost for data loading and vacuuming operations.

Data distribution is of 3 types, Even (bydefault), Key and All

Eg: This example shows Interleaved and All distribution.

create table customer_interleaved (
  c_custkey     integer        not null,
  c_name         varchar(25)    not null,
  c_address     varchar(25)    not null,
  c_city         varchar(10)    not null,
  c_nation       varchar(15)    not null,
  c_region       varchar(12)    not null,
  c_phone       varchar(15)    not null,
  c_mktsegment      varchar(10)    not null)
diststyle all
interleaved sortkey (c_custkey, c_city, c_mktsegment);

Eg: Even Distribution

create table myevent(
eventid int,
eventname varchar(200),
eventcity varchar(30));

Eg: Key distribution

create table t1(col1 int distkey, col2 int) diststyle key;

4. Create a Table with an IDENTITY Column

The following example creates a table named VENUE_IDENT, which has an IDENTITY column named VENUEID. This column starts with 0 and increments by 1 for each record. VENUEID is also declared as the primary key of the table.

create table venue_ident(venueid bigint identity(0, 1),
venuename varchar(100),
venuecity varchar(30),
venuestate char(2),
venueseats integer,
primary key(venueid));

5. Create a Table with DEFAULT Column Values

The following example creates a CATEGORYDEF table that declares default values for each column:

create table categorydef(
catid smallint not null default 0,
catgroup varchar(10) default 'Special',
catname varchar(10) default 'Other',
catdesc varchar(50) default 'Special events',
primary key(catid));

insert into categorydef values(default,default,default,default);

select * from categorydef;

catid | catgroup | catname |    catdesc
-------+----------+---------+----------------
0 | Special  | Other   | Special events

References:

http://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html
http://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_examples.html



POC on AWS:

1. Created EMR cluster with ec2 instances. Also created S3 buckets and Redshift cluster. 2. Access ids and Security keys would also be generated for each type of instance. 3. Copied CSV data to an S3 location. 4. Hive tables are created on this S3 location. 5. Few Transformations are applied and inserted data to partitioned table. 6. copied the data from this S3 location to Redshift tables using copy command, S3 location and access id and security key. 7. On S3 hive tables can be created only on EMR, but not in Cloudera/Hortonworks

Wednesday, July 12, 2017

Redshift part2

To see tables in the database.

select distinct(tablename) from pg_table_def where schemaname = 'public';

To see all the errors, use the statement,

select query, substring(filename,22,25) as filename,line_number as line,
substring(colname,0,12) as column, type, position as pos, substring(raw_line,0,30) as line_text,
substring(raw_field_value,0,15) as field_text,
substring(err_reason,0,45) as reason
from stl_load_errors
order by query desc
limit 10;

To delete a table use,

drop table dwdate;

or

drop table dwdate cascade;    //cascade keyword will remove this tables relationships with other tables.

Points to remember before copying data from a source:

1. Data source

You can use the COPY command to load data from an Amazon S3 bucket, an Amazon EMR cluster, a remote host using an SSH connection, or an Amazon DynamoDB table. For this tutorial, you will load from data files in an Amazon S3 bucket. When loading from Amazon S3, you must provide the name of the bucket and the location of the data files, by providing either an object path for the data files or the location of a manifest file that explicitly lists each data file and its location.

Key prefix
An object stored in Amazon S3 is uniquely identified by an object key, which includes the bucket name, folder names, if any, and the object name. A key prefix refers to a set of objects with the same prefix. The object path is a key prefix that the COPY command uses to load all objects that share the key prefix. For example, the key prefix custdata.txt can refer to a single file or to a set of files, including custdata.txt.001, custdata.txt.002, and so on.
Manifest file
If you need to load files with different prefixes, for example, from multiple buckets or folders, or if you need to exclude files that share a prefix, you can use a manifest file. A manifest file explicitly lists each load file and its unique object key. You will use a manifest file to load the PART table later in this tutorial.

2. To improve query performance set distkey and sortkeys especially when doing join operations.

3. 'diststyle all' keyword will make the table distributed.

Copying CSV data :

copy part from 's3://sample-redshift-data/Sample1/part-csv.tbl'
credentials 'aws_access_key_id=AKIAJR65X2FNTIQPLZVQ;aws_secret_access_key=UACFV4mzBdssys9eJDRdGOSUPO4l6nbMb9fH8/Px'
csv
null as '\000';

Note: when null as '\000' is specified then, The table column that receives the NULL value must be configured as nullable. That is, it must not include the NOT NULL constraint in the CREATE TABLE specification.

Copying data to dwdate table:

copy dwdate from 's3://sample-redshift-data/Sample1/dwdate-tab.tbl'
credentials 'aws_access_key_id=AKIAJR65X2FNTIQPLZVQ;aws_secret_access_key=UACFV4mzBdssys9eJDRdGOSUPO4l6nbMb9fH8/Px'
gzip
delimiter '\t'
dateformat 'auto';
Note: You can specify only one date format. If the load data contains inconsistent formats, possibly in different columns, or if the format is not known at load time, you use DATEFORMAT with the 'auto' argument. When 'auto' is specified, COPY will recognize any valid date or time format and convert it to the default format. The 'auto' option recognizes several formats that are not supported when using a DATEFORMAT and TIMEFORMAT string.

Copying data to customer table:

copy customer from 's3://sample-redshift-data/Sample1/customer-fw-manifest'
credentials 'aws_access_key_id=AKIAJR65X2FNTIQPLZVQ;aws_secret_access_key=UACFV4mzBdssys9eJDRdGOSUPO4l6nbMb9fH8/Px'
fixedwidth 'c_custkey:10, c_name:25, c_address:25, c_city:10, c_nation:15, c_region :12, c_phone:15,c_mktsegment:10'
maxerror 10
acceptinvchars as '^'
manifest;

Note: The ACCEPTINVCHARS option is usually a better choice for managing invalid characters. ACCEPTINVCHARS instructs COPY to replace each invalid character with a specified valid character and continue with the load operation
For this step, you will add the ACCEPTINVCHARS with the replacement character '^'.

Copying data to supplier table.

copy supplier from 's3://awssampledbuswest2/ssbgz/supplier.tbl'
credentials 'aws_access_key_id=AKIAJR65X2FNTIQPLZVQ;aws_secret_access_key=UACFV4mzBdssys9eJDRdGOSUPO4l6nbMb9fH8/Px'
delimiter '|'
gzip
region 'us-west-2';

Note: gzip keyword is used to specify that the data to be loaded in s3 source is compressed in gzip format.

Copying data to lineorder table.

copy lineorder from 's3://awssampledb/load/lo/lineorder-multi.tbl'
credentials 'aws_access_key_id=AKIAJR65X2FNTIQPLZVQ;aws_secret_access_key=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'
gzip
compupdate off
region 'us-east-1';

Note: Compare the time consumed to load data from a single large file and the same file splitted to multiple files.
loading using Multiple files is faster because multiple nodes runs in parallel to load split data.


Video 31 - Best practices to load data

1. Highest throughput can be obtained when loaded data from S3. DynamoDB,EMR comes next.
2. Can use CTAS when copying from internal table. Even this is faster as this makes use of internal cluster resources.
eg: "CREATE TABLE AS" OR "INSERT INTO SELECT"
3. If need to use Insert INTO TABLE values(..), then the best way is to use multi-row inserts. Possibly use batch loading methodology.
4. Redshift links 1 core for 1 slice of the file. Ideal load is 1S3 file per core, however this is an ideal case and is not possible always as ideal slice size is between 1MB-1GB.
   consider, if we have 10 DC1.large nodes of 2 cores each, 10 * 2 cores = 20 cores. vCPU column specifies the number of cores.
   So, 20 slices are ideal for even load distribution.
5. USE the linux command to split a large data file to multiple files "split -[#] N". Eg: "split -500N", this command will split the file into 500 equal sized files.
6.



Tuesday, July 11, 2017

RedShift Part1

Architecture:


Leader Node and compute nodes.

Compute nodes are same as data nodes in hadoop where data is saved.

Data is stored in compute nodes in the form of slices

Video 18: Data loading

Services are:
AWS Datapipeline
RDS SYNC


Video 19: Data distribution concepts


Even distribution
Key Distribution
All Distribution type - Similar as distributed cache in hadoop. The data would be copied to every compute node and will be used by all the slices.
Ideally the All distribution table should be heavily used and small, Relatively static(not frequently changed) and frequently joined.

Video 20 & 21: Redshift Basic usage


Exps:
sum(list),sum(colname)
operators:
"+","*","&","XOR","||" (Same as concat)
eg: fname || " " lastname || ":" avg(scores)

Syntax is almost same as SQL, however with minor changes.

create tble1(o_id integer not null,o_time timestamp not null, store_id integer,
product varchar not null    //No arrays
primary key(o_id))
distkey(store_id),    //This does Key distribution based on store_id
compound sortkey(store_id,o_id);    //sorts as per store_id and then o_id.

insert into tble1 values(1234,1435261730,885,"jkhg");

insert into tble1 values(1234,1435261730,885,"jkhg"),(1235,1435261730,888,"k;sg");   //Multiple insert values

copying data from other sources:

copy [table_name] from '[emr|dynamodb|s3://path/to/asset]' credentials

can load JSON,CSV,

Video 23: Creating a Redshift cluster


 A4 node cluser would cost $1/hour. After creation if turned off and on for 3 times in an hour then the charge would be $3. Need to use atleast for an hour after turning on.

Creating cluster.

Followed free trail path.

user: admin
password: Leelaadmin1

User name Password Access key ID Secret access key Console login link
------------------------------------------------------------------------------------------------------------------------------------
vish-admin }[!J6dh[My-d AKIAITSNVUXG3ZX3DN3A doU9Y/RSrL7EFoh7RP0LvQPPYWave8/o0Pvf4Qra https://303343717363.signin.aws.amazon.com/console
leela2-user NdtwdD$!aYe] AKIAJJXKTMBPEHGQQUTQ WXEEoxC4gAfIQcKswXFP/ShHkP/EmKbubTHBrVBJ https://303343717363.signin.aws.amazon.com/console
leela-admin O8+ipsq{UONX AKIAJR65X2FNTIQPLZVQ UACFV4mzBdssys9eJDRdGOSUPO4l6nbMb9fH8/Px https://303343717363.signin.aws.amazon.com/console


Launch Cluster

Step 2: Open a new link for VPC _ Security group

Step 3: Create users.

Open a new Amazon console link -> Identity & Access Management

Create users -> Policies -> attach policies

Step 4: Connecting using SQL work bench

In Redshift page -> connect client -> download JDBC jar file. (http://docs.aws.amazon.com/redshift/latest/mgmt/configure-jdbc-connection.html#download-jdbc-driver)

Install SQL Workbench -> load the downloaded JAR file for connecting to redshift cluster.

connect with cluster user id and password which are:
user: admin
password: Leelaadmin1

Below link has some common commands for working on this.
https://drive.google.com/file/d/0BzG0wQkWbKpLVVllLXJUTTcyT2s/view?usp=sharing

Amazon documentation is under, http://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-run-copy.html


Friday, July 7, 2017

Apache Nifi


Apache NIFI is a data flow tool

In case of any warning take the cursor on top of the exclamation mark and this shows the error.

1. GetFile - Gets the file from the local file system and puts in the flow

Specify Input Directory

2. PutFile - Writes data to Local file system

Specify Directory

3. SplitText - Splits the data as per lines specified/data size specified

Specify Line Split Count/ Maximum Fragment Size

4. Extract Text - Extracts values from the text as per the RegEx

give any variable and specify RegEx. values would be variable.1,variable.2 etc

eg: fieldval - (.+),(.+),(.+),(.+)

then each values are fieldval.1,fieldval.2,fieldval.3,fieldval.4

5. PutHDFS - Writes data to HDFS

Specify Hadoop Configuration Resources paths of hdfs-site.xml and core-site.xml
Directory output HDFS Directory location

Note: Make sure that full permissions are applied to HDFS O/P path
Eg:  hadoop fs -chmod -R 777 /user/hadoop/Leela/Nifi1_out

References:

https://www.youtube.com/watch?v=4yBc7hHvaQU

Thursday, July 6, 2017

Linux Commands

Nano Text Editor

To create a new file
nano 1.txt

Enter the desired text and press ctrl+x -> Press Y for save changes -> option to change file name and Press Enter.

vi editor

To create a new file use,
touch <FILENAME>

vi test

ESC and press I and now Enter/Modify the text. ->To save press ESC ->:wq!

To find files in Linux

locate "*.png"

sudo locate "*.xml" > 1.txt  //to write the results to a file

To delete a Directory and files inside it in Linux


sudo rm -rf cdh5-repository_1.0_all.deb

to remove a file

rm <FILENAME>



To rename a Directory

mv /home/user/oldname /home/user/newname

To get host name


hostname -f

Command to check memory usage on linux

free -m

To give permissions to a Directory

chmod 777 Leela/


Merge 2 files in local
cat quicktechie.txt hadoopexam.txt > MergedEmployee.txt

Adds a newline character at the end

echo "" >> file.txt  

To Download a file

wget http://www-eu.apache.org/dist/nifi/1.3.0/nifi-toolkit-1.3.0-bin.tar.gz /home/hadoop_1/Leela/Nifi


To Extract the downloaded file

tar -xzvf nifi-toolkit-1.3.0-bin.tar.gz


To know the memory usage in the machine

free -m


To Free up cached memory

sudo sysctl -w vm.drop_caches=3


File permissions in Linux

Basically there will be 3 sets of users Owner,Group and Others.

read - 4
write - 2
execute - 1

ls -ltr will display the access rights for the 3 sets of users.

eg: -rw-rw-r-- 1 cloudera cloudera 20136 Sep 10 23:41 derby.log

rw to Owner, rw to Group and r to others

sudo chmod 754 <filename>  

The above command will grant RWX to Owner, RW to Group and R to Others.

sudo chmod -R 754 Leela_files 

//-R will recursively grant the permissions to all the files in the directory

Few Linux commands:

set nu

yum erase logstash

yum clean all

VIM find

/ and type the word to search and press enter. subsequently press n.

ps -ef | grep processname

ps - list processes
-e - show all processes, not just those belonging to the user
-f - show processes in full format (more detailed than default)
command 1 | command 2 - pass output of command 1 as input to command 2
grep find lines containing a pattern
processname - the pattern for grep to search for in the output of ps -ef
So altogether

ps -ef | grep processname

eg: ps -ef | grep logstash

initctl start logstash

tail -50f logstash-plain.log

service elasticsearch start


yum install kibana-5.5.2-x86_64.rpm


To Find specific text in files in a directory(find in files Notepad++)

Searches for 'sqltext' in all the .hql files in /opt directory.
find / -type f | xargs grep 'text-to-find-here'
Eg:
find /opt/ -name "*.hql" | xargs grep -i sqltext

Searches for sqltext in all*.hql files under /opt/hal/installers/hal-batch-jobs/scripts

grep sqltext /opt/hal/installers/hal-batch-jobs/scripts/*.hql

To find a specific file under a primary directory

Below command will search recursively for file with name 'stderr' under directory whose name starts with /data like /data01, /data02,data03 etc.
find /data* -name "stderr"

grep History commands

history | grep "yarn*"


Get the status of the services

service --status-all


Set Proxy in the Linux machine.

Need to set Proxy server name in the below 4 files, this would set the Proxy server and the RPMs would be downloaded via this Proxy. This is useful in cases where the cluster is secured from internet connection and packages for installation are allowed only via Proxy server.


/etc/yum.conf

/etc/environment

/etc/profile.d

/etc/proxy.sh

Get the list of files and their details in the directory

ls -ltr

Get the list of Running processes

ps -A
Search with a specific name tomcat
ps -A | grep tomcat

Kill a running Process


Get pid of the process to be killed using above command. If the process id is 3184, then


kill -9 3184

     
        OR
kill -SIGKILL 3184

Kill with Process name.



pkill mysql


Diff between 2 files in Linux

diff <file1> <file2>

Get CPU Information

lscpu

RAM Info

cat /proc/meminfo

Hard Disk Info

df -h

SCP command to copy a Folder. 

The below command will copy all the contents in directory /home/umar/kafkaconsumer/ on remote machine with host name "xvzw160" to local filesystem "/home/gorrepat".
sudo scp -r gorrepat@xvzw160:/home/umar/kafkaconsumer/ /home/gorrepat

In case of file -r is not required.

cp command for copying folder,

cp -r kafkaconsumer/ kafkaconsumer_bk

To know the list of processes running by a particular user 'hadoop'
ps -ef | grep hadoop

The top command allows users to monitor processes and system resource usage on Linux
top

list all processes and their status and resource usage 
ps aux

filters hive named directories with ls -lrt

ls -lrt | grep hive


To get List of running Processes:
ps -aef

To Kill a process
kill -9 31767

To search running processes based on a name:
ps -aef|grep rdbms_extract|awk -F" " '{print $2}'

To save the PIDs of running processes based on  name(here pids with spark-shell are filtered)
ps -aef|grep spark-shell|awk -F" " '{print $2}' > myProcess.pid

To kill multiple PIDs those are running
ps -aef| grep spark-shell|awk -F" " '{print $2}'|xargs kill -9

Some shell script commands:

Get current dir path of the shell script from which it is triggeted
FILE_PATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 
echo "FILE_PATH path is" $FILE_PATH

Run query in a HQL file in beeline from shell script
beeline --silent=true --showHeader=false --outputformat=csv2 -u "$(beelineConnection}" -f ${Hive QueryHQLFile} 

Pass arguments to HQL file along with the above Hive query in a file
beeline --silent=true --showHeader=false --outputformat=csv2 -u "$(beelineConnection}" -f ${Hive QueryHQLFile} --hivevar hivedbname="rawDB" --hivevar hivestagedb="processedDB"

Inside the HQL file ${hivedbname} and ${hivestagedb} can be used and these will have the values passed.