1. Before you begin
Let's imagine you are a Data Engineer at a shoe company called Best Foot Forward (BFF). BFF sells a variety of sneakers and has both retail locations across the US and online ordering. As a result, they work with a variety of different data types:
- Tabular transaction data
- Images of returned shoes
- PDFs with additional data on each return
In this scenario, you need to analyze the return data to understand if there are any patterns in the shoes customers are returning. You'll then use these insights to inform inventory purchasing decisions and forecast future sales volume. BigQuery's AI functions and built-in time series forecasting models simplify the process of analyzing unstructured data to predict trends.
What you'll learn
- Access unstructured data directly in BigQuery
- Securely connect BigQuery to your Cloud Storage resources for AI analysis
- Automatically extract insights from images and PDFs with SQL using BigQuery's built-in AI functions
- Combine new AI-generated insights with your historical transaction data
- Predict future sales trends using the built-in TimesFM model with BigQuery's
AI.FORECASTfunction - Visualize and explore your forecasting results using Data Studio and Connected Sheets
What you'll need
- A Google Cloud project with billing enabled.
- A web browser such as Google Chrome.
- Familiarity with basic SQL concepts.
2. Set up your environment
Create a Google Cloud Project
- In the Google Cloud Console, on the project selector page, select or create a Google Cloud project.
- Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a project.
Start Cloud Shell
Cloud Shell is an in-browser command-line environment running in Google Cloud that comes preloaded with gcloud, Python, and other essential developer tools.
- Click Activate Cloud Shell at the top of the Google Cloud console.
- Once connected to Cloud Shell, verify your active authentication:
gcloud auth list - Confirm your default project is configured:
gcloud config get project - If your project is not set, configure it with:
export GOOGLE_CLOUD_PROJECT=YOUR_GOOGLE_CLOUD_PROJECT gcloud config set project $GOOGLE_CLOUD_PROJECT
Enable required Google Cloud APIs
Enable the required Google Cloud APIs in Cloud Shell:
- Gemini API (
aiplatform.googleapis.com): Allows BigQuery's AI functions to call Gemini for analyzing images and PDFs. - BigQuery API (
bigquery.googleapis.com): Lets you create datasets, tables, and run SQL queries. - Cloud Storage API (
storage.googleapis.com): Allows access to the dataset's shoe images, PDF return slips, and CSV transaction data in Cloud Storage. - BigQuery Connection API (
bigqueryconnection.googleapis.com): Lets you create a Cloud resource connection so BigQuery can securely access Cloud Storage objects and external AI models.
gcloud services enable \
aiplatform.googleapis.com \
bigquery.googleapis.com \
storage.googleapis.com \
bigqueryconnection.googleapis.com
Verify that the operation completes successfully:
Operation "operations/..." finished successfully.
Set environment variables
Configure environment variables for your Google Cloud project and location:
export GOOGLE_CLOUD_PROJECT=$(gcloud config get-value project)
export GOOGLE_CLOUD_LOCATION="us"
3. Explore the dataset
To complete this lab, you'll be using a publicly available dataset in Cloud Storage with fake transaction and returns data. This is the structure of the Cloud Storage bucket we're working with:
gs://sample-data-and-media/retail-shoes/sneaker_returnsimages: Images of shoes being returned.pdfs: Data corresponding with each returned shoe image containing the customer's name, purchase date, and reason for return.
transactionstransactions.csv: You'll load this into a BigQuery table and combine it with AI insights on the unstructured data.
Previewing the images
First, navigate to the Cloud Storage bucket:

You can click into individual images and scroll to the Preview button to preview them.

These are images customers have taken of the shoes they would like to return. Notice that the file name of each image contains the return ID. You'll use this to connect each image to the PDF return slip containing more details on the return.

Previewing the PDFs
Next, navigate to the retail-shoes/sneaker_returns/pdfs directory in the Cloud Storage bucket. Click on a few PDF files to preview the return data. You can do this by clicking on the Authenticated URL in Cloud Storage:

You'll see return slips like the following:

