Google's Anti-Pattern Recognition Tool: Streamlining BigQuery Performance - Build What's Next
Blog

Google’s Anti-Pattern Recognition Tool: Streamlining BigQuery Performance

1228

Of your peers have already read this article.

2:30 Minutes

The most insightful time you'll spend today!

Improve your BigQuery performance and optimize costs with Google's BigQuery anti-pattern recognition tool, a solution designed to identify and rectify SQL query inefficiencies, boosting your data handling efficiency.

Why do we need a BigQuery anti-pattern recognition tool?

BigQuery is a serverless and cost-effective enterprise data warehouse that works across cloud environments and scales with your data. As with any large scale data-intensive platform, following best practices and avoiding inefficient anti-patterns goes a long way in terms of performance and cost savings. 

Usually SQL optimization requires a significant time investment from engineers, who must read high-complexity queries, devise a variety of approaches to improve performance and efficiency, and test several optimization techniques. The best place to start is to fix anti-patterns, since this only requires easily applicable changes and provides significant performance improvements.

To facilitate the task of identifying and fixing said anti-pattern, Google Professional Services Organization (PSO) and Global Services Delivery (GSD) have developed a BigQuery anti-pattern recognition tool. This tool automates the process of scanning SQL queries, identifying antipatterns, and providing optimization recommendations.

https://storage.googleapis.com/gweb-cloudblog-publish/original_images/1-tool-arch.jpg

What is the BigQuery anti-pattern recognition tool?

The BigQuery anti-pattern recognition tool let you easily identify performance impacting anti-patterns across a large number of SQL queries in a single go. 

It utilizes ZetaSQL to parse BigQuery SQL queries into abstract syntax trees (AST) and then traverses the tree nodes to detect the presence of anti-patterns. 

The tool takes a BigQuery SQL query as an input, such as:

SELECT
 t.dim1,
 t.metric1
FROM
 `dataset.table` t
WHERE
 t.id NOT IN (
 SELECT
   id
 FROM
   `dataset.table2`)

And produces the output as:

Subquery in filter without aggregation at line 8.

It examines potential optimizations, including:

  • Selecting only the necessary columns
  • Handling multiple WITH-clause references 
  • Addressing subqueries in filters with aggregations
  • Optimizing ORDER BY queries with LIMIT
  • Enhancing string comparisons
  • Improving JOIN patterns
  • Avoiding subquery aggregation in the WHERE clause

The solution supports reading from various sources, such as:

  • Command line 
  • Local files
  • Cloud Storage files
  • Local folders
  • Cloud Storage folders
  • CSV (with one query per line)
  • INFORMATION_SCHEMA

Additionally, the solution provides flexibility in writing output to different destinations, including:

  • Printing to the terminal
  • Exporting as CSV

Writing to a BigQuery table

Using the BigQuery anti-pattern recognition tool

The BigQuery anti-pattern recognition tool is hosted on GitHub. Below are the Quick Start steps on using the tool via command line for inline queries. You can also leverage Cloud Run to deploy it as a container on cloud. 

Prerequisites

  • Linux OS
  • JDK 11 or above is installed
  • Maven
  • Docker
  • gcloud CLI

Quick start: – steps

1. Clone the repo into your local machine.

git clone git@github.com:GoogleCloudPlatform/bigquery-antipattern-recognition.git

2. Build the tool image inside the `bigquery-antipattern-recognition` folder.

mvn clean package jib:dockerBuild -DskipTests
https://storage.googleapis.com/gweb-cloudblog-publish/images/2_BigQuery_anti-pattern_recognition_tool.max-1600x1600.png

3. Run the tool for a simple inline query.

docker run \
  -i bigquery-antipattern-recognition \
  --query "SELECT * FROM \`project.dataset.table1\`"

4. Below is the output result in the command-line interface:

https://storage.googleapis.com/gweb-cloudblog-publish/images/3_BigQuery_anti-pattern_recognition_tool.max-1000x1000.png

Additionally, the above tool can read queries from Information Schema and load the output recommendations to a BigQuery table.

Below is an example of the BigQuery anti-pattern recognition tool results exported to a BigQuery table.

https://storage.googleapis.com/gweb-cloudblog-publish/images/4_BigQuery_anti-pattern_recognition_tool.max-1900x1900.png

Getting started

Ready to start optimizing your BigQuery queries and cutting costs? Check out the tool here and contribute to the tool via GitHub.

Have questions or feedback?

We’re actively working on new features to make the tool as useful to our customers. Use it and tell us what you think! For product feedback/technical questions, reach out to us at bq-antipattern-eng@google.com. If you’re already a BigQuery customer and would like a briefing on the tool, please reach out, we’d be happy to talk.

