איך יוצרים SQL באמצעות שפה טבעית ב-AlloyDB AI

באמצעות ה-API של AlloyDB AI לשפה טבעית, אתם יכולים לתרגם שאלות בשפה טבעית לשאילתות SQL ולתוצאות של מסד נתונים. במדריך הזה תגדירו את ה-API של AlloyDB AI לשפה טבעית באמצעות מסוף Google Cloud , כדי שהאפליקציות שלכם יוכלו לשלוח שאילתות למסד הנתונים בשפה טבעית.

הדוגמאות במדריך הזה הן להמחשה בלבד.

מטרות

  • ליצור טבלאות, למלא אותן ולהשתמש ביצירה אוטומטית כדי ליצור הקשר.
  • יוצרים אינדקס ערכים לעמודות במסד הנתונים.
  • יוצרים ומגדירים אובייקט של הגדרת שפה טבעית (nl_config).
  • יוצרים תבניות לשאילתה לדוגמה באפליקציה.
  • משתמשים בפונקציה get_sql() כדי ליצור שאילתת SQL שעונה על שאלה.
  • משתמשים בפונקציה execute_nl_query() כדי לענות על שאלה בשפה טבעית באמצעות מסד הנתונים.

עלויות

במסמך הזה משתמשים ברכיבים הבאים של Google Cloud, והשימוש בהם כרוך בתשלום:

בעזרת מחשבון העלויות אתם יכולים להעריך את העלויות בהתאם לשימוש הצפוי.

משתמשים חדשים של Google Cloud ? יכול להיות שאתם זכאים לתקופת ניסיון בחינם.

כשמסיימים את המשימות שמתוארות במסמך הזה אפשר למחוק את המשאבים שיצרתם כדי להימנע מחיובים נוספים. מידע נוסף זמין בקטע הסרת המשאבים.

לפני שמתחילים

הפעלת החיוב וממשקי ה-API הנדרשים

  1. בוחרים פרויקט במסוף Google Cloud .

    כניסה לדף לבחירת הפרויקט

  2. מוודאים שהחיוב מופעל בפרויקט ב- Google Cloud .

  3. מפעילים את Cloud APIs שנדרשים כדי ליצור מכונה של AlloyDB ל-PostgreSQL ולהתחבר אליה.

    הפעלת ה-API

    1. בשלב Confirm project, לוחצים על Next כדי לאשר את שם הפרויקט שבו רוצים לבצע שינויים.
    2. בשלב Enable APIs, לוחצים על Enable כדי להפעיל את ממשקי ה-API הבאים:

      • AlloyDB API

יצירת מסד נתונים והתחברות אליו

  1. יצירת אשכול והמופע הראשי שלו.
  2. מתחברים למכונה ויוצרים מסד נתונים.
  3. הפעלת השילוב של פלטפורמת הסוכנים. מידע נוסף זמין במאמר שילוב עם Agent Platform.

הפעלה והתקנה של התוסף הנדרש

כדי להתקין את alloydb_ai_nl extension ולהשתמש בו, צריך קודם להפעיל את התוסף באמצעות הדגל alloydb_ai_nl.enabled. מידע נוסף מופיע במאמר בנושא הגדרת דגלים של מסד נתונים במופע.

כדי להתקין את התוסף alloydb_ai_nl, שהוא ה-API לתמיכה בשפה טבעית של AlloyDB AI, מריצים את השאילתה הבאה:

CREATE EXTENSION alloydb_ai_nl cascade;

אובייקטים של שפה טבעית ב-AlloyDB AI שנוצרו במכונה הראשית מופצים לרפליקות לקריאה בלבד ולרפליקות חוצות-אזורים, לכן חשוב להפעיל את הדגל של שפה טבעית ב-AlloyDB AI בכל מכונה של AlloyDB ל-PostgreSQL.

שדרוג התוסף alloydb_ai_nl

אם כבר התקנתם את התוסף, הריצו את ההצהרה הבאה כדי לעדכן אותו לגרסה העדכנית:

ALTER EXTENSION alloydb_ai_nl UPDATE;

יצירת הסכימה והטבלאות nla_demo

בשלבים הבאים יוצרים את סכימת nla_demo והטבלאות בסכימה. אתם מאכלסים את הטבלאות בנתונים סינתטיים. הסכימה והנתונים שסופקו נועדו לתמוך בפעולות הבסיסיות של עסק קמעונאי אונליין, עם אפליקציות פוטנציאליות שמתרחבות לניהול לקוחות, לניתוח נתונים, לשיווק ולהיבטים תפעוליים.