Transaction data
The data in retail-shoes/transactions directory contains the following columns:
transaction_id: stringpurchase_date: dateproduct_sku: stringproduct_name: stringstore_location: stringprice: float64return_id: string
You will upload this to BigQuery in a later step. First, you'll work with the unstructured data.
4. Create BigQuery object tables
In order to get AI insights from our unstructured image and PDF data, you need to create references to those Cloud Storage objects in BigQuery. Rather than loading those objects directly into BigQuery tables, you can use BigQuery's object tables to do this.
Create a Cloud Resource Connection
Before you create an object table, you need to create a Cloud resource connection. This is a secure connection between BigQuery and other services. In this case, you'll use the connection to connect BigQuery to Cloud Storage, but you can also use it to connect to services outside of Google Cloud.
In the BigQuery section of the Cloud console, click on Pipelines and connections on the left nav:

Then click Create to create a new connection.

Choose External connections, then click Create connection. Select Agent Platform remote models, remote functions, Lakehouse and Spanner (Cloud Resource) as the type, give your connection the name bff, select Multi-region, and us for the region. You can optionally give it a "Friendly name" of bff and a description:

Click Create and you will see your connection displayed on the Connections tab.
Next we need to give this connection some permissions so it can access Cloud Storage and Agent Platform. To do this, click into your connection and copy its service account (redacted below):

You'll need to give this service account access to Cloud Storage and Agent Platform for the connection to work. To do this, navigate to the IAM section of the Cloud console. Click Grant access and paste the service account from your resource connection into the "New principals" text box. Assign it two roles: Storage Object Viewer and Agent Platform user. Then click Save.

Create the object tables
Before you create your object tables, you need a BigQuery dataset to store them in. Navigate back to the BigQuery section of the console. Click on the 3-dot menu next to your project name and then Create dataset:

Give the dataset the ID bff, and select US as the region. Then click Create dataset.
With a BigQuery dataset, and your BigQuery <> Cloud Storage resource connection established, you can now create the object tables. You'll create two object tables: one for the images and one for the PDFs.
Navigate to BigQuery Studio and in the Untitled query box, paste the following:
-- 1. Create the Object Table for the Sneaker Images
CREATE OR REPLACE EXTERNAL TABLE `bff.return_images`
WITH CONNECTION `us.bff`
OPTIONS (
object_metadata = 'SIMPLE',
uris = ['gs://sample-data-and-media/retail-shoes/sneaker_returns/images/*']
);
-- 2. Create the Object Table for the PDF Return Slips
CREATE OR REPLACE EXTERNAL TABLE `bff.return_pdfs`
WITH CONNECTION `us.bff`
OPTIONS (
object_metadata = 'SIMPLE',
uris = ['gs://sample-data-and-media/retail-shoes/sneaker_returns/pdfs/*']
);
Notice that you didn't need to specify any column names when creating the object table. BigQuery does that automatically for us and includes the following default columns in object tables. You can look at the newly created tables by clicking on them in the left nav under your bff dataset.

You can preview a few rows of data in the image table by clicking Query and typing the following into the query box:
SELECT * FROM `bff.return_images` LIMIT 10

5. Get insights on the unstructured multimodal data
Now that you've loaded your unstructured data into BigQuery via object tables, now it's time to use BigQuery's AI functions to get insights on that data.
Analyze shoe images
Instead of manually reviewing each return image to classify the reason for the return, you'll use BigQuery's AI.GENERATE function to analyze your images. With your image data in object tables, the next thing you need to do is run the following SQL query in BigQuery Studio. The CREATE OR REPLACE TABLE line will save the output from the query to a new table, which you'll use in the next step.
This query takes around 5-10 minutes to run.
CREATE OR REPLACE TABLE `bff.image_insights`
OPTIONS (
labels = [('goog-yardstick-devrel', '565014385')]
) AS
SELECT
REGEXP_EXTRACT(uri, r'(RET-\d+)') AS return_id,
AI.GENERATE(
('You are a QA inspector for Best Foot Forward. Look at this image of a returned sneaker. What is the primary visible defect? Choose exactly one from this list: [Sole Separation, Scuffed/Dirty, No Defect]. Respond with just the category name.', ref),
endpoint => 'gemini-3.8-flash',
connection_id => 'us.bff'
).result AS defect_category
FROM `bff.return_images`;
Let's dive into the magic behind this query:
- The first string you pass to
AI.GENERATEis the prompt that will be sent to Gemini (specified asendpoint) for each image in your object table - The
refpassed toAI.GENERATErefers to thereffield in the images Object Table, which contains the image URI in Cloud Storage - The response from
AI.GENERATEis returned asresult, which you save to a column in the output table calleddefect_category
When the query completes, navigate to the newly created image_insights table and preview the data by clicking the Go to table button and then the Preview tab.
To verify that the model correctly classified your images, run this query to return a single image the model classified as "Scuffed/Dirty" and then check the image to verify:
SELECT
return_id,
defect_category
FROM
`bff.image_insights`
WHERE defect_category LIKE '%Scuffed%'
ORDER BY return_id
LIMIT 1
Your results will look like the following (actual results may vary):