Blog

HarbourBridge Schema Assistant Allows Quick, Bulk Migration to Cloud Spanner

5464

Of your peers have already read this article.

1:30 Minutes

The most insightful time you'll spend today!

Google Cloud announces the open-source HarbourBridge Schema Assistant for a guided schema-design workflow for migrating from MySQL or PostgreSQL to Cloud Spanner. Learn more.

Today we’re announcing the HarbourBridge Schema Assistant, which provides a guided schema-design workflow for migrating from MySQL or PostgreSQL to Spanner. HarbourBridge imports dump files (from mysqldump or pg_dump) or directly connects to your source database, and converts the source database schema to an equivalent Spanner schema. The new Schema Assistant capability displays the source schema and Spanner schema side-by-side, highlights errors and walks you through a series of steps to validate and optimize your Spanner schema. It also produces a browsable assessment report with an overall migration-fitness score for Spanner, a table-by-table detailed analysis of type mappings and a list of features used in the source database that aren’t supported by Spanner. It supports editing of table and column names, column types, primary keys and constraints, as well as dropping of tables, columns, foreign keys and secondary indexes.

The new Schema Assistant complements HarbourBridge’s existing data and schema migration capabilities and is a critical step towards our goal of building a complete open-source migration toolkit. HarbourBridge continues to support command-line schema and data migration and turn-key Spanner evaluation.

Complementing the bulk data migration capabilities of HarbourBridge, we are also announcing the ability to migrate change events from MySQL to Cloud Spanner.

image4.png
HarborBridge takes your MySQL or PostgreSQL schema and translates it to a Spanner schema. It will provide you with a detailed report of all the changes and spanner fit scoes.

Supported Features in Schema Assistant

  1. Global type mapping. Users can customize the global mapping for how types should be mapped to Spanner consistently across the schema. For example, mapping large integers in source schema to Spanner’s NUMERIC.
  2. Local type mapping. Users can override the custom type mapping for a given table/column.
  3. Session management. A session keeps track of all the changes made to the schema mapping.
  4. Customization of secondary indexes. Users can add, edit and delete secondary indexes to optimize their Spanner performance.
  5. Customization of foreign keys and interleaved tables. Table interleaving is an important design consideration when migrating to Cloud Spanner as explained in more detail in this blog post.
image1.png
Global type mapping from MySQL to Spanner
image3.png
tables and columns mapping from source to destination

Features in the pipeline

We are already working to further expand the supported set of schema editing features and welcome your feedback. We are particularly excited to expand the Schema Assistant’s design recommendations for optimizing Spanner schemas e.g. in-depth recommendations for primary key design.

HarbourBridge is open source and we gladly accept contributions from the wider community.

Explainer

What’s Google Cloud Firestore Database and What are it’s Benefits for Business and Developers?

5957

Of your peers have already read this article.

2:30 Minutes

The most insightful time you'll spend today!

Cloud Firestore is a fast, fully managed, serverless, cloud-native NoSQL document database that simplifies storing, syncing, and querying data for your mobile, web, and IoT apps at global scale. Find out why businesses love it.

Cloud Firestore is a NoSQL document database that simplifies storing, syncing, and querying data for your mobile and web apps at global scale.

Cloud Firestore is a fast, fully managed, serverless, cloud-native NoSQL document database that simplifies storing, syncing, and querying data for your mobile, web, and IoT apps at global scale.

Its client libraries provide live synchronization and offline support, while its security features and integrations with Firebase and Google Cloud Platform (GCP) accelerate building truly serverless apps.

Here’s other stuff it’s good at:

Sync data across devices, on or offline

With Cloud Firestore, your applications can be updated in near real time when data on the back end changes. This is not only great for building collaborative multi-user mobile applications, but also means you can keep your data in sync with individual users who might want to use your app from multiple devices.

With Firebase Realtime Database, we felt we had built the best force-plate testing software on the market. Thanks to Cloud Firestore, in only two weeks, we built a system that’s significantly better and includes features we never thought possible to ship on Day 1.

Chris Wales, CTO, Hawkin Dynamics

Cloud Firestore has full offline support, so you can access and make changes to your data, and those changes will be synced to the cloud when the client comes back online. Built-in offline support leverages local cache to serve and store data, so your app remains responsive regardless of network latency or internet connectivity.

Simple and effortless

Cloud Firestore’s robust client libraries make it easy for you to update and receive new data while worrying less about establishing network connections or unforeseen race conditions. It can scale effortlessly as your app grows. Cloud Firestore allows you to run sophisticated queries against your data. This gives you more flexibility in the way you structure your data and can often mean that you have to do less filtering on the client, which keeps your network calls and data usage more efficient.

