Shantanu's Blog

Corporate Consultant

February 19, 2020

 

Manage athena tables using python


Here is 4 or 5 lines of code to read data from athena table into pandas dataframe.

from pyathena import connect
from pyathena.util import to_sql

bucket = ‘my_bucket_name’

conn = connect(
    aws_access_key_id=access,
    aws_secret_access_key=secret,
    s3_staging_dir="s3://" + bucket + "/tutorial/staging/",
    region_name="us-east-1",
)

ndf = pd.read_sql("SELECT * FROM sampledb.todel limit 100", conn)

# pandas dataframe to Athena table

to_sql(ndf, "sample_table", conn, "s3://" + bucket + "/tutorial/s3dir/",
    schema="sampledb", index=False, if_exists="replace")

Labels: , , ,


 

connect to redshift and import data into pandas

There are 2 ways to connect to redshift server and get the data into pandas dataframe. Use the module "sqlalchemy" or "psycopg2". As you can see, sqlalchemy is using psycopg2 module internally.

from sqlalchemy import create_engine

pg_engine = create_engine(
    "postgresql+psycopg2://%s:%s@%s:%i/%s" % (myuser, mypasswd, myserver, int(myport), mydbname)
)

my_query = "select * from some_table limit 100”
df = pd.read_sql(my_query, con=pg_engine)

since "create_engine" class can also be used to connect to mysql database, it is recommended for the sake of consistency.
_____

#!pip install psycopg2-binary
import psycopg2
pconn = psycopg2.connect("host=myserver port=myport  dbname=mydbname user=myuser password=mypasswd")
my_query = "select * from some_table limit 100”

cur = pconn.cursor()           
cur.execute(my_query)
mydict = cur.fetchall()
import pandas as pd
df = pd.DataFrame(mydict)

Labels: , , ,


 

Import csv data and convert it to parquet in athena

# Let's assume we have a large file that we need to import in athena, here are the commands to be used.

# gunzip -c panindia_pincode.csv.gz | head
"1","110016","DELHI","DELHI","","","",""
"2","110027","DELHI","DELHI","","","",""
"3","110062","DELHI","DELHI","","","",""


# create a table in athena

CREATE EXTERNAL TABLE pandindia_pincode (
  serial_number string,
  pincode_number string,
  client_city string,
  client_state string,
  dummy1 string,
  dummy2 string,
  dummy3 string,
  dummy4 string)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES (
  'serialization.format' = ',',
  'field.delim' = ',',
   "quoteChar"     = "\""
)
LOCATION 's3://datameetgeo/pincode/'
TBLPROPERTIES ('has_encrypted_data'='false');

## create parquet file format table

CREATE TABLE default.pandindia_pincode_parq
with (format='PARQUET', external_location='s3://datameetgeo/parquetpincode/'
) AS
SELECT * FROM default.pandindia_pincode

Labels: , ,


February 16, 2020

 

Using Python in Redshift


Here is a python function that can be installed in Redshift. It will normalize the text by removing junk characters and non-essential strings.

CREATE OR REPLACE FUNCTION f_file_split (mystr varchar(1000) ) RETURNS varchar(1000) IMMUTABLE as $$ 
    try:
        import itertools
        mylist=list()
        if mystr:
            for i in mystr[:100].split("_"):
                for x in i.split("-"):
                    for y in x.split("/"):
                        mylist.append(y.split("."))

        news = ' '.join(itertools.chain(*mylist))
        newlist=list()
        stopwords = ['sanstha', 'vikas', 'society', 'seva', 'json']
        for i in news.split():
            if len(i) < 4 or i in stopwords or i.isdigit() or i.startswith('bnk') or not i.isalpha() :
                pass
            else:
                newlist.append(i.lower().replace('vkss', '').replace('vks',''))
        return ' '.join(set(newlist))

    except:
        pass

$$ LANGUAGE plpythonu

I can add a new column in the table and populate that column with transformed values.

alter table final_details add column branch_name_fuzzy varchar(500);

update final_details set branch_name_fuzzy = f_file_split(filename);

Labels: , ,


 

Using partitions in Athena table

Here is a create table query that will create a partitioned table. The column "product_category" that is used for partitions, is not part of create table statement and still shows up in the select query.

CREATE EXTERNAL TABLE `reviews`(
  `marketplace` varchar(10),
  `customer_id` varchar(15),
  `review_id` varchar(15),
  `product_id` varchar(25),
  `product_parent` varchar(15),
  `product_title` varchar(50),
  `star_rating` int,
  `helpful_votes` int,
  `total_votes` int,
  `vine` varchar(5),
  `verified_purchase` varchar(5),
  `review_headline` varchar(25),
  `review_body` varchar(1024),
  `review_date` date,
  `year` int)
PARTITIONED BY (
  `product_category` varchar(25))
ROW FORMAT SERDE
  'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe'
STORED AS INPUTFORMAT
  'org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat'
LOCATION
  's3://amazon-reviews-pds/parquet'

In order to populate the table, we will need to use the alter table statement.
 
