{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": ""
  },
  {
   "metadata": {
    "jupyter": {
     "is_executing": true
    }
   },
   "cell_type": "code",
   "source": "from pyspark.sql import functions as F",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "Get dataframe from data catalog"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "df = spark.sql(\"select * from pmt_db.financial\")"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "vscode": {
     "languageId": "python_session"
    }
   },
   "outputs": [],
   "source": [
    "df.printSchema()\n",
    "df.show(10)"
   ]
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "Write to S3 bucket"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "vscode": {
     "languageId": "python_session"
    }
   },
   "outputs": [],
   "source": [
    "df.limit(10).write \\\n",
    "    .mode(\"overwrite\") \\\n",
    "    .format(\"csv\") \\\n",
    "    .option(\"header\", \"true\") \\\n",
    "    .save('s3://athena-spark-workshop/output/')\n"
   ]
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "Analyze data from Government"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "df_gov = (\n",
    "    df.filter(df.segment == \"Government\")\n",
    "    .withColumn(\"country\", F.lower(\"country\"))\n",
    "    .select(\"country\", \"product\", \"sales\", \"month_number\", \"year\").orderBy(\"country\")\n",
    ")"
   ]
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "df_gov.limit(10).show()"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "df_gov_agg = (\n",
    "    df_gov.groupby(\"country\", \"product\", \"year\").agg(\n",
    "        F.sum(\"sales\").cast(\"decimal(15,2)\").alias(\"total_sales\"),\n",
    "        F.avg(\"sales\").cast(\"decimal(15,2)\").alias(\"avg_sales\"),\n",
    "        F.max(\"sales\").cast(\"decimal(15,2)\").alias(\"max_sales\"),\n",
    "        F.min(\"sales\").cast(\"decimal(15,2)\").alias(\"min_sales\"),\n",
    "    )\n",
    ")"
   ]
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "df_gov_agg.limit(10).show()"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# Create table in glue data catalog so we can also query data using Athena Query Editor.\n",
    "\n",
    "# NOTE: Remember to load partitions in Athena Query Editor.\n"
   ]
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "%%sql\n",
    "create table if not exists default.gov(\n",
    "          country string ,\n",
    "          product string ,\n",
    "          total_sales decimal(15,2),\n",
    "          avg_sales decimal(15,2),\n",
    "          max_sales decimal(15,2),\n",
    "          min_sales decimal(15,2))\n",
    "    partitioned by (year bigint)\n",
    "    ROW FORMAT SERDE 'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe'\n",
    "    location 's3://athena-spark-workshop/output/gov'\n"
   ]
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# Get started with building visualization using Amazon Athena for Apache Spark"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "#### Use Seaborn to build visualization on this data\n"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "import seaborn as sns\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "\n",
    "pd_canada = (\n",
    "    df_gov_agg.filter(df_gov_agg.country == \"canada\")\n",
    "    .filter(df_gov_agg.year == \"2014\")\n",
    "    .toPandas()\n",
    ")\n",
    "print(pd_canada)\n",
    "res = sns.relplot(x='product', y='total_sales', data=pd_canada, kind=\"line\")\n",
    "\n",
    "\n",
    "%matplot plt"
   ]
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "#### Build visualization using Matplotlib"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "plt.clf()\n",
    "name = pd_canada['product'].head(12)\n",
    "price = pd_canada['total_sales'].head(12)\n",
    " \n",
    "# Figure Size\n",
    "fig = plt.figure(figsize =(10, 7))\n",
    " \n",
    "# Horizontal Bar Plot\n",
    "plt.bar(name[0:10], price[0:10])\n",
    " \n",
    "# Show Plot\n",
    "%matplot plt"
   ]
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "#### adding piglatin python library we created earlier to PySpark session. "
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "sc.addPyFile('s3://athena-spark-workshop-227972251644/library.zip') #use your path\n",
    "\n",
    "import piglatin\n",
    "piglatin.translate('hello')\n",
    "\n",
    "from pyspark.sql.functions import udf\n",
    "from pyspark.sql.functions import col\n",
    "\n",
    "hi_udf = udf(piglatin.translate)\n",
    "\n",
    "df = spark.createDataFrame([(1, \"hello\"), (2, \"world\")])\n",
    "\n",
    "df.withColumn(\"col\", hi_udf(col('_2'))).show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Athena PySpark",
   "language": "python",
   "name": "kepler_python_kernel"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "python",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "Python_Session",
   "pygments_lexer": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