Enterprise-grade, scalable NoSQL

Cloud Firestore is a fast and fully managed NoSQL cloud database. It is built to scale and takes advantage of GCP’s powerful infrastructure, with automatic horizontal scaling in and out, in response to your application’s load. Security access controls for data are built in and enable you to handle data validation via a configuration language.

Case Study

Google Migration and BigQuery Brings PedidosYa Closer towards its Goal of Becoming Data-driven

7235

Of your peers have already read this article.

2:00 Minutes

The most insightful time you'll spend today!

PedidosYa, a Latin American leader in the online food ordering space with over 20 million app downloads was looking to democratize data by gaining a secured access and building a comprehensive information ecosystem. PedidosYa was also challenged with its legacy data warehouse that couldn't keep with the brand's increasing analytics demands and was time-consuming and costly. To modernize their data warehouse and transform the analytics environment, PedidosYa chose Google Cloud for its serverless, managed, and integrated data platform, coupled with its seamless integration across open-source solutions. Also, Google Cloud's advanced cost and workload management coupled with its transparent log analytic gave the brand full visibility into any query performance issues to make improvements as they wanted. BigQuery helped PedidosYa achieve cost reduction per query by 5x and leverage its AL/ML-based stack for productivity benefits. Read on to learn more about PedidosYa's BigQuery and Google Cloud migration journey as a step closer towards becoming a data-driven organization.

Editor’s note: PedidosYa is the market leader for online food ordering in Latin America, serving 15 markets and over 400 cities. It’s also one of the largest brands within the German multinational company Delivery Hero SE. With over 20 million app downloads, PedidosYa provides the best online delivery experience through 71,000+ online partners, including restaurants, shops, drugstores, and specialized markets. 

Having constant access to fresh customer data is a key requirement for PedidosYa to improve and innovate our customer’s experience. Our internal stakeholders also require faster insights to drive agile business decisions. Back in early 2020, PedidosYa’s leadership tasked the data team to make the impossible possible. Our team’s mission was to democratize data by providing universal and secure access while creating a comprehensive information ecosystem across PedidosYa. We also had to achieve this goal while keeping costs under control— even during the migration stage and removing operational bottlenecks. 


Challenges with legacy cloud infrastructure

PedidosYa first built its data platform on top of AWS. Our data warehouse ran on Redshift, and our data lake was in S3. We used Presto and Hue as the user interfaces for our data analysts. However, maintaining this infrastructure was a daunting task. Our legacy platform couldn’t keep up with the increasing analytics demands. For example, the data stored on S3 complemented by Presto/Hue required high operational overhead. This was because Presto and our IAM (identity access management) didn’t integrate well in our legacy ecosystem. Managing individual users and mapping IAM roles with groups and Kerberos was operationally time-consuming and costly. Further, sharding access on the S3 files was far too complicated to enable seamless ACLs (access control lists).  

There were also challenges with workload management. Our data warehouse had batch data loaded overnight. If one analyst scheduled a query to run during the overnight ETL (extract, transform, load) workload, it would disrupt the current ETL task. This could stop the entire data pipeline. We’d have to wait until data engineers intervened with a manual fix.

It was also difficult to understand whether a query error was due to performance issues or platform resource exhaustion. This lack of clarity affected our data analysts’ ability to autonomously improve querying efficiency. Data team members needed to manually inspect personal queries looking for performance issues. Also,  the current architecture was prone to a ‘tragedy of the commons’ situation; it was seen as an unlimited and free resource. As a result, it was impossible to disentangle the infrastructure from different stakeholder teams, as all had very different needs. 

The decision to modernize our data warehouse

Given the growing challenges from our legacy platform, our tech team decided to transform our analytics environment with a modern data warehouse. They required the following key criteria from their next data platform: 

  • Scalability – The ability to grow with elastic infrastructure.
  • Cost control – Cost management and transparency. These factors promote efficiency and ownership—both key aspects of data democratization.
  • Metadata management – Intuitive data platform focusing on users’ previous SQL knowledge. Plus, being able to enrich the informational ecosystem with metadata,  to diminish data gatekeepers.
  • Ease of management – The team needed to reduce operational costs with a serverless solution. Data engineers wanted to focus on their key roles rather than acting as database administrators and infrastructure engineers. The team also wanted much higher availability, and to reduce the impact of maintenance windows and vacuum/analysis.
  • Data governance and access rights – With a growing employee base with varying data access requirements, the team needed a simple yet comprehensive solution to understand and track user access to data.