ALTER TABLE  reviews ADD
partition(product_category='Apparel')
location 's3://amazon-reviews-pds/parquet/product_category=Apparel/'
partition(product_category='Automotive')
location 's3://amazon-reviews-pds/parquet/product_category=Automotive'
partition(product_category='Baby')
location 's3://amazon-reviews-pds/parquet/product_category=Baby'
partition(product_category='Beauty')
location 's3://amazon-reviews-pds/parquet/product_category=Beauty'
partition(product_category='Books')
location 's3://amazon-reviews-pds/parquet/product_category=Books'
partition(product_category='Camera')
location 's3://amazon-reviews-pds/parquet/product_category=Camera'
partition(product_category='Grocery')
location 's3://amazon-reviews-pds/parquet/product_category=Grocery'
partition(product_category='Furniture')
location 's3://amazon-reviews-pds/parquet/product_category=Furniture'
partition(product_category='Watches')
location 's3://amazon-reviews-pds/parquet/product_category=Watches'
partition(product_category='Lawn_and_Garden')
location 's3://amazon-reviews-pds/parquet/product_category=Lawn_and_Garden';

Around 1 TB data per category is already saved in the given S3 bucket in parquet format.

# aws s3 ls --human s3://amazon-reviews-pds/parquet/product_category=Apparel/
2018-04-09 06:35:35  115.0 MiB part-00000-495c48e6-96d6-4650-aa65-3c36a3516ddd.c000.snappy.parquet
2018-04-09 06:35:35  115.3 MiB part-00001-495c48e6-96d6-4650-aa65-3c36a3516ddd.c000.snappy.parquet
2018-04-09 06:35:36  114.9 MiB part-00002-495c48e6-96d6-4650-aa65-3c36a3516ddd.c000.snappy.parquet
2018-04-09 06:35:35  115.2 MiB part-00003-495c48e6-96d6-4650-aa65-3c36a3516ddd.c000.snappy.parquet
2018-04-09 06:35:35  115.3 MiB part-00004-495c48e6-96d6-4650-aa65-3c36a3516ddd.c000.snappy.parquet
2018-04-09 06:35:39  115.3 MiB part-00005-495c48e6-96d6-4650-aa65-3c36a3516ddd.c000.snappy.parquet
2018-04-09 06:35:39  115.4 MiB part-00006-495c48e6-96d6-4650-aa65-3c36a3516ddd.c000.snappy.parquet
2018-04-09 06:35:39  114.8 MiB part-00007-495c48e6-96d6-4650-aa65-3c36a3516ddd.c000.snappy.parquet
2018-04-09 06:35:39  115.3 MiB part-00008-495c48e6-96d6-4650-aa65-3c36a3516ddd.c000.snappy.parquet
2018-04-09 06:35:40  115.3 MiB part-00009-495c48e6-96d6-4650-aa65-3c36a3516ddd.c000.snappy.parquet

If you are planning to use csv instead of parquet, then you will have to change the serialization, input / output formats in the create table statement.

Labels: ,


Archives

June 2001   July 2001   January 2003   May 2003   September 2003   October 2003   December 2003   January 2004   February 2004   March 2004   April 2004   May 2004   June 2004   July 2004   August 2004   September 2004   October 2004   November 2004   December 2004   January 2005   February 2005   March 2005   April 2005   May 2005   June 2005   July 2005   August 2005   September 2005   October 2005   November 2005   December 2005   January 2006   February 2006   March 2006   April 2006   May 2006   June 2006   July 2006   August 2006   September 2006   October 2006   November 2006   December 2006   January 2007   February 2007   March 2007   April 2007   June 2007   July 2007   August 2007   September 2007   October 2007   November 2007   December 2007   January 2008   February 2008   March 2008   April 2008   July 2008   August 2008   September 2008   October 2008   November 2008   December 2008   January 2009   February 2009   March 2009   April 2009   May 2009   June 2009   July 2009   August 2009   September 2009   October 2009   November 2009   December 2009   January 2010   February 2010   March 2010   April 2010   May 2010   June 2010   July 2010   August 2010   September 2010   October 2010   November 2010   December 2010   January 2011   February 2011   March 2011   April 2011   May 2011   June 2011   July 2011   August 2011   September 2011   October 2011   November 2011   December 2011   January 2012   February 2012   March 2012   April 2012   May 2012   June 2012   July 2012   August 2012   October 2012   November 2012   December 2012   January 2013   February 2013   March 2013   April 2013   May 2013   June 2013   July 2013   September 2013   October 2013   January 2014   March 2014   April 2014   May 2014   July 2014   August 2014   September 2014   October 2014   November 2014   December 2014   January 2015   February 2015   March 2015   April 2015   May 2015   June 2015   July 2015   August 2015   September 2015   January 2016   February 2016   March 2016   April 2016   May 2016   June 2016   July 2016   August 2016   September 2016   October 2016   November 2016   December 2016   January 2017   February 2017   April 2017   May 2017   June 2017   July 2017   August 2017   September 2017   October 2017   November 2017   December 2017   February 2018   March 2018   April 2018   May 2018   June 2018   July 2018   August 2018   September 2018   October 2018   November 2018   December 2018   January 2019   February 2019   March 2019   April 2019   May 2019   July 2019   August 2019   September 2019   October 2019   November 2019   December 2019   January 2020   February 2020  

This page is powered by Blogger. Isn't yours?