Next, navigate to the bucket and find the image ID that your query returned to confirm it contains a scuffed shoe. For example, here is the Cloud Storage page for sample-data-and-media/retail-shoes/sneaker_returns/images/RET-1081_shoe.png returned in the above query.
Analyze PDF return slips
You'll run a similar query on the PDF return slips. Paste this into a new BigQuery Studio tab. This query sends a request to Gemini for each PDF to classify the sentiment of the customer's comments. Notice that here you pass an output_schema to AI.GENERATE, which is helpful in this case since you're extracting two pieces of information from the PDFs: sentiment and return reason.
This query takes around 5-10 minutes to run.
CREATE OR REPLACE TABLE `bff.pdf_insights`
OPTIONS (
labels = [('goog-yardstick-devrel', '565014385')]
) AS
SELECT
REGEXP_EXTRACT(uri, r'(RET-\d+)') AS return_id,
pdf_data.sentiment AS customer_sentiment,
pdf_data.reason AS extracted_reason
FROM (
SELECT
uri,
AI.GENERATE(
('Read this return authorization slip and extract the sentiment (POSITIVE, NEUTRAL, or NEGATIVE) and the reason (a short 2-3 word phrase describing the return reason, like "Wrong Size" or "Defective").', ref),
endpoint => 'gemini-3.8-flash',
connection_id => 'us.bff',
output_schema => 'sentiment STRING, reason STRING'
).*
FROM `bff.return_pdfs`
) AS pdf_data;
You can preview the data in the pdf_insights table you just created by running this query on the newly created table:
SELECT * FROM `bff.pdf_insights`
LIMIT 10
Similar to the verification you did on the image_insights table, run this query to return a single row and then double-check the PDF to confirm the classification is correct:
SELECT
return_id,
extracted_reason
FROM `bff.pdf_insights`
WHERE extracted_reason
LIKE '%Defective%'
ORDER BY return_id
LIMIT 1
You'll see a result that looks something like this:

Navigate to the PDF file returned in your query to confirm the return slip contains a complaint about a defective shoe.
6. Combine multimodal insights with forecasting
Now that you've used BigQuery's AI functions to add label classifications to your image and PDF data, you need to find a way to join this with your tabular transaction data.
Create a BigQuery table with the transaction data
First, you'll create a new BigQuery table using the public transactions.csv file you previewed in the first step. To do this, find your dataset in the left nav of the BigQuery console and click the 3-dot menu next to it, then click Create table.

In the dropdown for Create table from, select Google Cloud Storage. In the file box, paste the public transactions file: sample-data-and-media/retail-shoes/transactions/transactions.csv. Select CSV for File format. Name the table transactions, and select the Auto-detect box under Schema. Leave the rest of the defaults selected and click Create table.

Join AI insights with the transaction data
With all of your data now in BigQuery, it's time to join our Gemini-generated insights with the structured transactions data.
In a new BigQuery Studio tab, run the following:
SELECT
t.product_name,
img.defect_category,
COUNT(t.transaction_id) as total_returns
FROM
`bff.transactions` t
JOIN
`bff.image_insights` img
ON t.return_id = img.return_id
GROUP BY
t.product_name,
img.defect_category
ORDER BY
total_returns DESC;
This query joins the transaction data with our image insights table on the return_id column to see if there are any correlations between product type and defect category. The results from running the above query should look something like this (exact results will vary):

