Shantanu's Blog

Database Consultant

October 28, 2020

 

Using Lambda Functions as UDF's in Redshift

Let's assume I have a list of client_codes saved in a redshift table and I need to find the details from an API.

# select client_code from some_table limit 10;
  client_code   |
--------------+
 1001 |  
 2002 |  
 9009 |  
 1009 |  
 1898 |  
 5465 |  
 3244 |  
 5576 |  
 4389 |  
 8756 |  
(10 rows)

I need to get the client addresses from a website. For e.g. the first client code is 1001 and address should come from
http://some_site.com/Details?dest=1001

This can not be done at SQL query level. You need to loop through an array using Python, PHP, Java etc. You can also write your scripts in AWS Lambda and use them as UDF (User Defined Functions) in Redshift. For e.g.

# select client_code, client_details(client_code) as c_address from some_table limit 10;
  client_code   |                  c_address
--------------+---------------------------------------------
 1001 | 21,Tamilnadu,
 2002 | 14,Madhya Pradesh & Chattisgarh,
 9009 | 7,Gujarat,
 1009 | 23,Uttar Pradesh (W) & Uttarakhand
 1898 | 11,Karnataka
 5465 | 3,Bihar & Jharkhand
 3244 | 11,Karnataka
 5576 | 6,Delhi
 4389 | 13,Kolkata
 8756 | 11,Karnataka
(10 rows)

The code of "client_details" Lambda function will look something like this...

import json
import requests
myurl = 'http://some_site.com/Details?dest='

def lambda_handler(event, context):
  ret = dict()
  res = list()
  for argument in event['arguments']:
      try:
        number = str(argument[0])
        page = requests.get(myurl+number[-10:])
        res.append((page.content).decode('utf-8'))
        ret['success'] = True
      except Exception as e:
        res.append(None)
        ret['success'] = False
        ret['error_msg'] = str(e)
      ret['results'] = res
  return json.dumps(ret)

Notes:
1) We are using "requests" module in this code. Since it is not available in AWS Lambda environment, I have added it using this layer...
# Layer: arn:aws:lambda:us-east-1:770693421928:layer:Klayers-python38-requests:9

2) You will also need to increase the timeout of Lambda upto 15 minutes. The API may take more than 3 seconds (default) to respond.

3) You will also have to update the IAM role associated with your Redshift cluster. (Actions - Manage Role) You can add the policy called "AWSLambdaFullAccess" or grant access to a single function as explained in the documentation.

The lambda function needs to be "linked" to Redshift using the "create function" statement like this...

CREATE OR REPLACE EXTERNAL FUNCTION client_details (number varchar )
RETURNS varchar STABLE
LAMBDA 'client_details'
IAM_ROLE 'arn:aws:iam::123456789012:role/RedshiftCopyUnload';

You need to change the IAM role name and the 12 digit account ID mentioned above in the IAM Role. 

You can now use your lambda function in your redshift query for e.g.

# select client_code, client_details(client_code) as c_address from some_table limit 10;

You can read more...

# https://aws.amazon.com/blogs/big-data/accessing-external-components-using-amazon-redshift-lambda-udfs/

Labels: , ,


October 26, 2020

 

Mappings in Cloudformation Template

The optional Mappings section of cloudformation template can be used to declare variables. It is like python dictionary. You use the "FindInMap" intrinsic function to retrieve values. For e.g.

Mappings:
  Function:
    SocialMediaMLFunction:
      S3Bucket: solutions
      S3Key: ai-driven-social-media-dashboard/v1.0.0/socialmediafunction.zip
    AddTriggerForFunction:
      S3Bucket: solutions
      S3Key: ai-driven-social-media-dashboard/v1.0.0/addtriggerfunction.zip
  Code:
    EC2Twitter:
      S3Bucket: solutions
      S3Key: ai-driven-social-media-dashboard/v1.0.0/ec2_twitter_reader.tar


If you want to refer to socialmediafunction.zip file along with it's path, then use...

S3Key: !FindInMap [ Function, SocialMediaMLFunction, S3Key]

And this statement will generate the URL that can be used to download the file...

EC2TwitterCode: !Join ['', ['https://s3.', !Ref 'AWS::Region', '.amazonaws.com/', !Join ['-', [!FindInMap [ Code, EC2Twitter, S3Bucket], !Ref 'AWS::Region']], '/', !FindInMap [ Code, EC2Twitter, S3Key]]]
 