הנתונים לדוגמה מראים איך אפשר להשתמש בשפה הטבעית של AlloyDB AI למטרות פיתוח, בדיקה והדגמה, במיוחד לתכונות כמו ממשקי שפה טבעית.

  1. מריצים את השאילתה הבאה כדי ליצור את הסכימה:

    CREATE SCHEMA nla_demo;
    
  2. יצירת טבלאות בסכימה nla_demo. בטבלה addresses נשמרים פרטי הכתובת של הלקוחות וההזמנות.

    CREATE TABLE nla_demo.addresses (
        address_id      SERIAL         PRIMARY KEY,
        street_address  VARCHAR(255)   NOT NULL,
        city            VARCHAR(255)   NOT NULL,
        country         VARCHAR(255)
    );
    
  3. מריצים את השאילתה הבאה כדי ליצור את הטבלה customers. בטבלה הזו מאוחסנים נתוני לקוחות, כולל מזהה הלקוח, השם, הפרטים ליצירת קשר, הפניה לכתובת, תאריך הלידה וזמן יצירת הרשומה.

    CREATE TABLE nla_demo.customers (
        customer_id     SERIAL         PRIMARY KEY,
        first_name      VARCHAR(255)   NOT NULL,
        last_name       VARCHAR(255)   NOT NULL,
        email           VARCHAR(255)   UNIQUE NOT NULL,
        address_id      INTEGER        REFERENCES nla_demo.addresses(address_id),
        date_of_birth   DATE,
        created_at      TIMESTAMP      DEFAULT CURRENT_TIMESTAMP
    );
    
  4. יוצרים את הטבלה categories, שבה מאוחסנות קטגוריות המוצרים.

    CREATE TABLE nla_demo.categories (
        category_id     INTEGER        PRIMARY KEY,
        category_name   VARCHAR(255)   UNIQUE NOT NULL
    );
    
  5. יוצרים את הטבלה brands, שבה מאוחסנים שמות המותגים.

    CREATE TABLE nla_demo.brands (
        brand_id      INTEGER        PRIMARY KEY,
        brand_name    VARCHAR(255)   NOT NULL
    );
    
  6. יוצרים את הטבלה products, שבה מאוחסנים פרטי המוצר כמו מזהה המוצר, השם, התיאור, המותג, הקישור לקטגוריה וזמן יצירת הרשומה.

    CREATE TABLE nla_demo.products (
        product_id    INTEGER        PRIMARY KEY,
        name          VARCHAR(255)   NOT NULL,
        description   TEXT           DEFAULT 'Not available',
        brand_id      INTEGER        REFERENCES nla_demo.brands(brand_id),
        category_id   INTEGER        REFERENCES nla_demo.categories(category_id),
        created_at    TIMESTAMP      DEFAULT CURRENT_TIMESTAMP,
        price         DECIMAL(10, 2),
        description_embedding        VECTOR(768)
    );
    
  7. תצור טבלה של orders. בטבלה הזו מאוחסן מידע על הזמנות של לקוחות, כולל פרטי הלקוח, התאריך, הסכום הכולל, כתובות המשלוח והחיוב וסטטוס ההזמנה.

    CREATE TABLE nla_demo.orders (
        order_id            INTEGER        PRIMARY KEY,
        customer_id         INTEGER        REFERENCES nla_demo.customers(customer_id),
        order_date          TIMESTAMP      DEFAULT CURRENT_TIMESTAMP,
        total_amount        DECIMAL(10, 2) NOT NULL,
        shipping_address_id INTEGER        REFERENCES nla_demo.addresses(address_id),
        billing_address_id  INTEGER        REFERENCES nla_demo.addresses(address_id),
        order_status        VARCHAR(50)
    );
    
  8. תצור טבלה של order_items. בטבלה הזו מתועדים פריטים ספציפיים בהזמנה, קישורים להזמנה ולווריאציית המוצר, ומצוינים הכמות והמחיר.

    CREATE TABLE nla_demo.order_items (
        order_item_id   SERIAL         PRIMARY KEY,
        order_id        INTEGER        REFERENCES nla_demo.orders(order_id),
        product_id      INTEGER        REFERENCES nla_demo.products(product_id),
        quantity        INTEGER        NOT NULL,
        price           DECIMAL(10, 2) NOT NULL
    );
    