If you look at the data, you'll notice the following trends:
- 20 of the Right Foot Classic shoe returns were all because they were scuffed and dirty
- 40 BFF Sole-Mate Low returns had no defect
- 40 of the Fast Forward High-Top returns were because of sole separation
This query provided a lot of business insights! Rather than manually analyzing each return image and PDF slip, you can conclude the following based on the query results:
- There seems to be a warehouse or packaging issue with the Right Foot Classic shoe since they're arriving dirty to customers. You should investigate this issue but don't need to pull the shoe from your inventory.
- None of the BFF Sole-Mate Low returns were defective, so further analysis is needed on the reason for these returns
- You should pull Fast Forward High-Top shoes from your inventory since they have a manufacturing defect. As a result, you should not include this product in the time-series forecast query you'll run in the next section.
Next, you should do further analysis to determine why BFF Sole-Mate Low shoes were returned if they didn't have any defects. To do that, run a query on the pdf_insights table joined with the return_id on the transactions table to identify the return reasons only for the BFF Sole-Mate Low shoe:
SELECT
t.product_name,
pdf.extracted_reason,
COUNT(t.transaction_id) AS total_returns
FROM
`bff.transactions` t
JOIN
`bff.pdf_insights` pdf
ON t.return_id = pdf.return_id
WHERE
t.product_name = 'BFF Sole-Mate Low'
GROUP BY
t.product_name,
pdf.extracted_reason
ORDER BY
total_returns DESC;
You should see something like this:

Aha! Most of the customers who returned this shoe got the wrong size. This is a straightforward fix, you can have the web team add a note to the product page that this shoe runs small. You don't need to update your inventory for this shoe.
To summarize, your AI insights have confirmed:
- You'll remove the defective Fast Forward High-Tops from your inventory, you don't need to run demand forecasting for this shoe since you'll pause any manufacturing orders on it
- Adjustments for the other shoe types can be made without affecting your purchasing or demand forecasting
7. Zero-shot forecasting in BigQuery with TimesFM
Now that you've analyzed the transaction data together with the image and PDF insights, you can use this to forecast future sales volume to determine how many of each shoe type to purchase from your manufacturer. Historically, to do this you'd need to use your data to train your own custom time-series model.
Now you can use Google's foundational TimesFM model directly in BigQuery to do zero-shot time-series forecasting.
What does "zero-shot" mean here? Rather than training a new model on your own data, you can make use of TimesFM to take care of the forecasting for you by simply giving it the transaction data you have.
Isolate the time series data
Before you run your forecasting query, you should create a new table that includes only the purchase date, product name, and total sales for each day. In this query you want to filter out Fast Forward High-Top since you won't be ordering or selling this shoe for now:
CREATE OR REPLACE TABLE `bff.daily_sales_timeseries`
OPTIONS (
labels = [('goog-yardstick-devrel', '565014385')]
) AS
SELECT
purchase_date,
product_name,
COUNT(transaction_id) AS total_shoes_sold
FROM
`bff.transactions`
WHERE
product_name != 'Fast Forward High-Top' -- Filtering out the defective shoe
GROUP BY
purchase_date,
product_name
ORDER BY
purchase_date ASC;
When this query completes, go to the newly created table and click the Preview tab. You'll see this table contains data on the total number of shoes sold for each type per day.

