Perform semantic analysis with managed AI functions

This tutorial shows you how to use BigQuery ML managed AI functions to perform semantic analysis on customer feedback.

Objectives

In this tutorial, you:

  • Create a dataset and load sentiment data into a table
  • Create a Cloud Resource Connection
  • Use the following AI functions to perform semantic analysis:
    • AI.IF: to filter your data with natural language conditions
    • AI.SCORE: to rate input by sentiment
    • AI.CLASSIFY: to classify input into user-defined categories

Costs

This tutorial uses billable components of Google Cloud, including the following:

  • BigQuery
  • BigQuery ML

For more information on BigQuery costs, see the BigQuery pricing page.

For more information on BigQuery ML costs, see BigQuery ML pricing.

Before you begin

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  5. If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.

  6. Enable the BigQuery API and BigQuery Connection API APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

    For new projects, the BigQuery API is automatically enabled.

  7. Optional: Enable billing for the project. If you don't want to enable billing or provide a credit card, the steps in this document still work. BigQuery provides you a sandbox to perform the steps. For more information, see Enable the BigQuery sandbox.

Required roles

To get the permissions that you need to use AI functions, ask your administrator to grant you the following IAM roles on the project:

For more information about granting roles, see Manage access to projects, folders, and organizations.

You might also be able to get the required permissions through custom roles or other predefined roles.

Create sample data

To create a dataset called my_dataset for this tutorial, run the following query.

CREATE SCHEMA my_dataset OPTIONS (location = 'LOCATION');

Next, create a table called customer_feedback that contains sample customer reviews for a device:

CREATE TABLE my_dataset.customer_feedback AS (
  SELECT
    *
  FROM
    UNNEST( [STRUCT<review_id INT64, review_text STRING> 
      (1, "The battery life is incredible, and the screen is gorgeous! Best phone I've ever had. Totally worth the price."),
      (2, "Customer support was a nightmare. It took three weeks for my order to arrive, and when it did, the box was damaged. Very frustrating!"),
      (3, "The product does exactly what it says on the box. No complaints, but not exciting either."),
      (4, "I'm so happy with this purchase! It arrived early and exceeded all my expectations. The quality is top-notch, although the setup was a bit tricky."),
      (5, "The price is a bit too high for what you get. The material feels cheap and I'm worried it won't last. Service was okay."),
      (6, "Absolutely furious! The item arrived broken, and getting a refund is proving impossible. I will never buy from them again."),
      (7, "This new feature for account access is confusing. I can't find where to update my profile. Please fix this bug!"),
      (8, "The shipping was delayed, but the support team was very helpful and kept me informed. The product itself is great, especially for the price.") 
      ])
);

Create a connection

Create a Cloud resource connection and get the connection's service account.

Select one of the following options:

Console

  1. Go to the BigQuery page.

    Go to BigQuery

  2. In the Explorer pane, click Add data:

    The Add data UI element.

    The Add data dialog opens.

  3. In the Filter By pane, in the Data Source Type section, select Business Applications.

    Alternatively, in the Search for data sources field, you can enter Vertex AI.

  4. In the Featured data sources section, click Vertex AI.

  5. Click the Vertex AI Models: BigQuery Federation solution card.

  6. In the Connection type list, select Vertex AI remote models, remote functions, BigLake and Spanner (Cloud Resource).

  7. In the Connection ID field, enter a name for your connection.

  8. Click Create connection.

  9. Click Go to connection.

  10. In the Connection info pane, copy the service account ID for use in a later step.

bq

  1. In a command-line environment, create a connection:

    bq mk --connection --location=REGION --project_id=PROJECT_ID \
        --connection_type=CLOUD_RESOURCE CONNECTION_ID

    The --project_id parameter overrides the default project.

    Replace the following:

    • REGION: your connection region
    • PROJECT_ID: your Google Cloud project ID
    • CONNECTION_ID: an ID for your connection

    When you create a connection resource, BigQuery creates a unique system service account and associates it with the connection.

    Troubleshooting: If you get the following connection error, update the Google Cloud SDK:

    Flags parsing error: flag --connection_type=CLOUD_RESOURCE: value should be one of...
    
  2. Retrieve and copy the service account ID for use in a later step:

    bq show --connection PROJECT_ID.REGION.CONNECTION_ID

    The output is similar to the following:

    name                          properties
    1234.REGION.CONNECTION_ID     {"serviceAccountId": "connection-1234-9u56h9@gcp-sa-bigquery-condel.iam.gserviceaccount.com"}
    

Terraform

Use the google_bigquery_connection resource.

To authenticate to BigQuery, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

The following example creates a Cloud resource connection named my_cloud_resource_connection in the US region:


# This queries the provider for project information.
data "google_project" "default" {}