אכלוס טבלאות בסכימה nla_demo

  1. מריצים את השאילתה הבאה כדי לאכלס את הטבלה addresses:

    INSERT INTO nla_demo.addresses (street_address, city, country)
    VALUES
        ('1800 Amphibious Blvd', 'Mountain View', 'USA'),
        ('Avenida da Pastelaria, 1903', 'Lisbon', 'Portugal'),
        ('8 Rue du Nom Fictif 341', 'Paris', 'France');
    
  2. מאכלסים את הטבלה customers.

    INSERT INTO nla_demo.customers (first_name, last_name, email, address_id, date_of_birth)
    VALUES
        ('Alex', 'B.', 'alex.b@example.com', 1, '2003-02-20'),
        ('Amal', 'M.', 'amal.m@example.com', 2, '1998-11-08'),
        ('Dani', 'G.', 'dani.g@example.com', 3, '2002-07-25');
    
  3. מאכלסים את הטבלה categories.

    INSERT INTO nla_demo.categories (category_id, category_name)
    VALUES
        (1, 'Accessories'),
        (2, 'Apparel'),
        (3, 'Footwear'),
        (4, 'Swimwear');
    
  4. מאכלסים את הטבלה brands.

    INSERT INTO nla_demo.brands (brand_id, brand_name)
    VALUES
        (1, 'CymbalPrime'),
        (2, 'CymbalPro'),
        (3, 'CymbalSports');
    
  5. מאכלסים את הטבלה products.

    INSERT INTO nla_demo.products (product_id, brand_id, category_id, name, description, price)
    VALUES
        (1, 1, 2, 'Hoodie', 'A comfortable, casual sweatshirt with an attached hood.', 79.99),
        (2, 1, 3, 'Running Shoes', 'Lightweight, cushioned footwear designed for the impact of running.', 99.99),
        (3, 2, 4, 'Swimsuit', 'A garment designed for swimming or other water activities.', 20.00),
        (4, 3, 1, 'Tote Bag', 'A large, unfastened bag with two parallel handles.', 69.99),
        (5, 3, 3, 'CymbalShoe', 'Footwear from Cymbal, designed for your life''s rhythm.', 89.99);
    
    UPDATE nla_demo.products SET description_embedding = embedding('text-embedding-004', description);
    
  6. מאכלסים את הטבלה orders.

    INSERT INTO nla_demo.orders (order_id, customer_id, total_amount, shipping_address_id, billing_address_id, order_status)
    VALUES
        (1, 1, 99.99, 1, 1, 'Shipped'),
        (2, 1, 69.99, 1, 1, 'Delivered'),
        (3, 2, 20.99, 2, 2, 'Processing'),
        (4, 3, 79.99, 3, 3, 'Shipped');
    
  7. מאכלסים את הטבלה order_items.

    INSERT INTO nla_demo.order_items (order_id, product_id, quantity, price)
    VALUES
        (1, 1, 1, 79.99),
        (1, 3, 1, 20.00),
        (2, 4, 1, 69.99),
        (3, 3, 1, 20.00),
        (4, 2, 1, 79.99);
    

יצירת הגדרה בשפה טבעית

כדי להשתמש בשפה טבעית ב-AlloyDB AI, ודאו שנקודת הקצה של Agent Platform מוגדרת. לאחר מכן יוצרים הגדרה ורושמים סכימה. ‫g_alloydb_ai_nl.g_create_configuration יוצר את המודל.

  1. יוצרים הגדרה של שפה טבעית.

    SELECT alloydb_ai_nl.g_create_configuration( 'nla_demo_cfg' );
    
  2. רושמים טבלאות בהגדרות של nla_demo_cfg.

    SELECT alloydb_ai_nl.g_manage_configuration(
        operation => 'register_table_view',
        configuration_id_in => 'nla_demo_cfg',
        table_views_in=>'{nla_demo.customers, nla_demo.addresses, nla_demo.brands, nla_demo.products, nla_demo.categories, nla_demo.orders, nla_demo.order_items}'
    );
    

יצירה והחלה של הקשר לטבלאות ולעמודות

