<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Deepak kumar on Medium]]></title>
        <description><![CDATA[Stories by Deepak kumar on Medium]]></description>
        <link>https://medium.com/@deepakk073?source=rss-872bd63b5a08------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*LSfhmA7eoN3Zw6SuxLeolQ.jpeg</url>
            <title>Stories by Deepak kumar on Medium</title>
            <link>https://medium.com/@deepakk073?source=rss-872bd63b5a08------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:31:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@deepakk073/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Optimizing BigQuery Queries Using Ollama’s DeepSeek-R1:7B Model]]></title>
            <link>https://medium.com/@deepakk073/optimizing-bigquery-queries-using-ollamas-deepseek-r1-7b-model-349da2f7cadc?source=rss-872bd63b5a08------2</link>
            <guid isPermaLink="false">https://medium.com/p/349da2f7cadc</guid>
            <category><![CDATA[generative-ai-solution]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[deepseek-r1]]></category>
            <dc:creator><![CDATA[Deepak kumar]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 08:56:07 GMT</pubDate>
            <atom:updated>2025-02-02T08:56:07.017Z</atom:updated>
            <content:encoded><![CDATA[<p>BigQuery is a powerful data warehouse solution, but inefficient queries can lead to increased costs and longer execution times. Since we prioritize security and do not want to expose our codebase to any LLM, we can mitigate this risk by utilizing Ollama’s DeepSeek-R1 model. This AI-powered approach will help you refine queries for better performance, cost savings, and improved efficiency.</p><h3>Why Query Optimization Matters</h3><p>BigQuery charges based on the amount of data scanned. Poorly optimized queries can lead to unnecessary data processing and increased costs. Here are some common pitfalls:</p><ul><li>Using SELECT * unnecessarily.</li><li>Not filtering data effectively.</li><li>Inefficient joins.</li><li>Using NOT IN instead of LEFT JOIN with IS NULL.</li><li>In to Join.</li></ul><p>Our solution leverages <strong>DeepSeek-R1:7B</strong>, a powerful LLM running offline via <strong>Ollama</strong>, to automatically identify and fix these inefficiencies.</p><p>Firstly, used Ollama’s command-line tool to validate the output without adding any extra prompts.<br><strong>Input:-</strong></p><pre> Select * from employee where deptno in (select deptno from dept );</pre><p><strong>Output:-</strong></p><pre>SELECT DISTINCT e.deptno, e.*<br>FROM employee e<br>WHERE e.deptno IN (SELECT deptno FROM dept);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HyYYf-7ff7Qry2YD1ToOXQ.png" /></figure><p>The LLM’s output is not optimized. Next, we will use LangChain and provide a prompt with an example.</p><p>you can check the code added as below-</p><p><a href="https://github.com/deepakk073/genai_poc/blob/3a4c2b5b5185de9b7f69b58d75845d471a42d2a6/BQ_Optimization/BQOptimizer.ipynb">https://github.com/deepakk073/genai_poc/blob/3a4c2b5b5185de9b7f69b58d75845d471a42d2a6/BQ_Optimization/BQOptimizer.ipynb</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*WgJLWesmfkGDSbUErN2AOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*FSAPvx5oSdarmy83YnsYcA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jeU5tO7gBrRV_9RuuC3IJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*OufCOuclX4yTyQV8P-nw4w.png" /></figure><p>Final Optimized output got-</p><pre>SELECT *<br>FROM `inv-prj.sales.sales_data` s<br>JOIN `inv-prj.sales.citymaster` c<br>ON s.city = c.city</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=349da2f7cadc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Election Result Q&A Bot Using Langchain, LLaMA-3.1, and Groq Cloud]]></title>
            <link>https://medium.com/@deepakk073/building-an-election-result-q-a-bot-using-langchain-llama-3-1-and-groq-cloud-f83204708663?source=rss-872bd63b5a08------2</link>
            <guid isPermaLink="false">https://medium.com/p/f83204708663</guid>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[talk-to-db]]></category>
            <category><![CDATA[groqcloud]]></category>
            <category><![CDATA[langchain-agents]]></category>
            <dc:creator><![CDATA[Deepak kumar]]></dc:creator>
            <pubDate>Sun, 29 Sep 2024 06:18:16 GMT</pubDate>
            <atom:updated>2024-09-29T06:23:10.895Z</atom:updated>
            <content:encoded><![CDATA[<p>Election seasons often bring a surge of curiosity about outcomes, trends, and statistics. Answering real-time queries on these results, especially at scale, can be challenging. This is where I decided to build an Election Result Q&amp;A Bot. Leveraging LangChain’s LLaMA 3.1 70B model and the high-performance capabilities of Groq Cloud, I created a PoC (Proof of Concept) to tackle this challenge.</p><p>Sample Q&amp;A Screenshot of bot-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lckdWEDHbM1QqYir1mSeqw.png" /></figure><h3>This POC can be used in below Business Cases-</h3><blockquote><strong>1. Confluence Q&amp;A Bot for Knowledge Management</strong></blockquote><blockquote><strong>Problem</strong>: Employees struggle to find relevant information on Confluence.</blockquote><blockquote><strong>Solution</strong>: A Q&amp;A Bot retrieves documents and data instantly based on natural language queries, reducing search time.</blockquote><blockquote><strong>2.HR Q&amp;A Bot for Employee Self-Service</strong></blockquote><blockquote><strong>Problem</strong>: HR teams are overwhelmed with routine employee inquiries.</blockquote><blockquote><strong>Solution</strong>: A Q&amp;A Bot answers common HR queries and provides access to documents, automating repetitive tasks.</blockquote><blockquote><strong>3. IT Support Bot for Helpdesk Management</strong></blockquote><blockquote><strong>Problem</strong>: IT teams are bogged down with repetitive support requests.</blockquote><blockquote><strong>Solution</strong>: The Q&amp;A Bot provides instant tech solutions from the knowledge base and raises Jira tickets for complex issues.</blockquote><blockquote><strong>4. Sales Q&amp;A Bot for CRM Insights</strong></blockquote><blockquote><strong>Problem</strong>: Sales teams waste time navigating multiple tools for deal updates.</blockquote><blockquote><strong>Solution</strong>: A Q&amp;A Bot delivers real-time insights on leads, pipeline, and sales performance through simple queries.</blockquote><p>Coming back to Election bot Result. Below is the architecture —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*Zrj4NdX2pV3BYBXkKSe7ow.png" /></figure><p>Election Data extraction:-</p><ol><li>Used TOI News websites to extract the Election result Data. Sample link — <a href="https://timesofindia.indiatimes.com/elections/lok-sabha-constituencies/bihar/muzaffarpur">here</a></li><li>Used langchain webBaseLoader for Extract all text from HTML webpages.</li><li>used Groq API’s to use the llama3.1 models. Groq cloud is a LPU interference Engine you can use multiple LLm’s using Groq API.</li><li>Parse the LLM output using JsonOutputParser.</li><li>Final load the data to Sqllite. you can use any storage like mysql, MSSQL, Bigquery, Redshift etc.</li></ol><pre>from langchain_groq import ChatGroq<br>from langchain_community.document_loaders import WebBaseLoader<br>from sqlalchemy import create_engine, inspect<br>from langchain_core.output_parsers import JsonOutputParser<br>import re<br>import sqlite3<br>import pandas as pd<br>import os<br>from dotenv import load_dotenv<br>load_dotenv()<br>llm = ChatGroq(<br>    temperature=0, <br>    groq_api_key=os.getenv(&quot;GROQ_API_KEY&quot;), <br>    model_name=&quot;llama-3.1-70b-versatile&quot;<br>)<br>## - Below you can run a test code snippet to check does llm has latest update or not?<br>response = llm.invoke(&quot;&quot;&quot;who wins from muzaffarpur constituency in 2024 &quot;&quot;&quot;)<br>print(response.content)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJ3_fZR4D2tZq2Sx97u9jQ.png" /></figure><p>The LLM does not have access to the latest updates. To extract the details of election results, you can use the following code. Ensure that the code is stacked sequentially in the notebook. After validation, we found that most of the relevant pages follow the URL structure: <a href="https://timesofindia.indiatimes.com/elections/lok-sabha-constituencies/+States+/Constituency">https://timesofindia.indiatimes.com/elections/lok-sabha-constituencies/+States+/Constituency</a>.</p><p>To map states to their respective constituencies, I have a CSV file that contains the mapping, which is stored in the repository at <a href="https://github.com/deepakk073/genai_poc/blob/main/eci_data_extract/src/data/constituency_list.csv">src/data/constituency_list.csv</a>. In the code below, we generate a list of URLs to be scraped. For this POC, we are focusing on constituencies from Bihar, as I am using a free account and want to avoid exceeding the LLM rate limits. Git hub Link — <a href="https://github.com/deepakk073/genai_poc/tree/main/eci_data_extract">Election Q&amp;A BOT Code Base</a></p><p>To map states to their respective constituencies, I have a CSV file that contains the mapping, which is stored in the repository at src/data/constituency_list.csv. In the code below, we generate a list of URLs to be scraped. For this POC, we are focusing on constituencies from Bihar, as I am using a free account and want to avoid exceeding the LLM rate limits.</p><pre>#Read the csv file and do the data cleaning and prepare the url, We are extracting data for Bihar Constituencies only.<br>constituency_list=pd.read_csv(&#39;src//data//constituency_list.csv&#39;) <br>state_constituency_mapping=constituency_list[constituency_list[&#39;state name&#39;]==&#39;Bihar&#39;]<br>state_constituency_mapping[&#39;state name&#39;] = state_constituency_mapping[&#39;state name&#39;].str.replace(&quot; &quot;,&quot;-&quot;)<br>state_constituency_mapping[&#39;Constituency&#39;]=state_constituency_mapping[&#39;Constituency&#39;].str.replace(&quot; &quot;,&quot;-&quot;)<br>state_constituency_mapping[&#39;url&#39;]=&#39;https://timesofindia.indiatimes.com/elections/lok-sabha-constituencies/&#39;+state_constituency_mapping[&#39;state name&#39;] +&#39;/&#39;+state_constituency_mapping[&#39;Constituency&#39;] <br>state_constituency_mapping=state_constituency_mapping.rename(columns={ &#39;state name&#39;:&#39;state_name&#39;})</pre><p>In below function we are extracting the text using webBaseLoader and furthre we have provided the details to llm to extract certain key details like — `state_name` `constituency_name` `candidate_name` `election_year` `votes` `vote%` `party_name` `is_won` And passing instruction to return it as a json format.</p><pre>def load_general_election_data(weburl):<br>    from langchain_core.prompts import PromptTemplate<br>    loader = WebBaseLoader(weburl)<br>    page_data = loader.load().pop().page_content<br>    prompt_extract = PromptTemplate.from_template(<br>        &quot;&quot;&quot;<br>        ### SCRAPED TEXT FROM WEBSITE:<br>        {page_data}<br>        ### INSTRUCTION:<br>        The scraped text is from the &quot;2024  Lok Sabha Election Results&quot; section of a website.<br>        Extract only 2024 loksabha election results of all candidates<br>        Your job is to extract the election result and return them in JSON format containing the <br>        following keys: `state_name` `constituency_name` `candidate_name` `election_year` `votes` `vote%` `party_name` `is_won`<br>        Only return the valid JSON.<br>        ### VALID JSON (NO PREAMBLE):    <br>        &quot;&quot;&quot;<br>    )<br><br>    chain_extract = prompt_extract | llm <br>    res = chain_extract.invoke(input={&#39;page_data&#39;:page_data})<br>    json_parser = JsonOutputParser()<br>    json_res = json_parser.parse(res.content)<br>    df=pd.DataFrame(json_res)<br>    df[&#39;url&#39;]=weburl<br>    conn=sqlite3.connect(&#39;db/election_analysis.db&#39;)<br>    cursor = conn.cursor()<br>    df.to_sql(&#39;election_results&#39;,conn,if_exists=&#39;append&#39;,index=False)<br>    conn.commit()<br>    conn.close()</pre><p>In next steps storing the details extracted by llm to Sqllite-</p><pre># load_general_election_data(&#39;https://timesofindia.indiatimes.com/elections/lok-sabha-constituencies/Puducherry/Puducherry&#39;)<br>conn=sqlite3.connect(&#39;db/election_analysis.db&#39;)<br>cursor = conn.cursor()<br>df_getdata=pd.read_sql_query(&quot;select *  from election_results;&quot;,conn )<br>df_getdata=df_getdata[&#39;url&#39;].unique()<br># df_getdata<br>state_constituency_mapping[~state_constituency_mapping[&#39;url&#39;].isin(df_getdata)].count()<br>for toi_url in state_constituency_mapping[~state_constituency_mapping[&#39;url&#39;].isin(df_getdata)][&#39;url&#39;]:<br>    try:<br>        load_general_election_data(toi_url)<br>    except Exception as e:<br>        print(f&quot;An unexpected error occurred: {e}&quot;)</pre><p>1st phase is completed here now we have extracted the data from TOI website and store it to DB.</p><p>Now we are working on the 2nd part to serve the Q&amp;A to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*iXmld-RQ3BhSdeGP2r_UMA.png" /></figure><p>Using langchain Sql Agent and Groq API Generating SQL query based on the user Questions and SQL Agent extract the Schema from DB and then build the schema mapping and run the query providing the results —</p><pre>from langchain_community.utilities.sql_database import SQLDatabase<br># # conn=sqlite3.connect(&#39;db/election_analysis.db&#39;)<br># # cursor = conn.cursor()<br>db= SQLDatabase.from_uri(&quot;sqlite:///db/election_analysis.db?mode=ro&quot;)<br># conn.close()<br>from langchain_community.agent_toolkits import create_sql_agent<br>from langchain_core.prompts import PromptTemplate<br>llm = ChatGroq(<br>    temperature=0, <br>    groq_api_key=os.getenv(&quot;GROQ_API_KEY&quot;), <br>    model_name= &quot;llama-3.1-70b-versatile&quot;<br>)<br># response = llm.invoke(&quot;&quot;&quot;capital of india&quot;&quot;&quot;)<br>prompt_output = PromptTemplate.from_template(<br>            &quot;&quot;&quot; <br>                ### INSTRUCTION:<br>                You are an agent that interacts with a SQL database,<br>                Given a question, generate a valid SQL query and return the result. In the result add the details of Vote% and No. of Votes got by the candidate<br>                ### VALID JSON (NO PREAMBLE):<br>                &quot;&quot;&quot;<br>        )<br><br>agent_executor= create_sql_agent(llm, db=db,  prompt_template=prompt_output,verbose=True,top_k=20) <br></pre><p>In below Screenshot if you see, We asked a Question how many seat won by BJP. you can check the action taken by SQL Agent based on the schema it Converted user question to SQL Query and provided the results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iYQOzBL4hLPe7kGT-MZ6Nw.png" /></figure><p>On top of it created a Streamlit app and you can interact with BOT on the UI</p><pre>import streamlit as st<br>from langchain_groq import ChatGroq<br>from langchain_community.agent_toolkits import create_sql_agent<br>import sqlite3<br>import pandas as pd<br>import os<br>from dotenv import load_dotenv<br>load_dotenv()<br>from langchain_core.prompts import PromptTemplate<br>from langchain_community.utilities.sql_database import SQLDatabase<br><br>def create_streamlit_app():<br>    st.title(&quot;Election Result Q&amp;A Bot&quot;)<br>    question = st.text_input(&quot;Ask your Question:&quot;)<br>    # submit_button = st.button(&quot;Submit&quot;)<br>    llm = ChatGroq(<br>    temperature=0, <br>    groq_api_key=os.getenv(&quot;GROQ_API_KEY&quot;), <br>    model_name=&quot;llama-3.1-70b-versatile&quot;<br>)<br>    db= SQLDatabase.from_uri(&quot;sqlite:///db/election_analysis.db?mode=ro&quot;)<br>    # response = llm.invoke(&quot;&quot;&quot;capital of india&quot;&quot;&quot;)<br>    prompt_output = PromptTemplate.from_template(<br>                &quot;&quot;&quot; <br>                ### INSTRUCTION:<br>                You are an agent that interacts with a SQL database,<br>                Given a question, generate a valid SQL query and return the result. In the result add the details of Vote% and No. of Votes got by the candidate<br>                ### VALID JSON (NO PREAMBLE):<br>                &quot;&quot;&quot;<br>            )<br><br>    agent_executor= create_sql_agent(llm, db=db,  prompt_template=prompt_output,top_k=20) <br><br><br>    if question:<br>        with st.spinner(&#39;Generating answer...&#39;):<br>            answer=agent_executor.invoke({&quot;input&quot;:question})<br>            answer=answer[&#39;output&#39;]<br>            print(question,&quot;-&quot;,answer)<br>            st.success(f&quot;Answer:{answer} &quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    st.set_page_config(layout=&quot;wide&quot;, page_title=&quot;Election Commission Bot for Bihar&quot;)<br>    create_streamlit_app()</pre><p>All Code is present in to the Git hub — <a href="https://github.com/deepakk073/genai_poc/tree/main/eci_data_extract">Election Q&amp;A BOT Code Base</a></p><p>Stay tuned- Upcoming POC</p><ol><li>Build an agent-driven workflow using <strong>Langgraph </strong>and <strong>Crew AI </strong>to create a bot that performs stock analysis. The bot will monitor price fluctuations, and if a stock’s price changes by +/- X%, it will generate a market analysis and send an alert to the shareholders.</li><li>Will Create a POC using <strong>Langsmith</strong>, <strong>Langflow</strong>, <strong>LangGraph </strong>and <strong>Langserve.</strong></li><li>1st version of <strong>Big query optimization BOT</strong> using PROMPT and few shot learning.</li><li>Finetune model POC using Distilbert pretrained model &amp; tokenizer</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f83204708663" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhance Your Bigquery Platform Monitoring: with Custom Alerts]]></title>
            <link>https://medium.com/@deepakk073/enhance-your-bigquery-platform-monitoring-with-custom-alerts-9f8132c42c0a?source=rss-872bd63b5a08------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f8132c42c0a</guid>
            <category><![CDATA[bigquery-studio]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[bigquery-sql]]></category>
            <category><![CDATA[monitoring]]></category>
            <dc:creator><![CDATA[Deepak kumar]]></dc:creator>
            <pubDate>Mon, 27 May 2024 06:05:37 GMT</pubDate>
            <atom:updated>2024-05-27T06:05:37.391Z</atom:updated>
            <content:encoded><![CDATA[<p>Enhance your Bigquery platform monitoring: With Custom Alerts in Bigquery</p><p>In BigQuery monitoring, our monitoring options are quite restricted, and transforming them into actionable insights poses significant challenges</p><p>To address this issue, we’ve developed an approach that enables you to receive email notifications for the specific metrics you’re interested in. As an administrator, we focus on the following key performance indicators (KPIs) in the monitoring process.</p><ol><li>Monitor query execution times and identify slow-running queries.</li><li>Track query usages patterns to optimize the resource allocation.</li><li>Slot utilization, if a query is taking more slot then sent an email.</li><li>Monitor job concurrency to understand how many jobs are running simultaneously</li><li>Track bytes processed by queries to manage and optimize data processing costs.</li><li>Set up billing alerts to keep track of the query costs.</li><li>Set up alerts for specific error/critical issues.</li><li>Set up of the alerts on the resource usage by a individual user.</li></ol><p>We will walkthrough the architecture for the email alerts. And will take couple of example from above kpi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*5oRoUZ9cVHEiDAld3UhPWA.png" /><figcaption>Architecture for Custom email alerts.</figcaption></figure><p>In above architecture.</p><ol><li>Schedule the query to get the KPI information. Query execute in X min.</li><li>In schedule Query if any events match the specified KPI criteria, We store the relevent information in the Email_Outbox table.</li><li>Subsequently, upon insertion of job details into the Email_Outbox table, Insertjob events get triggered and Eventarc initiates a Cloud Run job.</li><li>Cloud run job sends real-time alerts to the users.</li></ol><p>KPI Queries —</p><p>Monitor query execution times and identify slow-running queries. We are taking 5 min as base, so if a query is running more than 5 min then we will get notify with query details.</p><pre>SELECT<br>  query,<br>  user_email,<br>job_id,<br>  timestamp_diff(current_timestamp,start_timestamp interval second) AS elapsed_time<br>FROM<br>  `project_id.dataset_id.JOBS_BY_PROJECTS`<br>WHERE<br>  end_time IS NULL<br>GROUP BY<br>  query_id<br>HAVING<br>  timestamp_diff(current_timestamp,start_timestamp interval second) &gt; 300;</pre><p>Slot utilization, if a query is taking more slot then sent an email. We are taking 1000 avg slots as a base, So if a query is taking morethan 1000 avg slots then we will get notify.</p><pre>SELECT<br>  query,<br>  user_email,<br>  job_id,<br>  AVG(total_slot_ms/timestamp_diff(current_timestamp,start_timestamp interval milisecond)) AS avg_slots<br>FROM<br>  `project_id.dataset_id.JOBS_BY_PROJECTS`<br>WHERE<br>  end_time IS NULL<br>GROUP BY<br>  query_id<br>HAVING<br>  AVG(AVG(total_slot_ms/timestamp_diff(current_timestamp,start_timestamp interval milisecond)) AS avg_slots) &gt; 1000;<br><br></pre><p>End to End Code is present in the Git Repo <a href="https://github.com/deepakk073/poc_project/tree/main/bq_custom_alerts">https://github.com/deepakk073/poc_project/tree/main/bq_custom_alerts</a></p><p>Below Query you can schedule the query with X interval, That will run and looks for the slow running query and insert the details to email_outbox table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f43f73da1755ce33e8c1d4d0f7c83be/href">https://medium.com/media/5f43f73da1755ce33e8c1d4d0f7c83be/href</a></iframe><p>GCP Enviornment setup —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8095932efa3beef2591392450aa46ddf/href">https://medium.com/media/8095932efa3beef2591392450aa46ddf/href</a></iframe><p>Once the row is inserted to email_outbox table then eventarc will look for the insert job event on resource email_outbox and it will run the cloud run Job.</p><p>Docker file for Cloud run setup and install all the requiered python module that needed to run the program.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/775a885cf60c5d8914c3c405f54f9a0b/href">https://medium.com/media/775a885cf60c5d8914c3c405f54f9a0b/href</a></iframe><p>Below program has used to sent the email to user. on line no 20 checking for row count if the insert is happen on the email_outbox table and row &gt; 0 then send email to the user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/419909b1f5f2753bdd32812dd2b5b874/href">https://medium.com/media/419909b1f5f2753bdd32812dd2b5b874/href</a></iframe><p>We are using sendgrid for email service. and in secerate_key.py we have stored the sendgrid api key. In live project we can use gcp cloud key management service to store the api key.</p><p>Git hub link -<a href="https://github.com/deepakk073/poc_project/tree/main/bq_custom_alerts">https://github.com/deepakk073/poc_project/tree/main/bq_custom_alerts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f8132c42c0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BigQuery Job Details]]></title>
            <link>https://medium.com/@deepakk073/bigquery-job-details-bfeacdb89717?source=rss-872bd63b5a08------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfeacdb89717</guid>
            <dc:creator><![CDATA[Deepak kumar]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 08:00:07 GMT</pubDate>
            <atom:updated>2024-03-03T08:00:07.391Z</atom:updated>
            <content:encoded><![CDATA[<h3>Big Query Job Details</h3><p>Identifying the list of jobs executed in Big query and their slots details —</p><pre>WITH JobStages AS (<br>  SELECT<br>    stage.job_id,<br>    stage.stage_id,<br>    stage.status AS stage_status,<br>    MAX(TIMESTAMP_DIFF(stage.end_time, stage.start_time, MILLISECOND)) AS stage_duration_ms,<br>    ARRAY_AGG(DISTINCT query.job_id) AS queries_executed_at_stage<br>  FROM<br>    `project_id.dataset_id.INFORMATION_SCHEMA.JOBS_BY_PROJECT` AS stage<br>  LEFT JOIN<br>    `project_id.dataset_id.INFORMATION_SCHEMA.JOBS` AS query<br>  ON<br>    query.job_id = stage.job_id<br>  GROUP BY<br>    stage.job_id, stage.stage_id, stage.status<br>)<br><br>SELECT<br>  query.job_id,<br>  TIMESTAMP_DIFF(query.end_time, query.start_time, MILLISECOND) AS duration_ms,<br>  TIMESTAMP_DIFF(query.start_time, query.creation_time, MILLISECOND) AS wait_ms,<br>  query.total_bytes_processed,<br>  query.slots_reserved,<br>  query.total_slot_ms,<br>  stage.stage_id,<br>  stage.stage_status,<br>  stage.stage_duration_ms,<br>  stage.queries_executed_at_stage,<br>  CONCAT(&#39;https://console.cloud.google.com/bigquery?project=&#39;, query.project_id, &#39;&amp;j=&#39;, query.job_id) AS job_url,<br>  IF(error_result IS NOT NULL, error_result[&#39;message&#39;], NULL) AS error_message,<br>  IF(error_result IS NOT NULL, error_result[&#39;reason&#39;], NULL) AS error_reason<br>FROM<br>  `project_id.dataset_id.INFORMATION_SCHEMA.JOBS` AS query<br>LEFT JOIN<br>  JobStages AS stage<br>ON<br>  query.job_id = stage.job_id<br>WHERE<br>  query.end_time IS NOT NULL<br>  AND TIMESTAMP_DIFF(query.end_time, query.start_time, MILLISECOND) &gt; 1000<br>ORDER BY<br>  duration_ms DESC;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfeacdb89717" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MSTeams notification for Bigquery long-running Queries]]></title>
            <link>https://medium.com/@deepakk073/msteams-notification-for-bigquery-long-running-queries-d8a774949849?source=rss-872bd63b5a08------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8a774949849</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[bq]]></category>
            <dc:creator><![CDATA[Deepak kumar]]></dc:creator>
            <pubDate>Sun, 19 Nov 2023 07:48:30 GMT</pubDate>
            <atom:updated>2023-11-19T07:48:30.428Z</atom:updated>
            <content:encoded><![CDATA[<p>To receive notifications on Teams for prolonged queries, various methods can be employed. However, in this instance, we will utilize Python to dispatch a notification message to MS Teams. To accomplish this, configuring a webhook at the channel level within the Teams is necessary. The subsequent steps outline the process for creating the required webhook.</p><blockquote>1. In Microsoft Teams, go to the channel where you want to post messages.</blockquote><blockquote>2. Click on the ellipsis (three dots) next to the channel name and select “Connectors.”</blockquote><blockquote>3. Search for and select “Incoming Webhook.”</blockquote><blockquote>4. Click “Add” to add the incoming webhook to the channel.</blockquote><blockquote>5. Configure the webhook, provide a name, and upload an image if desired.</blockquote><blockquote>6. Copy the generated webhook URL.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*nDiy9uWQTomUBaz4lNwtUA.png" /></figure><p>Once you get the Webhook URL copy the URL and put it on a placeholder. Now we have to write a big query to get the list of queries who is running from <strong>5 minutes and taking 1500 slots.</strong></p><p>Below is the BQ Query to get the list of queries running from 5 min and taking more than 1500 slots</p><pre>SELECT<br>  user_email,<br>  query,<br>  start_time,<br>   round(total_slot_ms / timestamp_diff(current_timestamp,start_time,millisecond),2) slots,<br>  current_datetime,<br>  DATETIME_DIFF(current_timestamp,start_time,second) AS duration_secs,<br>  total_bytes_processed  AS byte_used,<br>  &#39;https://console.cloud.google.com/bigquery?project=&#39;||project_id||&#39;&amp;j=bq:us:&#39;||ifnull(parent_job_id,job_id)||&#39;&amp;page=queryresults&#39; Bqurl,<br>from <br>&lt;project_id&gt;.`region-us`.INFORMATION_SCHEMA.JOBS_BY_PROJECT<br>where state !=&#39;DONE&#39; and <br>date(creation_time) = current_date and<br>DATETIME_DIFF(current_timestamp,start_time,second)&gt;300 --running from last 5 min<br>--below check for slots consumed more than 1500 <br>and round(total_slot_ms / timestamp_diff(current_timestamp,start_time,millisecond),2) &gt;1500<br>group by 1,2,3,4,5,6,7,8,9</pre><p>Now we will use the thing in the below Python program and schedule the program to run in 5 min.</p><p>you have to update the project_id and webhook URL and then once you run the Python code you will get the notification on the team&#39;s channel.</p><p>Python code -</p><pre>from google.cloud import bigquery<br>import requests<br>import json<br>from datetime import datetime, timedelta<br><br># Set your BigQuery project ID, dataset ID, and table ID<br>project_id = &#39;project-id&#39;<br><br># Set your Microsoft Teams webhook URL<br>#Update the teams webhook url as created in 1st steps<br>teams_webhook_url = &quot;https://outlook.office.com/webhook/your_webhook_url&quot;<br><br>def get_long_running_queries(project_id, threshold_duration, threshold_slots):<br>    client = bigquery.Client(project=project_id)<br><br>    # Calculate the timestamp for 5 minutes ago<br>    five_minutes_ago = datetime.utcnow() - timedelta(minutes=5)<br><br>    # Query to get long-running queries<br>    query = f&quot;&quot;&quot;<br>       SELECT<br>  user_email,<br>  query,<br>  start_time,<br>   round(total_slot_ms / timestamp_diff(current_timestamp,start_time,millisecond),2) slots,<br>  current_datetime,<br>  DATETIME_DIFF(current_timestamp,start_time,second) AS duration_secs,<br>  total_bytes_processed  AS byte_used,<br>  &#39;https://console.cloud.google.com/bigquery?project=&#39;||project_id||&#39;&amp;j=bq:us:&#39;||ifnull(parent_job_id,job_id)||&#39;&amp;page=queryresults&#39; Bqurl,<br>from <br>&lt;project_id&gt;.`region-us`.INFORMATION_SCHEMA.JOBS_BY_PROJECT<br>where state !=&#39;DONE&#39; and <br>date(creation_time) = current_date and<br>DATETIME_DIFF(current_timestamp,start_time,second)&gt;300 --running from last 5 min<br>--below check for slots consumed more than 1500 <br>and round(total_slot_ms / timestamp_diff(current_timestamp,start_time,millisecond),2) &gt;1500<br>group by 1,2,3,4,5,6,7,8,9<br><br>    &quot;&quot;&quot;<br><br>    # Run the query<br>    query_job = client.query(query)<br><br>    # Fetch results<br>    results = query_job.result()<br><br>    return results<br><br>def send_teams_message(webhook_url, message):<br>    headers = {&quot;Content-Type&quot;: &quot;application/json&quot;}<br>    payload = {<br>        &quot;text&quot;: message<br>    }<br><br>    response = requests.post(webhook_url, headers=headers, data=json.dumps(payload))<br><br>    if response.status_code == 200:<br>        print(&quot;Message sent successfully&quot;)<br>    else:<br>        print(f&quot;Failed to send message. Status code: {response.status_code}, Response content: {response.text}&quot;)<br><br>def main():<br>    # Set threshold values<br>    threshold_duration = 5 * 60  # 5 minutes in seconds<br>    threshold_slots = 1500<br><br>    # Get long-running queries<br>    long_running_queries = get_long_running_queries(project_id, threshold_duration, threshold_slots)<br><br>    # Format the message<br>    message = &quot;**Long running queries:**\n\n&quot;<br>    for row in long_running_queries:<br>        message += f&quot;**Job Executed By:-** {row[&#39;user_email&#39;]}\n```sql\n{row[&#39;query&#39;]}\n``` \n**Start Time:-** {row[&#39;start_time&#39;]}\n**Total Slots:-** {row[&#39;slots&#39;]}\n\n**Job Details:-** {row[&#39;Bqurl&#39;]} \n\n&quot;<br><br>    # Send the message to Teams<br>    send_teams_message(teams_webhook_url, message)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>once you run the above code you will receive the notification on the team&#39;s group like the below-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*DysMROqzT0n2rOVPNHIqMQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8a774949849" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integration of chatgpt in google docs.]]></title>
            <link>https://medium.com/@deepakk073/integration-of-chatgpt-in-google-docs-7e5921f824f9?source=rss-872bd63b5a08------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e5921f824f9</guid>
            <category><![CDATA[chatgpt3]]></category>
            <category><![CDATA[google-app-script]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[google-docs-add-on]]></category>
            <category><![CDATA[chatgpt-chatbot]]></category>
            <dc:creator><![CDATA[Deepak kumar]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 21:41:44 GMT</pubDate>
            <atom:updated>2023-07-11T03:48:27.461Z</atom:updated>
            <content:encoded><![CDATA[<p>There are two ways to integrate chatgpt in google docs. Chatgpt provides an extension of google docs that you can get from the extension -&gt;add on and install the chatgpt extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dpFQoQUklEJrLGab5VBzmg.png" /></figure><p>2nd way to use the appscript code and Create a menu inside the menu, you can write a function that will call the chatgpt api and write the response the same document.</p><p>To send the message to chatgpt api we have selected the text and called the chatgpt function and write the response on the document.</p><p>Below app script code -&gt;</p><pre>/ Constants<br>const API_KEY = &quot;sk-*********************&quot;;<br>const MODEL_TYPE = &quot;gpt-3.5-turbo&quot;; //chatGPT model<br><br>//Create a menu in google Docs<br>function onOpen() {<br>  DocumentApp.getUi().createMenu(&quot;ChatGPT&quot;)<br>      .addItem(&quot;Sent Message to ChatGPT&quot;, &quot;sentmessagetochatgpt&quot;)<br>      .addToUi();<br>}<br><br>function sentmessagetochatgpt() {<br>  const doc = DocumentApp.getActiveDocument();<br>  const selectedText = doc.getSelection().getRangeElements()[0].getElement().asText().getText();<br>  const body = doc.getBody();<br>  const prompt = selectedText;<br>  const temperature = 0;<br>  const maxTokens = 2060;<br><br>  const requestBody = {<br>    model: MODEL_TYPE,<br>    messages: [{role: &quot;user&quot;, content: prompt}],<br>    temperature,<br>    max_tokens: maxTokens,<br>  };<br><br>  const requestOptions = {<br>    method: &quot;POST&quot;,<br>    headers: {<br>      &quot;Content-Type&quot;: &quot;application/json&quot;,<br>      Authorization: &quot;Bearer &quot; + API_KEY,<br>    },<br>    payload: JSON.stringify(requestBody),<br>  };<br><br>  const response = UrlFetchApp.fetch(&quot;https://api.openai.com/v1/chat/completions&quot;, requestOptions);<br>  const responseText = response.getContentText();<br>  const json = JSON.parse(responseText);<br>  const generatedText = json[&#39;choices&#39;][0][&#39;message&#39;][&#39;content&#39;];<br>  Logger.log(generatedText);<br>  body.appendParagraph(generatedText.toString());</pre><p>above code, you have to replace the API_KEY with your own api key (to generate API key follow the given link— <a href="https://platform.openai.com/account/api-keys">https://platform.openai.com/account/api-keys</a>). To go to the Appscript studio you have to click on google docs Extension -&gt; App Script as shown on the below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*T7hCuGnZyiQtRUOKorpcxw.png" /></figure><p>You can paste the code in the Appscript you can save the code and Run, initially, it asks for permission to access your data on the docs. you will receive an alert that this app is not verified by Google you have to click on advanced and go with unsafe(shown in image 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tMR_LP-SeYNMTRU3LP33mQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*nJe31t839wRi4BdXB22bew.png" /></figure><p>After giving the permission chatgpt menu will start appearing in the docs as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BYjQuQHrFAU1d0_r3ievrw.png" /></figure><p>Now let’s ask anything in chatgpt- to ask in the google docs you have to write your question and select the text and click on the chatgpt menu -&gt; “sent meesage to chatgpt”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ovFMq6tyEsvUdUDJByLH7Q.png" /></figure><p>After click, you will get the response as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*eFyb9129kAl-NeIHKjAjJg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e5921f824f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to update all sequences with the max value of the respective table]]></title>
            <link>https://medium.com/@deepakk073/how-to-update-all-sequences-with-the-max-value-of-the-respective-table-c53b1fb5fd1b?source=rss-872bd63b5a08------2</link>
            <guid isPermaLink="false">https://medium.com/p/c53b1fb5fd1b</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[data-migration]]></category>
            <dc:creator><![CDATA[Deepak kumar]]></dc:creator>
            <pubDate>Sun, 12 Mar 2023 06:18:29 GMT</pubDate>
            <atom:updated>2023-03-12T06:21:33.783Z</atom:updated>
            <content:encoded><![CDATA[<p>To update/restart all sequences with their max value of the respective table. Such activity is often encountered in migration work or somehow your indexes are not aligned with the max ID of the table and that column has a primary/Unique key then it throws the error. To get rid of this problem below are the steps to follow.</p><p>There are two ways to update the sequence&#39;s last value.</p><p>1st way is to use the DDL command and alter the sequence and restart your sequence with the given number.</p><pre>ALTER SEQUENCE dkschema.test_seq_incr5 RESTART WITH 22;<br>--(dkschema is the schema name)</pre><p>2nd way is to setvalue of a sequence.</p><pre>select setval(&#39;dkschema.test_seq_incr5&#39;,100, true)</pre><p>Let’s suppose we are migrating the data from one database to another and we have to reset the sequence with the max id of the table.</p><p>Assuming the sequences are used as a default value in the table. Based on that assumption we can get the Table, Column, and Sequence relation from the INFORMATION_SCHEMA.COLUMNS Table.</p><pre>select * from information_schema.columns <br> where table_Schema =&#39;dkschema&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*XEX0qWMikWnZ1Xnwi7B_nQ.png" /></figure><p>we got the sequence details in column_default as shown in the above image.</p><pre>SELECT <br> regexp_replace(column_default,&#39;^(nextval)\S\S|(::regclass)||\S$|(&#39;&#39;)&#39;,&#39;&#39;,&#39;g&#39;)  sequence_name<br> ,table_schema||&#39;.&#39;||table_name table_fullname<br> ,format(&#39;select max(%I) as mx_id from %I.%I&#39;,column_name,table_schema,table_name) MaxID<br> --,query_to_xml(format(&#39;select max(%I) as mx_id from %I.%I&#39;,column_name,table_schema,table_name),FALSE, TRUE, &#39;&#39;)<br>FROM information_schema.columns<br>where column_default like &#39;nextval%&#39;<br>and table_schema like &#39;dkschema&#39;</pre><p>The above query gives us the sequence name and using table_name and column_name, We are able to form a select query that will give us the MaxId of the respective table. using <a href="https://stackoverflow.com/questions/14897398/using-query-to-xml-in-postgresql-with-prepared-statements"><strong>query_to_xml</strong></a> function that select statements are executing on the fly as shown in the below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ht9KuDDUIuJ4auGMNBy0zw.png" /></figure><p>QUERY_TO_XML has count of the each table in XML Format in next step we have to extract max_id value from below xml data(query_to_xml)=</p><blockquote>&lt;row xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&quot;&gt;<br> &lt;mx_id&gt;35&lt;/mx_id&gt;<br>&lt;/row&gt;</blockquote><p>to extract the mx_id from the XML we are using <strong>xpath</strong> function to get the max_id of that column. In the next column, we are preparing a statement like select setval(‘sequence_name’, count, true) to set the current max value in the sequence and we are running that select statement using the query_to_xml function. It will update the sequence value of all tables.</p><pre>With cte as <br>(<br> SELECT <br>    regexp_replace(column_default,&#39;^(nextval)\S\S|(::regclass)||\S$|(&#39;&#39;)&#39;,&#39;&#39;,&#39;g&#39;)  seq_name<br>    ,table_schema||&#39;.&#39;||table_name table_fullname<br>    ,format(&#39;select max(%I) as mx_id from %I.%I&#39;,column_name,table_schema,table_name) MaxID<br>    ,query_to_xml(format(&#39;select max(%I) as mx_id from %I.%I&#39;,column_name,table_schema,table_name),FALSE, TRUE, &#39;&#39;) xml_maxId<br> FROM information_schema.columns<br> where column_default like &#39;nextval%&#39;<br>   and table_schema like &#39;dkschema&#39;<br>)select <br>    seq_name,<br>    table_fullname,<br>    (xpath(&#39;/row/mx_id/text()&#39;, xml_maxId))[1]::text sequence_value_Update,<br>    query_to_xml(concat(&#39;select setval(&#39;&#39;&#39;,seq_name,&#39;&#39;&#39;&#39;,&#39;,&#39;,<br>             coalesce((xpath(&#39;/row/mx_id/text()&#39;, xml_maxId))[1]::text,&#39;1&#39;),<br>        &#39;,true&#39;,&#39;)&#39;)<br>      ,FALSE, TRUE, &#39;&#39;)  AS max_count<br> from cte</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_0S9RwAQUbmD7BnO70nL2Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c53b1fb5fd1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analysis of New Delhi’s Legislative Assembly Elections, 2020 with Python, BigQuery, & Data Studio]]></title>
            <link>https://medium.com/mediaagility-sparks/delhi-election-analysis-using-beautifulsoup-python-bigquery-and-data-studio-17371bfd98ba?source=rss-872bd63b5a08------2</link>
            <guid isPermaLink="false">https://medium.com/p/17371bfd98ba</guid>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Deepak kumar]]></dc:creator>
            <pubDate>Sun, 23 Feb 2020 17:00:37 GMT</pubDate>
            <atom:updated>2020-02-28T10:08:18.286Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Analysis of New Delhi’s Legislative Assembly Elections, 2020 with Beautiful Soup Python, BigQuery, and Data Studio</strong></h3><figure><a href="https://datastudio.google.com/reporting/1EBNG-ndgvUQ2m2x8e52Lc6HJ4QlhGHAW/page/gc2FB"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WbrSf2ODq-cuqKUlserK9w.png" /></a></figure><p>2020 Legislative Election in India’s capital, New Delhi, was an interesting affair for various political, development, and policy reasons. In addition to these reasons, I developed an interest to analyze and understand more about it with technology. I dedicated a weekend for this project to understand the following -</p><p>I. The vote share of each political party</p><p>II. The gain in vote share and the seat won-lost ratio to understand the performance of Ministers of Parliament</p><p>III. The assembly constituencies that saw close-defeats</p><p>IV. Loksabha-constituency-wise vote gain and comparison with the votes of the winner</p><p>These are the steps I followed in this analysis; I explain a few in detail below -</p><ol><li>Collecting data using Python and Beautiful Soup.</li><li>Downloading data from Election Commission’s website and dumping it into BigQuery.</li><li>Cleansing and refining the data on BigQuery.</li><li>Once the data was ready, I created a dashboard using Data Studio.</li></ol><h3><strong>Data collection</strong></h3><p>I created a script that visits the <a href="http://results.eci.gov.in/DELHITRENDS2020/ConstituencywiseU051.htm">Election Commission</a>’s website and appends the data of all candidates into a CSV file. Below is the code to accumulate the data into a CSV file (delhi_assembly_2020.csv).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NM7hODHh_QmLUkeeVZwzew.png" /></figure><p>The next step was to create a script to get the constituency of each candidate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*04cRy1Qk45Kwiz2LstQkFA.png" /></figure><p>The next script gets the constituency-wise MP (Minister of Parliament) list and creates the 3rd CSV file (delhi_mplist.csv).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1kKy0ezRDLrcdQxzDni69A.png" /></figure><p>I have added all these codes <a href="https://github.com/deepakk073/delhi_election_analysis">here</a> and would encourage you to go ahead and elaborate and reuse them further.</p><h3><strong>Loading data to BigQuery</strong></h3><p>I uploaded all the three CSV files to BigQuery using a web UI. While analyzing the data, I found there were few assembly names that appeared differently in delhi_assembly_2020 and delhi_legislative_assembly_Loksabha CSV files. So, I had to standardize them in the delhi_assembly_2020 file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*dzCVp1w8qyYoRT_9N9bL1A.png" /></figure><p>After the standardization, I created the dataset to feed the dashboard. Following is the <a href="https://console.cloud.google.com/bigquery?sq=169798990516:fe0efbd12a1b4302bcf44cdccac05e1a">query</a> -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0nhHxqfKzqh7mIN4B1RgQA.png" /></figure><p><a href="https://datastudio.google.com/reporting/1EBNG-ndgvUQ2m2x8e52Lc6HJ4QlhGHAW/page/gc2FB">Here </a>is the dashboard that displays visually the following: Loksabha constituency-wise vote share, party-wise vote share analysis, highest vote and seat gain by Loksabha constituencies, winning margins of fewer than 10K votes, voting concentration based on the total votes per constituency, and more.</p><p>This was a fun and insightful project and helped me apply my skills to understand a real-life event.</p><p>Have ideas and questions? Let’s discuss in the comments section.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatastudio.google.com%2Fembed%2Freporting%2F1EBNG-ndgvUQ2m2x8e52Lc6HJ4QlhGHAW%2F%3Ffeature%3Doembed&amp;dntp=1&amp;display_name=Google+Data+Studio&amp;url=https%3A%2F%2Fdatastudio.google.com%2Freporting%2F1EBNG-ndgvUQ2m2x8e52Lc6HJ4QlhGHAW&amp;image=https%3A%2F%2Fdatastudio.google.com%2Freporting%2F1EBNG-ndgvUQ2m2x8e52Lc6HJ4QlhGHAW%2Fthumbnail%3Fsz%3Dw1200-h900-p-nu%26feature%3Doembed&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=google" width="1200" height="935" frameborder="0" scrolling="no"><a href="https://medium.com/media/b25faa32629ccd3663faef156c7f820a/href">https://medium.com/media/b25faa32629ccd3663faef156c7f820a/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17371bfd98ba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mediaagility-sparks/delhi-election-analysis-using-beautifulsoup-python-bigquery-and-data-studio-17371bfd98ba">Analysis of New Delhi’s Legislative Assembly Elections, 2020 with Python, BigQuery, &amp; Data Studio</a> was originally published in <a href="https://medium.com/mediaagility-sparks">MediaAgility Sparks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Nested and Repeated fields in Bigquery]]></title>
            <link>https://medium.com/mediaagility-sparks/working-with-nested-and-repeated-fields-in-bigquery-1dcae3228caf?source=rss-872bd63b5a08------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dcae3228caf</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Deepak kumar]]></dc:creator>
            <pubDate>Thu, 05 Dec 2019 06:23:53 GMT</pubDate>
            <atom:updated>2019-12-10T08:17:09.022Z</atom:updated>
            <content:encoded><![CDATA[<p>When I moved from SQL server and started working on BigQuery, one of the striking differences was how BigQuery denormalized data, as opposed to flattening in SQL. This is the reason why computation performance is enhanced in BigQuery - a query needs to run on fewer fields to fetch data. In most scenarios, the additional cost for storage is offset significantly by the computational gains achieved.</p><p>Nested and repeated fields are how BigQuery maintains denormalized data. They help in maintaining relationships without slowing the performance as relational (normalized) schema does.</p><p>With the different schema of nested and repeated fields, the querying also is a bit different. So, this blog will talk about various queries on nested and repeated fields through for two data types: array and struct. I have attached screenshots of the queries and results wherever needed.</p><p><strong>Array Datatype</strong></p><p>An array is an ordered list containing zero or more values. It stores only a single data type, not mixed integers and string values.</p><p><strong>Creating an array field -</strong></p><blockquote><em>Select ARRAY&lt;STRING&gt;[‘Apple’, ’Mango’, ’Cherry’, ’Banana’] as Fruits</em></blockquote><blockquote>Select ARRAY[<em>‘Apple’, ’Mango’, ’Cherry’, ’Banana’</em>] as <em>Fruits</em></blockquote><blockquote>Select [<em>‘Apple’, ’Mango’, ’Cherry’, ’Banana’</em>] as <em>Fruits</em></blockquote><blockquote>with cte as<br>(select ‘Apple’ Fruit<br> union all select ‘Mango’<br> union all select ‘Cherry’<br> union all select ‘Banana’<br> ) select array(select Fruit from cte) Fruits</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*8IEHylz_gzPXwhaOhYVPVA.png" /></figure><p><strong>Fetching data from the array column, based on position.</strong></p><p>There are two functions <strong>ORDINAL </strong>and <strong>OFFSET </strong>that is used to fetch data from an array based on an index. <strong>ORDINAL </strong>starts with ONE and <strong>OFFSET </strong>starts with ZERO.</p><blockquote>with cte as<br> (<br> Select ARRAY&lt;STRING&gt;[‘Apple’, ‘Mango’, ‘Cherry’,’Banana’] as Fruits<br> ) select Fruits[ORDINAL(1)], Fruits[OFFSET(0)],<br> Fruits[ORDINAL(2)], Fruits[OFFSET(1)],<br> Fruits[ORDINAL(3)], Fruits[OFFSET(2)],<br> Fruits[ORDINAL(4)], Fruits[OFFSET(3)]<br> from cte</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*D5d7S0nS_67wc0YvA5xUBw.png" /></figure><p><strong>Counting each element of an array column.</strong></p><p>When we query with <strong>count(Fruits) </strong>on an array, we get the count of rows, not the count of the elements within that array.</p><blockquote>with cte as<br> (<br> Select ARRAY&lt;STRING&gt;[‘Apple’, ‘Mango’, ‘Cherry’,’Banana’] as Fruits<br> union all<br> Select ARRAY&lt;STRING&gt;[‘Grapes’, ‘Cherries’, ‘Blueberry’,’Damson’] as Fruits<br> ) <strong>select count(*)<br> from cte</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*h1CUpwXfbbqw7s-4QJnzxQ.png" /></figure><p><strong>ARRAY_LENGTH</strong> function is used to get the exact count of elements in an array column.</p><blockquote>with cte as<br> (<br> Select ARRAY&lt;STRING&gt;[‘Apple’, ‘Mango’, ‘Cherry’,’Banana’] as Fruits<br> union all<br> Select ARRAY&lt;STRING&gt;[‘Grapes’, ‘Cherries’, ‘Blueberry’,’Damson’] as Fruits<br> )<strong> select ARRAY_LENGTH(Fruits)<br> from cte</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*Zmvo9hVnqr7lUWrZCN9p-w.png" /></figure><p><strong>SUM</strong> calculates the count of all elements. It gives the exact count of the data present in the array columns.</p><blockquote>with cte as<br> (<br> Select ARRAY&lt;STRING&gt;[‘Apple’, ‘Mango’, ‘Cherry’,’Banana’] as Fruits<br> union all<br> Select ARRAY&lt;STRING&gt;[‘Grapes’, ‘Cherries’, ‘Blueberry’,’Damson’] as Fruits<br> ) <strong>select Sum(ARRAY_LENGTH(Fruits))<br> from cte</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*4e0XHXAepwaZ-vJAyOdxEw.png" /></figure><p><strong>Unnesting the array fields in BigQuery.</strong></p><p>Here is the data that we wanted to unnest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*afq36ZwzHsm8E5Opo3ZJ6A.png" /></figure><p>The query to unnest the data with respect to shop is <strong>Select Fruit, shop from cte, Unnest(Fruits) Fruit.</strong></p><p><em>.</em></p><blockquote>with cte as<br> (<br> Select ARRAY&lt;STRING&gt;[‘Apple’, ‘Mango’, ‘Cherry’,’Banana’,’Grapes’,’Kiwi’] as Fruits,’Shop1&#39; Shop<br> union all <br> Select ARRAY&lt;STRING&gt;[‘Apple’, ‘Mango’, ‘Cherry’] as Fruits,’Shop2&#39; Shop<br> union all<br> Select ARRAY&lt;STRING&gt;[‘Apple’, ‘Mango’, ‘Cherry’,’Banana’,’Orange’] as Fruits,’Shop3&#39; Shop<br> ) <strong>select Fruit,shop<br> from cte<br> ,unnest(Fruits) Fruit</strong></blockquote><p>The Fruits array has been unnested below and each value of fruits is appearing in the new alias Fruit column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*gCuAWNH7Q--2_DEBuwz1VQ.png" /></figure><p><strong>Struct Datatype</strong></p><p>In struct datatype, we can store data of different data types.</p><p>The syntax for creating data with struct column-</p><blockquote>#Creating a struct type data on the fly<br>select STRUCT&lt;INT64, STRING&gt;(3, ‘Project1’) as teams</blockquote><blockquote>#Creating a struct type data on the fly<br>select STRUCT(3 As noofpeople, ‘Project1’ as project) teams</blockquote><blockquote>#Creating a multiple row struct type data on the fly<br>select STRUCT(3 As noofpeople, ‘Project1’ as project) teams<br>union all<br>select STRUCT(3 As noofpeople, ‘Project2’ as project) teams</blockquote><blockquote># Struct type data with array column<br>select STRUCT(3 As noofpeople, ‘Project1’ as project,[‘People1’,’People2&#39;] as teammember) as teams</blockquote><blockquote># multiple Struct type data with array column<br>select STRUCT(3 As noofpeople, ‘Project1’ as project, ‘People2’, ’People3&#39;,’People4&#39;] as teammember) AS teams<br>union all<br>select STRUCT(3 As noofpeople, ‘Project2’ as project, [‘People2’,’People3&#39;,’People4&#39;,’People5&#39;] ) teams</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*RT-zQnvc8EKTIjJrdfMsOw.png" /></figure><h3><strong>Unnesting the struct column</strong></h3><p>In the below query, we need to find how many projects People2 is associated with. People2 is in the ‘teammember’ column in the repeated mode. So we first unnest the column and then filter out the required information. The queries are as follows:</p><blockquote><em>with cte as <br>(<br> select STRUCT(2 As noofpeople, ‘Project1’ as project, [‘People1’,’People2&#39;] as teammember) teams, ‘2nd Column’ Column2<br> union all<br> select STRUCT(3 As noofpeople, ‘Project2’ as project, [‘People2’,’People3&#39;,’people4&#39;] as teammember) teams, ‘2nd Column’ Column2<br> union all<br> select STRUCT(4 As noofpeople, ‘Project2’ as project, [‘People2’,’People3&#39;,’people4&#39;,’people5&#39;] as teammember) teams, ‘2nd Column’ Column2<br>)<br>select tm,teams.project from cte<br>left join UNNEST(teams.teammember) tm<br>where tm=’People2&#39;</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zRc0K5YLjH7NZGEAqv82qQ.png" /></figure><p>For practice purpose you can validate these example for further clarifications:- <a href="https://console.cloud.google.com/bigquery?sq=395845685018:ef448b1c4f734f7c9cfc4880529df5ef">https://console.cloud.google.com/bigquery?sq=395845685018:ef448b1c4f734f7c9cfc4880529df5ef</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dcae3228caf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mediaagility-sparks/working-with-nested-and-repeated-fields-in-bigquery-1dcae3228caf">Working with Nested and Repeated fields in Bigquery</a> was originally published in <a href="https://medium.com/mediaagility-sparks">MediaAgility Sparks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transpose of Rows to Column in Bigquery]]></title>
            <link>https://medium.com/@deepakk073/transpose-of-rows-to-column-in-bigquery-54a189bf9fed?source=rss-872bd63b5a08------2</link>
            <guid isPermaLink="false">https://medium.com/p/54a189bf9fed</guid>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[google-big-query]]></category>
            <dc:creator><![CDATA[Deepak kumar]]></dc:creator>
            <pubDate>Sat, 26 Jan 2019 19:17:42 GMT</pubDate>
            <atom:updated>2019-08-28T04:53:20.016Z</atom:updated>
            <content:encoded><![CDATA[<h3>Transpose Rows to Column in Bigquery</h3><p>We have some string data based on row and column delimited in the column of big query table. It is not a good practice to store the data in string format with different delimiter. We can store such data as a struct.</p><p>Let’s take a example you are migrating data from sql server. Where we can save such data very often and then with the help of table valued function we can easily convert those data into column. In big query it is not so easy.</p><p>We have a table temptable where there are two columns. id and value in value. If you see the data which is present in the Data column is like of json we have key and it’s value based on the = delimiter. Now we have to transpose these data in a way that we can run query</p><blockquote>SELECT id, name, age, hobby<br>FROM `temptable`<br>WHERE company= ‘mediaagility’<br>AND age= 30</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*yvJIm2ogYaLkip0onfwxCA.png" /></figure><p>We have to transpose the data in below format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*JUpOYMwBOJihRV9gUWb7Lg.png" /></figure><p>For Transpose the data first of all we have to split the value data based on “;” once we split the value column then will get and array let’s take the alias of that column is keyvalue.</p><p>Syntax:- <strong>SPLIT(Data,’;’)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*QqKr1zOyywChudUeaKF7Bg.png" /></figure><p>After that will unnest the array and split the data based ‘=’ and will create 2 column (Key and value). where all key is present in Key column ad all value will present in Value.</p><p>Synatax:- <strong>Split(KeyValue,’=’)[OFFSET(0)] </strong>:- It returns an array of 2 row in 0th offset all key is present and on 1 offset our value will present.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*WF3PBJSXoKB-BkzwROOfJA.png" /></figure><p>We are creating a view with the name of vw_tempdata. Here is the link of above query. You can do dry run.</p><p>Query:- <a href="https://console.cloud.google.com/bigquery?sq=957358732541:acc8052ce3634c488cd73826207022aa">https://console.cloud.google.com/bigquery?sq=957358732541:acc8052ce3634c488cd73826207022aa</a></p><p>Here is the query for transpose the data from row to column and value will iterated with respect to the column.</p><blockquote>select id<br> ,MAX(IF(Key = “name”, Value, NULL)) as name<br> ,MAX(IF(Key = “ age”, Value, NULL)) as age<br> ,MAX(IF(Key = “ project”, Value, NULL)) as project<br> ,MAX(IF(Key = “ company “, Value, NULL)) as company <br> ,MAX(IF(Key = “ previouscompany”, Value, NULL)) as previouscompany<br> ,MAX(IF(Key = “ hobby”, Value, NULL)) as hobby<br>From `deepakk-bot.deepakdev.vw_tempdata`<br>group by id order by id</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*5k1-ZcvmwHzIFaRWqTvbEA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54a189bf9fed" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>