# This creates a cloud resource connection in the US region named my_cloud_resource_connection.
# Note: The cloud resource nested object has only one output field - serviceAccountId.
resource "google_bigquery_connection" "default" {
  connection_id = "my_cloud_resource_connection"
  project       = data.google_project.default.project_id
  location      = "US"
  cloud_resource {}
}

To apply your Terraform configuration in a Google Cloud project, complete the steps in the following sections.

Prepare Cloud Shell

  1. Launch Cloud Shell.
  2. Set the default Google Cloud project where you want to apply your Terraform configurations.

    You only need to run this command once per project, and you can run it in any directory.

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID

    Environment variables are overridden if you set explicit values in the Terraform configuration file.

Prepare the directory

Each Terraform configuration file must have its own directory (also called a root module).

  1. In Cloud Shell, create a directory and a new file within that directory. The filename must have the .tf extension—for example main.tf. In this tutorial, the file is referred to as main.tf.
    mkdir DIRECTORY && cd DIRECTORY && touch main.tf
  2. If you are following a tutorial, you can copy the sample code in each section or step.

    Copy the sample code into the newly created main.tf.

    Optionally, copy the code from GitHub. This is recommended when the Terraform snippet is part of an end-to-end solution.

  3. Review and modify the sample parameters to apply to your environment.
  4. Save your changes.
  5. Initialize Terraform. You only need to do this once per directory.
    terraform init

    Optionally, to use the latest Google provider version, include the -upgrade option:

    terraform init -upgrade

Apply the changes

  1. Review the configuration and verify that the resources that Terraform is going to create or update match your expectations:
    terraform plan

    Make corrections to the configuration as necessary.

  2. Apply the Terraform configuration by running the following command and entering yes at the prompt:
    terraform apply

    Wait until Terraform displays the "Apply complete!" message.

  3. Open your Google Cloud project to view the results. In the Google Cloud console, navigate to your resources in the UI to make sure that Terraform has created or updated them.

Grant permissions to the connection's service account

Grant the connection's service account the Vertex AI User role. You must grant this role in the same project you created or selected in the Before you begin section. Granting the role in a different project results in the error bqcx-1234567890-xxxx@gcp-sa-bigquery-condel.iam.gserviceaccount.com does not have the permission to access resource.

To grant the role, follow these steps:

  1. Go to the IAM & Admin page.

    Go to IAM & Admin

  2. Click Grant Access.

  3. In the New principals field, enter the service account ID that you copied earlier.

  4. In the Select a role field, choose Vertex AI, and then select Vertex AI User role.

  5. Click Save.

Categorize overall sentiment

It can be helpful to extract the overall sentiment expressed in text to support use cases such as the following:

  • Gauge customer satisfaction from reviews.
  • Monitor brand perception on social media.
  • Prioritize support tickets based on how upset users are.

The following query shows how to use the AI.CLASSIFY function to classify reviews from the customer_feedback table as positive, negative, or neutral:

SELECT
  review_id,
  review_text,
  AI.CLASSIFY(
    review_text,
    categories => ['positive', 'negative', 'neutral'],
    connection_id => "CONNECTION_ID") AS sentiment
FROM
  my_dataset.customer_feedback;

The result looks similar to the following:

+-----------+------------------------------------------+-----------+
| review_id | review_text                              | sentiment |
+-----------+------------------------------------------+-----------+
| 7         | This new feature for account access is   | negative  |
|           | confusing. I can't find where to update  |           |
|           | my profile. Please fix this bug!         |           |
+-----------+------------------------------------------+-----------+
| 4         | "I'm so happy with this purchase! It     | positive  |
|           | arrived early and exceeded all my        |           |
|           | expectations. The quality is top-notch,  |           |
|           | although the setup was a bit tricky."    |           |
+-----------+------------------------------------------+-----------+
| 2         | "Customer support was a nightmare. It    | negative  |
|           | took three weeks for my order to         |           |
|           | arrive, and when it did, the box was     |           |
|           | damaged. Very frustrating!"              |           |
+-----------+------------------------------------------+-----------+
| 1         | "The battery life is incredible, and     | positive  |
|           | the screen is gorgeous! Best phone I've  |           |
|           | ever had. Totally worth the price."      |           |
+-----------+------------------------------------------+-----------+
| 8         | "The shipping was delayed, but the       | positive  |
|           | support team was very helpful and kept   |           |
|           | me informed. The product itself is       |           |
|           | great, especially for the price."        |           |
+-----------+------------------------------------------+-----------+
| 5         | The price is a bit too high for what     | negative  |
|           | you get. The material feels cheap and    |           |
|           | I'm worried it won't last. Service was   |           |
|           | okay.                                    |           |
+-----------+------------------------------------------+-----------+
| 3         | "The product does exactly what it says   | neutral   |
|           | on the box. No complaints, but not       |           |
|           | exciting either."                        |           |
+-----------+------------------------------------------+-----------+
| 6         | "Absolutely furious! The item arrived    | negative  |
|           | broken, and getting a refund is proving  |           |
|           | impossible. I will never buy from them   |           |
|           | again."                                  |           |
+-----------+------------------------------------------+-----------+

Analyze aspect-based sentiment

If an overall sentiment such as positive or negative isn't sufficient for your use case, you can analyze a specific aspect of the meaning of text. For example, you might want to understand a user's attitude towards the quality of the product, without regard for their thoughts on its price. You can even ask for a custom value to indicate that a particular aspect doesn't apply.

The following example shows how to use the AI.SCORE function to rate user sentiment from 1 to 10 based on how favorable each review in the customer_feedback table is toward price, customer service, and quality. The function returns the custom value -1 in cases where an aspect isn't mentioned in the review so that you can filter these out later.

SELECT
  review_id,
  review_text,
  AI.SCORE(
    ("Score 0.0 to 10 on positive sentiment about PRICE for review: ", review_text,
    "If price is not mentioned, return -1.0"),
    connection_id => "CONNECTION_ID") AS price_score,
  AI.SCORE(
    ("Score 0.0 to 10 on positive sentiment about CUSTOMER SERVICE for review: ", review_text,
    "If customer service is not mentioned, return -1.0"),
    connection_id => "CONNECTION_ID") AS service_score,
  AI.SCORE(
    ("Score 0.0 to 10 on positive sentiment about QUALITY for review: ", review_text,
    "If quality is not mentioned, return -1.0"),
    connection_id => "CONNECTION_ID") AS quality_score
FROM
  my_dataset.customer_feedback
LIMIT 3;

The result looks similar to the following:

+-----------+------------------------------------------+--------------+---------------+---------------+
| review_id | review_text                              |    price_score | service_score | quality_score |
+-----------+------------------------------------------+--------------+---------------+---------------+
| 4         | "I'm so happy with this purchase! It     | -1.0         | -1.0          | 9.5           |
|           | arrived early and exceeded all my        |              |               |               |
|           | expectations. The quality is top-notch,  |              |               |               |
|           | although the setup was a bit tricky."    |              |               |               |
+-----------+------------------------------------------+--------------+---------------+---------------+
| 8         | "The shipping was delayed, but the       |  9.0         |  8.5          | 9.0           |
|           | support team was very helpful and kept   |              |               |               |
|           | me informed. The product itself is       |              |               |               |
|           | great, especially for the price."        |              |               |               |
+-----------+------------------------------------------+--------------+---------------+---------------+
| 6         | "Absolutely furious! The item arrived    | -1.0         |  1.0          | 0.0           |
|           | broken, and getting a refund is proving  |              |               |               |
|           | impossible. I will never buy from them   |              |               |               |
|           | again."                                  |              |               |               |
+-----------+------------------------------------------+--------------+---------------+---------------+

Detect emotions

In addition to positive or negative sentiment, you can classify text based on specific emotions that you select. This is useful when you want to gain a better understanding of user responses, or to flag highly emotional feedback for review.

SELECT
  review_id,
  review_text,
  AI.CLASSIFY(
    review_text,
    categories => ['joy', 'anger', 'sadness', 'surprise', 'fear', 'disgust', 'neutral', 'other'],
    connection_id => "CONNECTION_ID"
  ) AS emotion
FROM
  my_dataset.customer_feedback;

The result looks similar to the following:

+-----------+------------------------------------------+---------+
| review_id | review_text                              | emotion |
+-----------+------------------------------------------+---------+
| 2         | "Customer support was a nightmare. It    | anger   |
|           | took three weeks for my order to         |         |
|           | arrive, and when it did, the box was     |         |
|           | damaged. Very frustrating!"              |         |
+-----------+------------------------------------------+---------+
| 7         | This new feature for account access is   | anger   |
|           | confusing. I can't find where to update  |         |
|           | my profile. Please fix this bug!         |         |
+-----------+------------------------------------------+---------+
| 4         | "I'm so happy with this purchase! It     | joy     |
|           | arrived early and exceeded all my        |         |
|           | expectations. The quality is top-notch,  |         |
|           | although the setup was a bit tricky."    |         |
+-----------+------------------------------------------+---------+
| 1         | "The battery life is incredible, and     | joy     |
|           | the screen is gorgeous! Best phone I've  |         |
|           | ever had. Totally worth the price."      |         |
+-----------+------------------------------------------+---------+
| 8         | "The shipping was delayed, but the       | joy     |
|           | support team was very helpful and kept   |         |
|           | me informed. The product itself is       |         |
|           | great, especially for the price."        |         |
+-----------+------------------------------------------+---------+
| 5         | The price is a bit too high for what     | sadness |
|           | you get. The material feels cheap and    |         |
|           | I'm worried it won't last. Service was   |         |
|           | okay.                                    |         |
+-----------+------------------------------------------+---------+
| 3         | "The product does exactly what it says   | neutral |
|           | on the box. No complaints, but not       |         |
|           | exciting either."                        |         |
+-----------+------------------------------------------+---------+
| 6         | "Absolutely furious! The item arrived    | anger   |
|           | broken, and getting a refund is proving  |         |
|           | impossible. I will never buy from them   |         |
|           | again."                                  |         |
+-----------+------------------------------------------+---------+