כדי לספק תשובות מדויקות לשאלות בשפה טבעית, משתמשים ב-API של AlloyDB AI בשפה טבעית כדי לספק הקשר לגבי טבלאות, תצוגות ועמודות. אתם יכולים להשתמש בתכונה ליצירת הקשר אוטומטי של AlloyDB AI Natural Language API כדי ליצור הקשר מטבלאות ומעמודות, ולהחיל את ההקשר כ-COMMENTS שמצורף לטבלאות, לתצוגות ולעמודות.

  1. כדי ליצור הקשרים של הסכימה עבור הטבלאות והעמודות שרשומות בהגדרות של nla_demo_cfg, מריצים את הפקודה הבאה:

    SELECT alloydb_ai_nl.generate_schema_context(
      'nla_demo_cfg',
      TRUE
    );
    

    השאילתה הקודמת מאכלסת את התצוגה alloydb_ai_nl.generated_schema_context_view בהקשר. העברת TRUE מחליפה את ההקשר בתצוגה הזו מריצות קודמות.

  2. כדי לאמת את ההקשר שנוצר לטבלה nla_demo.products, מריצים את השאילתה הבאה:

    SELECT object_context
    FROM alloydb_ai_nl.generated_schema_context_view
    WHERE schema_object = 'nla_demo.products';
    

    ההקשר שיתקבל יהיה דומה לזה:

    The products table stores information about products, including their name,
    a brief description, the brand they belong to (referenced by brand_id),
    and the category they fall under (referenced by category_id). Each product
    has a unique identifier (product_id) and a timestamp indicating its creation
    time (created_at).
    
  3. כדי לאמת את ההקשר שנוצר לעמודה, כמו nla_demo.products.name, מריצים את הפקודה הבאה:

    SELECT object_context
    FROM alloydb_ai_nl.generated_schema_context_view
    WHERE schema_object = 'nla_demo.products.name';
    

    הפלט של השאילתה אמור להיראות כך:

    The name column in the nla_demo.products table contains the specific
    name or title of each product. This is a short, descriptive text string
    that clearly identifies the product, like "Hoodie," "Tote Bag,"
    "Running Shoes," or "Swimsuit." It helps distinguish individual products
    within the broader context of their brand and category. The name column
    specifies the exact product. This column is essential for users and
    systems to identify and refer to specific products within the database.
    
  4. בודקים את ההקשר שנוצר בתצוגה alloydb_ai_nl.generated_schema_context_view ומעדכנים את ההקשר שצריך לשנות.

    SELECT alloydb_ai_nl.update_generated_relation_context(
      'nla_demo.products',
      'The "nla_demo.products" table stores product details such as ID, name, description, brand, category linkage, and record creation time.'
    );
    
    SELECT alloydb_ai_nl.update_generated_column_context(
      'nla_demo.products.name',
      'The "name" column in the "nla_demo.products" table contains the specific name or title of each product.'
    );
    
  5. מחילים את ההקשר שנוצר שרוצים לצרף לאובייקטים המתאימים:

    SELECT alloydb_ai_nl.apply_generated_relation_context(
      'nla_demo.products', true
    );
    
    SELECT alloydb_ai_nl.apply_generated_column_context(
      'nla_demo.products.name',
      true
    );
    

    רשומות ההקשר שנוצרות בתצוגה alloydb_ai_nl.generated_schema_context_view מוחלות על אובייקטי הסכימה התואמים, וההערות מוחלפות.

  6. מחילים את הקשר הסכימה שנוצר.

    SELECT alloydb_ai_nl.apply_generated_schema_context(
      'nla_demo_cfg',
      TRUE);
    

    העברת TRUE מחליפה את ההקשר הקיים של אובייקטים שרשומים ב-nla_demo_cfg.

בניית אינדקס הערכים

‫AlloyDB AI API של שפה טבעית יוצר שאילתות SQL מדויקות באמצעות קישור ערכים. קישור ערכים משייך ביטויי ערך בהצהרות בשפה טבעית לסוגי מושגים ולשמות עמודות שרשומים מראש, ויכול להעשיר את השאלה בשפה טבעית.