Migrating to Google Cloud

After exploring other alternatives, we concluded Google Cloud had an answer to each of our decision drivers. Google Cloud’s serverless, managed, and integrated data platform, coupled with its seamless integration across open-source solutions, was the perfect answer for our organization. In particular, the natural integration with Airflow as a job orchestrator and Kubernetes for flexible on-demand infrastructure was key.  

We  used Dataflow together with Pub/Sub and Cloud Functions for our data ingestion requirements, which has made our deployment process with Terraform seamless. Because we set up everything in our environment programmatically, operation time has diminished. Google Cloud reduced the deployment process from about 16 hours in our legacy platform to 4 hours.  This is partly due to the friendliness of automating the deployment (such as schema check, load test, table creation, build.) process with Terraform, Cloud Functions, Pub/Sub, Dataflow, and BigQuery on GCP. Input messages processed with Dataflow allow us to abstract and plan the schema changes according to the needs of the functional team. For example, schema changes raise an alarm, and then we can modify the raw layer table schema. By doing this, we ensure that backend modifications that we don’t control do not affect upper layers.

A key reason why we picked Google Cloud was because of its advanced cost and workload management coupled with its transparent log analytics. This information gives us a complete view into any query performance issues to make improvements on the fly. Further, we achieved a significant amount of cost savings by consolidating multiple tools to BigQuery.With BigQuery, we’ve been able to reduce our total cost per query by 5x.

This was due to a number of reasons:

  • Automating pipeline deployment made it much simpler to maintain the data processing processes. 
  • Analysts are conscious about what queries they’re running, resulting in running better, more optimized queries. 
  • Analysts use a Data Studio dashboard to see their queries and all the associated costs. As a result, there’s a lot more transparency for each persona.

 With these changes, we can easily manage and assign costs associated with each workload with their own cost centers using specific Google Cloud projects.

Change management is always challenging. However, BigQuery is intuitive and doesn’t have a steep learning curve from Hue/Hive on SQL basics. BigQuery also allowed the team to expand its capabilities and enabled them to properly work with nested structures, avoiding unnecessary joins and improving query efficiency. Additionally, we now use Data Catalog as our unique point of truth for metadata management. This allows our team to break the data access barriers and enable federation of data across the organization. By using Airflow to orchestrate everything, we keep track of every data stream. With this information, each end user can see their regularly used data entities’ status via the dashboard. This also adds transparency to our everyday data processes.

Finally, with Google Cloud’s IAM rules applied across the different products, data sharing and access is close to a noOps experience. We have programmatically implemented access according to roles and level access within the company. This allows certain pre-validated roles to view more sensitive information. These solutions help drive a more automated data governance experience. 

Up next: Google Cloud AI/ML

The new stack based on BigQuery has created significant productivity gains. Freed from the burden of operational management, PedidosYa’s data team can now focus on adding value through data tools and products.  

  • Our data engineers are better equipped to integrate constantly changing transactional and operational data.
  • The dataOps team can automate the infrastructure and provide autonomy to the end user.
  • Our data quality team can focus on bringing added value to data stakeholders. 
  • Data scientists and data analytics can spend more time analyzing data and less time asking data gatekeepers for data access.

PedidosYa can now democratize data access with a well-governed architecture. We are still at the beginning of our journey, but we are closer to achieving our vision of building a data-driven organization. Up next: expanding our artificial intelligence and machine learning capabilities.

Tune in to Google Cloud’s Applied ML Summit on June 10th, 2021, or listen on-demand later, to learn how to apply groundbreaking machine learning technology in your projects.

How-to

Why and How to Migrate to Google BigQuery

5369

Of your peers have already read this article.

6:30 Minutes

The most insightful time you'll spend today!

Learn how to transition from an on-premises data warehouse to BigQuery on Google Cloud starting from a schema and data transfer overview, to data governance and data pipelines, and finally to reporting and analysis, and performance optimization.

Over the past few decades, organizations have mastered the science of data warehousing. They have increasingly applied descriptive analytics to large quantities of stored data, gaining insight into their core business operations. Conventional Business Intelligence (BI), which focuses on querying, reporting, and Online Analytical Processing, might have been a differentiating factor in the past, either making or breaking a company, but it’s no longer sufficient.

Today, not only do organizations need to understand past events using descriptive analytics, they need predictive analytics, which often uses machine learning (ML) to extract data patterns and make probabilistic claims about the future. The ultimate goal is to develop prescriptive analytics that combine lessons from the past with predictions about the future to automatically guide real-time actions.