The output will look something like this...

https://s3.us-east-1.amazonaws.com/solutions-us-east-1/ai-driven-social-media-dashboard/v1.0.0/ec2_twitter_reader.tar
_____

Here is another example:

Value: !FindInMap [RegionAndInstanceTypeToAMIID, !Ref "AWS::Region", !Ref EnvironmentType]

If your current region is us-east-1 and if the user has selected "test" environment as a parameter while creating the template, then the value returned will be "ami-8ff710e2" from this mapping:

 Mappings:
    RegionAndInstanceTypeToAMIID:
      us-east-1:
        test: "ami-8ff710e2"
        prod: "ami-f5f41398"
      us-west-2:
        test: "ami-eff1028f"
        prod: "ami-d0f506b0"

Labels:


October 24, 2020

 

Using Bucketing in Amazon Athena

To reduce the data scan cost, AWS Athena provides an option to bucket your data. This optimization technique can perform wonders on reducing cost.

Like partitioning, columns that are frequently used to filter the data are good candidates for bucketing. However, unlike partitioning, with bucketing it’s better to use columns with high cardinality as a bucketing key. For example, Year and Month columns are good candidates for partition keys, whereas userID and sensorID are good examples of bucket keys. By doing this, you make sure that all buckets have a similar number of rows.

Bucketing is a technique that groups data based on specific columns together within a single partition. These columns are known as bucket keys. By grouping related data together into a single bucket (a file within a partition), you significantly reduce the amount of data scanned by Athena, thus improving query performance and reducing cost.

For example, imagine collecting and storing clickstream data. If you frequently filter or aggregate by Sensor ID, then within a single partition it’s better to store all rows for the same sensor together.

CREATE TABLE TargetTable
WITH (
      format = 'PARQUET',
      external_location = 's3://<s3_bucket_name>/curated/',
      partitioned_by = ARRAY['dt'],
      bucketed_by = ARRAY['sensorID'],
      bucket_count = 3)
AS SELECT *
FROM SourceTable

You can run the select query like this:

select * from TargetTable where dt= '2020-08-04-21' and sensorID = '1096'

Labels: ,


September 18, 2020

 

Speech to text using assembly AI

Run this python code to submit the mp3 file from S3. You will have to register first to get the authorization API key.

https://app.assemblyai.com/login/

import requests
headers = {
    "authorization": "XXX",
    "content-type": "application/json"
}

endpoint = "https://api.assemblyai.com/v2/transcript"
json = {
  "audio_url": "https://s3-us-west-2.amazonaws.com/blog.assemblyai.com/audio/8-7-2018-post/7510.mp3"
}
response = requests.post(endpoint, json=json, headers=headers)
print(response.json())

You will get id and status like this...

'id': 'g9j4q46h9-5d04-4f96-8186-b4def1b1b65b', 'status': 'queued',

Use the id to query the results.

endpoint = "https://api.assemblyai.com/v2/transcript/g9j4q46h9-5d04-4f96-8186-b4def1b1b65b"
response = requests.get(endpoint, headers=headers)
print(response.json())

And you will get the text of audio file. It will look something like this...

'text': 'You know, Demons on TV like that. And and for people to expose themselves to being rejected on TV or you know, her M humiliated by fear factor or you know.'

Labels: ,


 

Remove junk from pandas dataframe

Non-latin unicode characters in pandas dataframe are a big problem. Several hours are lost cleaning the data when some obscure characters are found in the dataframe imported from the csv or excel file. Here is an easy solution...

from unicodedata import normalize
def clean_normalize_whitespace(x):
    if isinstance(x, str):
        return normalize('NFKC', x).strip()
    else:
        return x

df_GDP = df_GDP.applymap(clean_normalize_whitespace)
#clean column headings as well
df_GDP.columns = df_GDP.columns.to_series().apply(clean_normalize_whitespace)

I have used NFKC parameter that stands for Normal Form Kompatibility Composition. The other one is NFKD (Decompostion) along with NFD as well as NFC.

https://unicode.org/reports/tr15/#Norm_Forms

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   March 2020   April 2020   May 2020   July 2020   August 2020   September 2020   October 2020  

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