לדוגמה, אפשר לענות על השאלה "מה המחיר של קפוצ'ון" בצורה מדויקת יותר אם Hoodie משויך למושג product_name, שמשויך לnla_demo.products.name. .

  1. כדי להגדיר את סוג המושג product_name ולקשר אותו לעמודה nla_demo.products.name, מריצים את השאילתות הבאות:

    SELECT alloydb_ai_nl.add_concept_type(
        concept_type_in => 'product_name',
        match_function_in => 'alloydb_ai_nl.get_concept_and_value_generic_entity_name',
        additional_info_in => '{
          "description": "Concept type for product name.",
          "examples": "SELECT alloydb_ai_nl.get_concept_and_value_generic_entity_name(''Hoodie'')" }'::jsonb
    );
    SELECT alloydb_ai_nl.associate_concept_type(
        'nla_demo.products.name',
        'product_name',
        'nla_demo_cfg'
    );
    
  2. כדי לוודא שסוג הקונספט product_name נוסף לרשימת סוגי הקונספטים, מריצים את השאילתה הבאה ומוודאים ש-product_name נכלל בתוצאה של השאילתה:

    SELECT alloydb_ai_nl.list_concept_types();
    
  3. כדי לוודא שהעמודה nla_demo.products.name משויכת לסוג הקונספט product_name, מריצים את השאילתה הבאה:

    SELECT *
    FROM alloydb_ai_nl.value_index_columns
    WHERE column_names = 'nla_demo.products.name';
    
  4. כדי להגדיר את סוג הקונספט brand_name ולשייך אותו לעמודה nla_demo.brands.brand_name, מריצים את השאילתות הבאות:

    SELECT alloydb_ai_nl.add_concept_type(
        concept_type_in => 'brand_name',
        match_function_in => 'alloydb_ai_nl.get_concept_and_value_generic_entity_name',
        additional_info_in => '{
          "description": "Concept type for brand name.",
          "examples": "SELECT alloydb_ai_nl.get_concept_and_value_generic_entity_name(''CymbalPrime'')" }'::jsonb
    );
    SELECT alloydb_ai_nl.associate_concept_type(
        'nla_demo.brands.brand_name',
        'brand_name',
        'nla_demo_cfg'
    );
    
  5. אחרי שמגדירים את סוגי המושגים ומשייכים אליהם עמודות, יוצרים אינדקס ערכים.

    SELECT alloydb_ai_nl.create_value_index('nla_demo_cfg');
    SELECT alloydb_ai_nl.refresh_value_index('nla_demo_cfg');
    

יצירה אוטומטית של שיוכים לסוגי מושגים

באמצעות שפה טבעית ב-AlloyDB AI, אתם יכולים ליצור שיוכים באופן אוטומטי על סמך סוגי הקונספט הקיימים, במקום לשייך באופן ידני סוג קונספט לעמודות – למשל, להפעיל באופן ידני את alloydb_ai_nl.associate_concept_type.

כדי ליצור באופן אוטומטי שיוך של סוג מושג:

  1. יצירת שיוכים לכל היחסים במסגרת nla_demo_cfg:

    SELECT alloydb_ai_nl.generate_concept_type_associations('nla_demo_cfg');
    
  2. בודקים את השיוכים שנוצרו.

    SELECT * from alloydb_ai_nl.generated_value_index_columns_view;
    

    התוצאה אמורה להיראות כך: הוא מתייחס גם למושגים מובנים וגם למושגים שהמשתמשים מגדירים.

     -[ RECORD 1 ]---+-----------------------------------------------------------
     id              | 1
     config          | nla_demo_cfg
     column_names    | nla_demo.addresses.city
     concept_type    | city_name
     additional_info | {}
     -[ RECORD 2 ]---+-----------------------------------------------------------
     id              | 2
     config          | nla_demo_cfg
     column_names    | nla_demo.addresses.country
     concept_type    | country_name
     additional_info | {}
     -[ RECORD 3 ]---+-----------------------------------------------------------
     id              | 3
     config          | nla_demo_cfg
     column_names    | nla_demo.customers.first_name,nla_demo.customers.last_name
     concept_type    | full_person_name
     additional_info | {}
     -[ RECORD 4 ]---+-----------------------------------------------------------
     id              | 4
     config          | nla_demo_cfg
     column_names    | nla_demo.brands.brand_name
     concept_type    | brand_name
     additional_info | {}
     -[ RECORD 5 ]---+-----------------------------------------------------------
     id              | 5
     config          | nla_demo_cfg
     column_names    | nla_demo.products.name
     concept_type    | product_name
     additional_info | {}
    
     ....
     ```
    
  3. אופציונלי: מעדכנים או מסירים את השיוכים שנוצרו.

    -- Update, NULL means keeping the original value.
    SELECT alloydb_ai_nl.update_generated_concept_type_associations(
     id => 1,
     column_names => NULL,
     concept_type => 'generic_entity_name',
     additional_info => NULL
    );
    
    -- Drop
    SELECT alloydb_ai_nl.drop_generated_concept_type_association(id => 1);
    
  4. מחילים את השיוכים שנוצרו.

    SELECT alloydb_ai_nl.apply_generated_concept_type_associations('nla_demo_cfg');
    
  5. כדי שהשינויים יבואו לידי ביטוי, צריך לרענן את אינדקס הערכים.

    SELECT alloydb_ai_nl.refresh_value_index('nla_demo_cfg');
    

הגדרת תבניות של שאילתות

אתם יכולים להגדיר תבניות כדי לשפר את איכות התשובות שנוצרות על ידי ה-API של השפה הטבעית של AlloyDB AI.

  1. כדי לספק תבניות לדוגמה לשאלות קריטיות לעסק, וכדי לספק שאלות צפויות שבהן נדרשת רמת דיוק גבוהה, מריצים את השאילתה הבאה כדי להוסיף תבנית:

    SELECT alloydb_ai_nl.add_template(
        nl_config_id => 'nla_demo_cfg',
        intent => 'List the first names and the last names of all customers who ordered Swimsuit.',
        sql => 'SELECT c.first_name, c.last_name FROM nla_demo.Customers c JOIN nla_demo.orders o ON c.customer_id = o.customer_id JOIN nla_demo.order_items oi ON o.order_id = oi.order_id JOIN nla_demo.products p ON oi.product_id = p.product_id  AND p.name = ''Swimsuit''',
        sql_explanation => 'To answer this question, JOIN `nla_demo.Customers` with `nla_demo.orders` on having the same `customer_id`, and JOIN the result with nla_demo.order_items on having the same `order_id`. Then JOIN the result with `nla_demo.products` on having the same `product_id`, and filter rwos that with p.name = ''Swimsuit''. Return the `first_name` and the `last_name` of the customers with matching records.',
        check_intent => TRUE
    );
    
  2. כדי לראות את רשימת התבניות שנוספו, מריצים שאילתה בתצוגה alloydb_ai_nl.template_store_view:

    SELECT nl, sql, intent, psql, pintent
    FROM alloydb_ai_nl.template_store_view
    WHERE config = 'nla_demo_cfg';
    

    מתקבל הפלט הבא:

    nl      | List the first names and the last names of all customers who ordered Swimsuit.
    sql     | SELECT c.first_name, c.last_name
            | FROM nla_demo.Customers c
            | JOIN nla_demo.orders o ON c.customer_id = o.customer_id
            | JOIN nla_demo.order_items oi ON o.order_id = oi.order_id
            | JOIN nla_demo.products p ON oi.product_id = p.product_id
            | AND p.name = 'Swimsuit'
    intent  | List the first names and the last names of all customers who ordered
            | Swimsuit.
    psql    | SELECT c.first_name, c.last_name
            | FROM nla_demo.Customers c JOIN nla_demo.orders o
            | ON c.customer_id = o.customer_id 
            | JOIN nla_demo.order_items oi ON o.order_id = oi.order_id
            | JOIN nla_demo.products p ON oi.product_id = p.product_id
            | AND p.name = $1
    pintent | List the first names and the last names of all customers who ordered
            | $1.
    

    בתבנית הזו, הערך שתואם למאפיין psql הוא שאילתת ה-SQL עם הפרמטרים, והערך של העמודה pintent הוא הצהרת הכוונה עם הפרמטרים. המזהה של תבנית שנוספה לאחרונה יכול להיות שונה, בהתאם לתבניות שהוספתם בעבר. התבניות מספקות תשובות מדויקות מאוד לשאלות.

  3. כדי ליצור תבנית שמשתמשת בחיפוש סמנטי, מריצים את הצהרת הדוגמה הבאה:

    SELECT alloydb_ai_nl.add_template(
     nl_config_id => 'nla_demo_cfg',
     intent => 'List 3 products most similar to a Swimwear.',
     sql => $$SELECT name FROM nla_demo.products 
             ORDER BY description_embedding <=> embedding('text-embedding-004', 'Swimwear')::vector$$,
     sql_explanation => $$To answer this question, ORDER products in `nla_demo.products` , based by their distance of the descrption_embedding of the product with the embedding of 'Swimwear'.$$,
     check_intent => TRUE
    );
    

    התבנית שלמעלה מוסיפה את השורה הבאה לתצוגה המפורטת alloydb_ai_nl.template_store_view:

    nl      | List 3 products most similar to a Swimwear.
    sql     | SELECT name FROM nla_demo.products                                                                
            | ORDER BY description_embedding <=>
            | embedding('text-embedding-004', 'Swimwear')::vector
    intent  | List 3 products most similar to a Swimwear.
    psql    | SELECT name FROM nla_demo.products                                                                
            | ORDER BY description_embedding <=>
            | embedding('text-embedding-004', $1)::vector
    pintent | List 3 products most similar to a $1.
    

הגדרת מקטע של שאילתה

אתם יכולים להגדיר מקטעים כדי לשפר את איכות התשובות שנוצרות על ידי AlloyDB AI API של שפה טבעית.

כדי לספק קטע קוד לפרדיקטים קריטיים לעסק, ולספק תנאים צפויים שבהם צפויה רמת דיוק גבוהה, מריצים את השאילתה הבאה:

SELECT alloydb_ai_nl.add_fragment(
  nl_config_id => 'nla_demo_cfg',
  table_aliases => ARRAY['nla_demo.products AS T'],
  intent => 'luxury product',
  fragment => $$description LIKE '%luxury%' OR description LIKE '%premium%' OR description LIKE '%exclusive%' OR description LIKE '%high-end%' OR description LIKE '%finest%' OR description LIKE '%elite%' OR description LIKE '%deluxe%'$$);

כדי לראות את רשימת החלקים שנוספו, שולחים שאילתה לתצוגה alloydb_ai_nl.fragment_store_view:

SELECT intent, fragment, pintent
FROM alloydb_ai_nl.fragment_store_view;

מתקבל הפלט הבא:

intent    | luxury product
fragment  | description LIKE '%luxury%' OR description LIKE '%premium%' OR description LIKE '%exclusive%' OR description LIKE '%high-end%' OR description LIKE '%finest%' OR description LIKE '%elite%' OR description LIKE '%deluxe%'
pintent   | luxury product

יצירת תוצאות SQL משאלות בשפה טבעית

  1. כדי להשתמש ב-AlloyDB AI Natural Language API ליצירת שאילתות SQL וקבוצות תוצאות, מריצים את השאילתה הבאה:

    SELECT
        alloydb_ai_nl.get_sql(
            'nla_demo_cfg',
            'Find the customers who purchased Tote Bag.'
        ) ->> 'sql';
    

    מתקבל הפלט הבא:

    SELECT DISTINCT "c"."first_name", "c"."last_name"
    FROM "nla_demo"."customers" AS "c"
    JOIN "nla_demo"."orders" AS "o" ON "c"."customer_id" = "o"."customer_id"
    JOIN "nla_demo"."order_items" AS "oi" ON "o"."order_id" = "oi"."order_id"
    JOIN "nla_demo"."products" AS "p" ON "oi"."product_id" = "p"."product_id"
    WHERE "p"."name" = 'Tote Bag';
    

    פלט ה-JSON הוא שאילתת SQL שמשתמשת בתבנית שהוספתם בקטע הגדרת תבנית שאילתה.

  2. כדי להשתמש ב-AlloyDB AI API של שפה טבעית ליצירת שאילתות SQL, מריצים את השאילתה הבאה:

    SELECT
        alloydb_ai_nl.get_sql(
            'nla_demo_cfg',
            'List the maximum price of any CymbalShoe.'
        ) ->> 'sql';
    

    מתקבל הפלט הבא:

    SELECT max("price")
    FROM "nla_demo"."products"
    WHERE "name" = 'CymbalShoe'
    

    ‫AlloyDB AI API של שפה טבעית מזהה ש-CymbalShoe הוא שם המוצר, באמצעות אינדקס הערך. מריצים את השאילתה הבאה כדי להחליף את CymbalShoe בשם מותג (CymbalPrime):

    SELECT
        alloydb_ai_nl.get_sql(
            'nla_demo_cfg',
            'List the maximum price of any CymbalPrime.'
        ) ->> 'sql';
    

    הפלט שמתקבל:

    SELECT max("price")
    FROM "nla_demo"."products" AS t1
    JOIN "nla_demo"."brands" AS t2
    ON t1."brand_id" = t2."brand_id"
    WHERE t2."brand_name" = 'CymbalPrime';
    

    ‫AlloyDB AI משתמש באינדקס הערכים שנוצר ביצירת אינדקס הערכים כדי לפתור את CymbalPrime לסוג הקונספט brand_name, ומשתמש בעמודה nla_demo.brands.brand_name שמשויכת ל-brand_name.

  3. כדי להשתמש ב-API של השפה הטבעית של AlloyDB AI כדי לקבל את התוצאה של שאלה, מריצים את השאילתה הבאה:

    SELECT
    alloydb_ai_nl.execute_nl_query(
        'nla_demo_cfg',
        'Find the last name of the customers who live in Lisbon.'
    );
    

    מתקבל הפלט הבא:

    execute_nl_query     
    --------------------------
    {"last_name":"M."}
    
  4. כדי להשתמש ב-API של השפה הטבעית ב-AlloyDB AI כדי ליצור הצהרות SQL שמשתמשות בחיפוש סמנטי, מריצים את השאילתה הבאה:

    SELECT
     alloydb_ai_nl.get_sql(
         'nla_demo_cfg',
         'List 2 products similar to a Tote Bag.');
    

    מוחזרת הצהרת ה-SQL הבאה:

    SELECT name FROM nla_demo.products
    ORDER BY description_embedding <=> embedding(
        'text-embedding-004', 'Tote Bag')::vector
    LIMIT 2;
    

איך מקבלים סיכומי SQL

אתם יכולים ליצור סיכום תוצאות משאלה בשפה טבעית על סמך הנתונים שמאוחסנים במסד הנתונים. כך משתמשי הקצה יכולים להבין את הנתונים על ידי הצגת שאלות בשפה טבעית באופן ישיר.

כדי לקבל סיכום של SQL, מריצים את השאילתה לדוגמה הבאה:

SELECT
   alloydb_ai_nl.get_sql_summary(
      nl_config_id => 'nla_demo_cfg',
      nl_question => 'which brands have the largest number of products.'
);

השאילתה הזו מחזירה אובייקט JSON כפלט, בדומה לדוגמה הבאה:

   "answer": "The result set lists three brands: CymbalSports, CymbalPro, and CymbalPrime. Each brand is represented once, suggesting an equal distribution of products across these three brands within the dataset."

הסרת המשאבים

כדי להימנע מחיובים בחשבון Google Cloud בגלל השימוש במשאבים שנעשה במסגרת המדריך הזה, אפשר למחוק את הפרויקט שמכיל את המשאבים או להשאיר את הפרויקט ולמחוק את המשאבים בנפרד.

בקטעים הבאים מוסבר איך למחוק את המשאבים והאובייקטים האלה.

מחיקת האשכול

כשמוחקים את האשכול שיצרתם בקטע לפני שמתחילים, נמחקים גם כל האובייקטים שיצרתם.

  1. נכנסים לדף Clusters במסוף Google Cloud .

    כניסה לדף Clusters

  2. בעמודה Resource name, לוחצים על שם האשכול, my-cluster.

  3. לוחצים על Delete cluster.

  4. בקטע Delete cluster my-cluster, מזינים my-cluster כדי לאשר שרוצים למחוק את האשכול.

  5. לוחצים על Delete.

  6. אם יצרתם חיבור פרטי כשיצרתם אשכול, נכנסים לדף רשתות VPC במסוף Google Cloud ולוחצים על Delete VPC network.

מחיקת האובייקטים

אתם יכולים להשאיר את המשאבים שהגדרתם בקטע לפני שמתחילים, ולמחוק רק את האובייקטים שיצרתם בפרויקט Google Cloud .

  1. כדי להסיר את התבנית שהגדרתם בקטע הגדרת תבנית שאילתה, מריצים את השאילתה הבאה:

    SELECT alloydb_ai_nl.drop_template(id)
    FROM alloydb_ai_nl.template_store_view
    WHERE config = 'nla_demo_cfg';
    
  2. כדי להסיר את השיוכים שנוצרו אוטומטית ב-Autogenerate concept type associations, מריצים את השאילתה הבאה:

    SELECT alloydb_ai_nl.drop_generated_concept_type_association(id)
    FROM alloydb_ai_nl.generated_value_index_columns_view
    WHERE config = 'nla_demo_cfg';
    
  3. כדי להסיר את סוג המושג product_name שהגדרתם ביצירת אינדקס הערכים, מריצים את השאילתה הבאה:

    SELECT alloydb_ai_nl.drop_concept_type('product_name');
    
  4. כדי לרענן את אינדקס הערכים אחרי שמסירים את סוג הקונספט product_name, מריצים את השאילתה הבאה:

    SELECT alloydb_ai_nl.refresh_value_index();
    
  5. כדי להסיר את ההגדרה nla_demo_cfg שיצרתם בקטע יצירת הגדרה של שפה טבעית, מריצים את השאילתה הבאה:

    SELECT
    alloydb_ai_nl.g_manage_configuration(
        'drop_configuration',
        'nla_demo_cfg'
    );
    
  6. כדי להסיר את הסכימה nla_demo ואת הטבלאות שיצרתם ואכלסתם בקטעים יצירת הסכימה והטבלאות של nla_demo ואכלוס הטבלאות בסכימה של nla_demo, מריצים את השאילתה הבאה:

    DROP SCHEMA nla_demo CASCADE;
    

המאמרים הבאים