Run the forecasting query with TimesFM using AI.FORECAST
Now that you've isolated your time-series data, you can use it to predict future sales volume. When you run AI.FORECAST in BigQuery, it uses the TimesFM model under the hood without any additional configuration required on your part. The following query tells TimesFM how to read our historical sales data:
timestamp_coltells TimesFM which column has the date.data_coltells TimesFM which metric from our data we want to forecast. In this case, the number of shoes sold.id_colstells TimesFM to slice the forecast on a specific column, in this case product name. When we run the query, the model will generate separate forecasts for each shoe type.
SELECT *,
-- This lets you color-code historical data vs. future predictions in the next step
CONCAT(product_name, ' - ', time_series_type) AS product_phase
FROM (
SELECT *
FROM AI.FORECAST(
TABLE `bff.daily_sales_timeseries`,
horizon => 30,
timestamp_col => 'purchase_date',
data_col => 'total_shoes_sold',
id_cols => ['product_name'],
output_historical_time_series => TRUE
)
)
-- Zoom in: Only show the last 90 days of history + the new 30-day forecast
WHERE CAST(time_series_timestamp AS DATE) >= DATE_SUB((SELECT MAX(purchase_date) FROM `bff.daily_sales_timeseries`), INTERVAL 90 DAY)
The query results include 90 days of historical data and 30 days of predicted future sales for each shoe type. In the query results for future dates, the time_series_data column includes the predicted shoe sales. There are also columns for the prediction confidence, and the prediction interval upper and lower bounds. You can look at the query results, however, time-series data is easier to understand when visualized as a line chart. In the next step you'll create a visualization of the forecasting data.
8. Visualize the results
Visualize with Data Studio
You'll use Data Studio to create a time series chart of your query results from the previous step. From your query results page, click the Open in dropdown on the right and select Data Studio.

When you click to open Data Studio, you'll see a warning about data access. Click Acknowledge. Then you'll see a modal to grant consent to personalize your Data Studio experience. Click Allow.
When you are redirected to Data Studio, it will generate a few default charts for you. You can delete them. Then click the Add a chart button from the top menu and select the first icon under Time series:

Your BigQuery results should already be selected as the data source. Under Dimension - X axis, select time_series_timestamp. Then under Breakdown dimension select product_phase. Under Metric - Y axis select time_series_data. Your chart will look something like this:

This chart shows that TimesFM picked up on the seasonal trends in our historical sales data. You can see clear spikes on the weekends, and you can use the projected sales to determine how many of each shoe to order from the manufacturer. Even more, you did this all without having to train or fine-tune a custom model - hence zero-shot!
Optional: Visualize results in Connected Sheets
If you prefer to work in spreadsheets, you can also visualize your forecasting results using Connected Sheets. Connected Sheets offers many features for interacting with your BigQuery data directly from a familiar spreadsheet environment.
To export your data to a Google Sheet, navigate to the results page for the AI.FORECAST query you ran above. Then click Open In and select Connected Sheets.

On the menu bar under "Connected sheet 1", select Pivot table.

On the Create pivot table box, leave New sheet selected and click Create:

On the right side Pivot table editor, configure the following and leave the defaults selected for each configuration:
- Click the Add button next to Rows and set it to
time_series_timestamp - Click the Add button next to Columns and set it to
product_phase - Click the Add button next to Values and set it to
time_series_data

Click the Apply button at the bottom right of the pivot table editor. When it loads you'll see a sheet automatically generated that includes your correctly formatted time series data.
With the time series data formatted in your sheet, you can now visualize it with a chart. From the top menu select Insert > Chart. You should see a chart automatically appear on your sheet:

You can change the default title to "BFF: Shoe Sales Forecast". With just a few clicks, you've exported your BigQuery data to Google Sheets and generated a chart you can share with your business teams. Nice work!
9. Clean up resources
Delete cloud resources
If you'd like to delete the resources created in this lab to avoid recurring charges, in Cloud Shell, run the following gcloud command to first delete the bff BigQuery dataset.
bq rm -r -f -d bff
Next, delete the BigQuery Cloud resource connection:
bq rm --connection --location=us bff
10. Congratulations
Congratulations! You've now learned how to use BigQuery's AI functions to get insights on large amounts of multimodal data, how to join that multimodal data with tabular data, and then perform demand forecasting using BigQuery's built-in TimesFM model.
What you covered
- Accessed unstructured data using BigQuery Object Tables
- Configured a Cloud Resource Connection for secure AI analysis
- Used AI functions (
AI.GENERATE) to automatically extract insights from images and PDFs - Combined AI-generated insights with structured transaction data
- Forecasted future sales with zero-shot models (
AI.FORECAST) - Visualized forecasting results in Data Studio and Connected Sheets
Next steps
To learn more about the products you used in this lab, check out the following resources: