Eseguire l'analisi semantica con le funzioni AI gestite

Questo tutorial mostra come utilizzare le funzioni AI gestite di BigQuery ML per eseguire l'analisi semantica dei feedback dei clienti.

Obiettivi

In questo tutorial:

  • Crea un set di dati e carica i dati del sentiment in una tabella.
  • Utilizza le seguenti funzioni AI per eseguire l'analisi semantica:
    • AI.IF: per filtrare i dati con condizioni in linguaggio naturale
    • AI.SCORE: per valutare l'input in base al sentiment
    • AI.CLASSIFY: per classificare l'input in categorie definite dall'utente

Costi

Questo tutorial utilizza componenti fatturabili di Google Cloud, tra cui:

  • BigQuery
  • BigQuery ML

Per saperne di più sui costi di BigQuery, consulta la pagina dei prezzi di BigQuery.

Per saperne di più sui costi di BigQuery ML, consulta la pagina dei prezzi di BigQuery ML. BigQuery ML pricing.

Prima di iniziare

  1. Accedi al tuo Google Cloud account. Se non hai mai utilizzato Google Cloud, crea un account per valutare il rendimento dei nostri prodotti in scenari reali. I nuovi clienti ricevono anche 300 $di crediti senza costi per eseguire, testare e implementare carichi di lavoro.
  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. Abilita l'API BigQuery.

    Ruoli richiesti per abilitare le API

    Per abilitare le API, devi disporre dell'autorizzazione serviceusage.services.enable. Se hai creato il progetto, probabilmente hai già questa autorizzazione tramite il ruolo Proprietario (roles/owner). In caso contrario, puoi ottenere questa autorizzazione tramite il ruolo Amministratore utilizzo servizi (roles/serviceusage.serviceUsageAdmin). Scopri come concedere i ruoli.

    Abilitare l'API

    Per i nuovi progetti, l'API BigQuery viene abilitata automaticamente.

  7. (Facoltativo): Abilita la fatturazione per il progetto. Se non vuoi abilitare la fatturazione o fornire una carta di credito, i passaggi descritti in questo documento funzionano comunque. BigQuery ti fornisce una sandbox per eseguire i passaggi. Per saperne di più, consulta Attiva la sandbox di BigQuery.

Ruoli obbligatori

Per ottenere le autorizzazioni necessarie per utilizzare le funzioni AI, chiedi all'amministratore di concederti i seguenti ruoli IAM nel progetto:

  • Esegui job di query e job di caricamento: Utente job BigQuery (roles/bigquery.jobUser)
  • Crea un set di dati, crea una tabella, carica i dati in una tabella ed esegui query su una tabella: Editor dati BigQuery (roles/bigquery.dataEditor)

Per saperne di più sulla concessione dei ruoli, consulta Gestisci l'accesso a progetti, cartelle e organizzazioni.

Potresti anche riuscire a ottenere le autorizzazioni richieste tramite i ruoli personalizzati o altri ruoli predefiniti.

Creare dati di esempio

Per creare un set di dati denominato my_dataset per questo tutorial, esegui la seguente query.

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

Crea quindi una tabella denominata customer_feedback che contenga recensioni di esempio dei clienti per un dispositivo:

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.") 
      ])
);

Categorizzare il sentiment generale

Può essere utile estrarre il sentiment generale espresso nel testo per supportare casi d'uso come i seguenti:

  • Misura la soddisfazione dei clienti in base alle recensioni.
  • Monitora la percezione del brand sui social media.
  • Assegna la priorità ai ticket di assistenza in base al livello di insoddisfazione degli utenti.

La seguente query mostra come utilizzare la funzione AI.CLASSIFY per classificare le recensioni della tabella customer_feedback come positive, negative o neutre:

SELECT
  review_id,
  review_text,
  AI.CLASSIFY(
    review_text,
    categories => ['positive', 'negative', 'neutral'],
    endpoint => 'gemini-2.5-pro') AS sentiment
FROM
  my_dataset.customer_feedback;

Il risultato è simile al seguente:

+-----------+------------------------------------------+-----------+
| 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."                                  |           |
+-----------+------------------------------------------+-----------+

Analizzare il sentiment basato sugli aspetti

Se un sentiment generale come positivo o negativo non è sufficiente per il tuo caso d'uso, puoi analizzare un aspetto specifico del significato del testo. Ad esempio, potresti voler comprendere l'atteggiamento di un utente nei confronti della qualità del prodotto, indipendentemente dalle sue opinioni sul prezzo. Puoi anche richiedere un valore personalizzato per indicare che un determinato aspetto non è applicabile.