Categorize reviews by topic

You can use the AI.CLASSIFY function to group reviews into predefined topics. For example, you can do the following:

  • Discover common themes in customer feedback.
  • Organize documents by subject matter.
  • Route support tickets by topic.

The following example shows how to classify customer feedback into various types such as billing issue or account access and then count how many reviews belong to each category:

SELECT
  AI.CLASSIFY(
    review_text,
    categories => ['Billing Issue', 'Account Access',
                   'Product Bug', 'Feature Request',
                   'Shipping Delay', 'Other'],
    connection_id => "CONNECTION_ID") AS topic,
    COUNT(*) AS number_of_reviews,
FROM
  my_dataset.customer_feedback
GROUP BY topic
ORDER BY number_of_reviews DESC;

The result looks similar to the following:

+----------------+-------------------+
| topic          | number_of_reviews |
+----------------+-------------------+
| Other          | 5                 |
| Shipping Delay | 2                 |
| Product Bug    | 1                 |
+----------------+-------------------+

Identify semantically similar reviews

You can use the AI.SCORE function to assess how semantically similar two pieces of text are by asking it to rate similarity of meaning. This can help you with tasks such as the following:

  • Find duplicate or near-duplicate entries.
  • Group similar pieces of feedback.
  • Power semantic search applications.

The following query finds reviews that discuss difficulty setting up the product:

SELECT
  review_id,
  review_text,
  AI.SCORE(
    (
      """How similar is the review to the concept of 'difficulty in setting up the product'?
         A higher score indicates more similarity. Review: """,
      review_text),
    connection_id => "CONNECTION_ID") AS setup_difficulty
FROM my_dataset.customer_feedback
ORDER BY setup_difficulty DESC
LIMIT 2;

The result looks similar to the following:

+-----------+------------------------------------------+------------------+
| review_id | review_text                              | setup_difficulty |
+-----------+------------------------------------------+------------------+
| 4         | "I'm so happy with this purchase! It     | 3                |
|           | arrived early and exceeded all my        |                  |
|           | expectations. The quality is top-notch,  |                  |
|           | although the setup was a bit tricky."    |                  |
+-----------+------------------------------------------+------------------+
| 7         | This new feature for account access is   | 1                |
|           | confusing. I can't find where to update  |                  |
|           | my profile. Please fix this bug!         |                  |
+-----------+------------------------------------------+------------------+

You can also use the AI.IF function to find reviews that relate to text:

SELECT
  review_id,
  review_text
FROM my_dataset.customer_feedback
WHERE
  AI.IF(
    (
      "Does this review discuss difficulty setting up the product? Review: ",
      review_text),
    connection_id => "CONNECTION_ID");

Combine functions

It can be helpful to combine these functions in a single query. For example, the following query first filters reviews for negative sentiment, and then classifies them by the type of frustration:

SELECT
  review_id,
  review_text,
  AI.CLASSIFY(
    review_text,
    categories => [
      'Poor Quality', 'Bad Customer Service', 'High Price', 'Other Negative'],
    connection_id => "CONNECTION_ID") AS negative_topic
FROM my_dataset.customer_feedback
WHERE
  AI.IF(
    ("Does this review express a negative sentiment? Review: ", review_text),
    connection_id => "CONNECTION_ID");

Create reusable prompt UDFs

To keep your queries readable, you can reuse your prompt logic by creating user-defined functions. The following query creates a function to detect negative sentiment by calling AI.IF with a custom prompt. Then, it calls that function to filter by negative review.

CREATE OR REPLACE FUNCTION my_dataset.is_negative_sentiment(review_text STRING)
RETURNS BOOL
AS (
    AI.IF(
      ("Does this review express a negative sentiment? Review: ", review_text),
      connection_id => "CONNECTION_ID")
);

SELECT
  review_id,
  review_text
FROM my_dataset.customer_feedback
WHERE my_dataset.is_negative_sentiment(review_text);

Clean up

To avoid incurring charges, you can either delete the project that contains the resources that you created, or keep the project and delete the individual resources.

Delete your project

To delete the project:

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

Delete your dataset

To delete the dataset and all resources that it contains, including all tables and functions, run the following query:

DROP SCHEMA my_dataset CASCADE;