Traditional data warehouse practices capture raw data from various sources, which are often Online Transactional Processing (OLTP) systems. Then, a subset of data is extracted in batches, transformed based on a defined schema, and loaded into the data warehouse. Because traditional data warehouses capture a subset of data in batches and store data based on rigid schemas, they are unsuitable for handling real-time analysis or responding to spontaneous queries. Google designed BigQuery in part in response to these inherent limitations.

Innovative ideas are often slowed by the size and complexity of the IT organization that implements and maintains these traditional data warehouses. It can take years and substantial investment to build a scalable, highly available, and secure data warehouse architecture. BigQuery offers sophisticated software as a service (SaaS) technology that can be used for serverless data warehouse operations. This lets you focus on advancing your core business while delegating infrastructure maintenance and platform development to Google Cloud.

BigQuery offers access to structured data storage, processing, and analytics that’s scalable, flexible, and cost effective. These characteristics are essential when your data volumes are growing exponentially—to make storage and processing resources available as needed, as well as to get value from that data. Furthermore, for organizations that are just starting with big data analytics and machine learning, and that want to avoid the potential complexities of on-premises big data systems, BigQuery offers a pay-as-you-go way to experiment with managed services.

With BigQuery, you can find answers to previously intractable problems, apply machine learning to discover emerging data patterns, and test new hypotheses. As a result, you have timely insight into how your business is performing, which enables you to modify processes for better results. In addition, the end user’s experience is often enriched with relevant insights gleaned from big data analysis, as we explain later in this series.

The migration framework

Undertaking a migration can be a complex and lengthy endeavor. Therefore, we recommend adhering to a framework to organize and structure the migration work in phases:

  1. Prepare and discover: Prepare for your migration with workload and use case discovery.
  2. Assess and plan: Assess and prioritize use cases, define measures of success, and plan your migration.
  3. Execute: Iterate the following steps for each use case:
    1. Migrate (offload): Migrate only your data, schema, and downstream business applications.
    2. Migrate (full): Alternatively, migrate the use case fully end-to-end. The same as Migrate (offload), with the addition of the upstream data pipelines.
    3. Verify and validate: Test and validate the migration to assess return on investment.

The following diagram illustrates the recommended framework and shows how the different phases are connected:

For a deeper understanding, read Migrating data warehouses to BigQuery: Introduction and overview

6073

Of your peers have already watched this video.

48:30 Minutes

The most insightful time you'll spend today!

Explainer

Can Your Data Warehouse Handle a 100-Trillion Row Query?

Today’s enterprise demands from data go far beyond the capabilities of traditional data warehousing and for many leaders, the need to digitally transform their businesses is a key driver for data analytics spending.

Businesses want to make real-time decisions from fresh information as well as make future predictions from their data in order to remain competitive.

In this video, Jordan Tigani, Director of Product Management, Google BigQuery reveals the power of Google Cloud’s modern data warehouse, BigQuery, that helps businesses make informed decisions quickly.

In addition, he talks about how big Google BigQuery can get. He shares examples of how one customer ran a query against a giant table of 100 trillion rows. “I think it was something like 19 petabytes of data scanned. It took about took about 20 minutes. It used 39,000 slots, which is about 20,000 cores,” says Tigani.

He also shares examples of how businesses, such as online retailer, Zulily generate real business benefits from being able to query large datasets faster, and more easily than ever–without having to invest time managing infrastructure.

Finally, Amir Aryanpour, Technical Architect, Channel 4, talks abouut how connecting connecting Google BigQuery to other solutions with the Google Cloud Platform, including storage, data visualisation, and a sentiment analysis engine, among others, helped the company.

More Relevant Stories for Your Company

Case Study

WPP Innovates with the Cloud

Unlocking the Power of Data and Creativity withthe Cloud: The WPP Story

How-to

Guide for Measuring Cloud Spanner Performance for Your Custom Workload

Database migration to a new database platform or technology can be daunting for various reasons. One of the common concerns is database performance. It is hard to evaluate database performance early in the evaluation cycle without performing actual data migration and application changes. This becomes even more important in the

Blog

Creating and Using Storage Buckets for Your Data Needs

So, you want to store objects on the cloud? But you're really new to Google Cloud or Cloud Storage and would like someone to walk you through the process step by step? Today is your lucky day!  I will help you understand the big steps involved in setting up and

Explainer

What is BigQuery?

BigQuery is Google Cloud's enterprise data warehouse designed to help you ingest, store, analyze, and visualize big data with ease. Organizations rely on data warehouses to aggregate data from disparate sources, process it, and make it readily available for data analysis that supports their strategic decision-making. You can ingest data

SHOW MORE STORIES