L'esempio seguente mostra come utilizzare la funzione AI.SCORE per valutare il sentiment degli utenti da 1 a 10 in base a quanto ogni recensione nella tabella customer_feedback è favorevole al prezzo, al servizio clienti e alla qualità. La funzione restituisce il valore personalizzato -1 nei casi in cui un aspetto non viene menzionato nella recensione, in modo da poterli filtrare in un secondo momento.

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"),
    endpoint => 'gemini-2.5-pro') 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"),
    endpoint => 'gemini-2.5-pro') 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"),
    endpoint => 'gemini-2.5-pro') AS quality_score
FROM
  my_dataset.customer_feedback
LIMIT 3;

Il risultato è simile al seguente:

+-----------+------------------------------------------+--------------+---------------+---------------+
| 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."                                  |              |               |               |
+-----------+------------------------------------------+--------------+---------------+---------------+

Rilevare le emozioni

Oltre al sentiment positivo o negativo, puoi classificare il testo in base a emozioni specifiche che selezioni. Questa funzionalità è utile quando vuoi comprendere meglio le risposte degli utenti o contrassegnare i feedback altamente emotivi per la revisione.

SELECT
  review_id,
  review_text,
  AI.CLASSIFY(
    review_text,
    categories => ['joy', 'anger', 'sadness', 'surprise', 'fear', 'disgust', 'neutral', 'other'],
    endpoint => 'gemini-2.5-pro'
  ) AS emotion
FROM
  my_dataset.customer_feedback;

Il risultato è simile al seguente:

+-----------+------------------------------------------+---------+
| 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."                                  |         |
+-----------+------------------------------------------+---------+

Categorizzare le recensioni per argomento

Puoi utilizzare la funzione AI.CLASSIFY per raggruppare le recensioni in argomenti predefiniti. Puoi ad esempio eseguire le seguenti operazioni:

  • Scopri i temi comuni nei feedback dei clienti.
  • Organizza i documenti per argomento.
  • Inoltra i ticket di assistenza per argomento.

L'esempio seguente mostra come classificare i feedback dei clienti in vari tipi, ad esempio problema di fatturazione o accesso all'account , e quindi contare quante recensioni appartengono a ogni categoria:

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

Il risultato è simile al seguente:

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

Identificare le recensioni semanticamente simili

Puoi utilizzare la funzione AI.SCORE per valutare la somiglianza semantica di due testi chiedendo di valutare la somiglianza del significato. Questa funzionalità può aiutarti a svolgere attività come le seguenti:

  • Trova voci duplicate o quasi duplicate.
  • Raggruppa feedback simili.
  • Potenzia le applicazioni di ricerca semantica.

La seguente query trova le recensioni che parlano della difficoltà di configurazione del prodotto:

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),
    endpoint => 'gemini-2.5-pro') AS setup_difficulty
FROM my_dataset.customer_feedback
ORDER BY setup_difficulty DESC
LIMIT 2;

Il risultato è simile al seguente:

+-----------+------------------------------------------+------------------+
| 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!         |                  |
+-----------+------------------------------------------+------------------+

Puoi anche utilizzare la funzione AI.IF per trovare le recensioni correlate al testo:

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),
    endpoint => 'gemini-2.5-pro');

Combinare le funzioni

Può essere utile combinare queste funzioni in un'unica query. Ad esempio, la seguente query filtra prima le recensioni per il sentiment negativo e poi le classifica in base al tipo di frustrazione:

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

Creare funzioni definite dall'utente per i prompt riutilizzabili

Per mantenere le query leggibili, puoi riutilizzare la logica dei prompt creando funzioni definite dall'utente. La seguente query crea una funzione per rilevare il sentiment negativo chiamando AI.IF con un prompt personalizzato. Quindi, chiama questa funzione per filtrare in base alla recensione negativa.

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),
      endpoint => 'gemini-2.5-pro')
);

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

Libera spazio

Per evitare addebiti, puoi eliminare il progetto che contiene le risorse che hai creato oppure mantenere il progetto ed eliminare le singole risorse.

Elimina il progetto

Per eliminare il progetto:

  1. Nella Google Cloud console, vai alla pagina Gestisci risorse.

    Vai a Gestisci risorse

  2. Nell'elenco dei progetti, seleziona il progetto che vuoi eliminare, quindi fai clic su Elimina.
  3. Nella finestra di dialogo, digita l'ID progetto, quindi fai clic su Chiudi per eliminare il progetto.

Elimina il set di dati

Per eliminare il set di dati e tutte le risorse che contiene, incluse tutte le tabelle e le funzioni, esegui la seguente query:

DROP SCHEMA my_dataset CASCADE;