Build a retrieval-augmented generation (RAG) system

Updated at:

This topic introduces retrieval-augmented generation (RAG) and explains how to build and use a RAG system.

Preview the results

A RAG system retrieves relevant documents from a knowledge base and submits them along with the original input to a large language model (LLM). The LLM then generates a response based on both the retrieved information and the original input.

  • SQL query

    /*polar4ai*/SELECT * FROM PREDICT (MODEL _polar4ai_tongyi, SELECT 'Who are you?') WITH ();
  • SQL result

    ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    | result                                                                                                                                                                                                                                                                                                             |
    +--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    | Hello! I am Qwen, a large-scale language model developed by Alibaba Group. I can answer questions, generate text such as stories, official documents, emails, scripts, logical reasoning, programming, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask me anytime!                                                                                                         |
    +--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

RAG system architecture diagram

The following diagram shows the overall workflow for building and using a RAG system:

image

Large language models (LLMs) have limitations in accuracy and real-time performance. They are not ideal for customer service or Q&A scenarios that require precise answers. To address this, the industry uses retrieval-augmented generation (RAG). RAG combines an LLM—such as Qwen—with an information retrieval component. This improves model performance. RAG uses the information retrieval component to retrieve relevant documents from a knowledge base. It then passes both the retrieved documents and the original query to the LLM. The LLM leverages its existing inductive generation capability to produce accurate responses based on up-to-date information—without retraining the model.

The conversational system service deployed on PolarDB integrates LLM and RAG technologies. This effectively addresses LLM limitations. It delivers accurate and information-rich responses for Q&A scenarios. It significantly improves natural language processing task efficiency and user experience.

Build document vector and tokenization index tables

Documents to retrieve already exist in the database

If the documents to retrieve already exist in the database, vectorize them.

  1. Prepare data

    1. Create a document data table

      CREATE TABLE enterprise_context(
          file_id varchar(256) COMMENT 'Index for traceability',
          file_name varchar(256) COMMENT 'Title or core content',
          content text COMMENT 'Text content', 
          category_id varchar(128) COMMENT 'Category information',
          PRIMARY KEY (file_id)
      );
    2. Insert document data

      INSERT INTO enterprise_context(file_id,file_name,content,category_id) VALUES
      ('doc1','Introduction to PolarDB for AI','PolarDB for AI is a distributed machine learning component built into PolarDB for MySQL. Based on a cloud-native architecture, it provides a suite of MLOps capabilities through SQL statements—including model creation, model status checks, model listing, model evaluation, and model inference. It also includes built-in machine learning and artificial intelligence algorithms such as classification, regression, and clustering algorithms. By combining MLOps and built-in models, PolarDB for AI delivers efficient, reliable, and convenient data intelligence for data-driven intelligent applications. It breaks down the system wall between databases and business applications and provides an end-to-end data intelligence service powered by database data.','c1'),
      ('doc2','PolarDB for AI in search and recommendation','PolarDB for AI transforms traditional DB+AI data intelligence applications into end-to-end data intelligence applications. It shifts database services from traditional data engineers and algorithm engineers to business engineers who directly integrate with business systems. Using PolarDB for AI’s Artificial Intelligence Recommendation algorithms and knowledge graph technology—and combined with Alibaba’s e-commerce strategies—it delivers end-to-end recommendation services for enterprises. This helps enterprises quickly overcome cold-start challenges. It offers personalized solutions tailored to different business scenarios and continuously enhances core business capabilities to drive revenue growth.','c2');
  2. Vectorize documents and build vector and tokenization indexes

    Note
    • The text-to-vector model _polar4ai_text2vec splits long documents into multiple text chunks. This increases RAG retrieval precision.

    • For more information about text vectorization, see Build a document retrieval system.

    Segment text data
    Create an index table

    RAG index tables use fixed parameter names and types. The SQL statement for the table schema is:

    /*polar4ai*/CREATE TABLE file_index_table(
      chunk_id varchar(265),
      chunk_content text_ik_smart, 
      file_id varchar(256),
      file_name varchar(256),
      category_id varchar(128),
      vecs vector_768, 
      PRIMARY KEY(chunk_id)
    );

    The parameters in the RAG index table are described below:

    Parameter

    Description

    Example value

    chunk_id

    {file_id}-{chunk_order}. A primary key ID assigned to each text chunk. Within the same file, IDs increment sequentially.

    file1-1

    chunk_content

    Text chunk. Tokenized using a tokenizer. You can use text_ik_smart (coarse-grained tokenization) or text_ik_max_word (fine-grained tokenization).

    Text content

    file_id

    File identifier used for traceability.

    xxx.docx

    file_name

    File name, title, or related statement (optional).

    Core content

    category_id

    Category ID used to limit the document search scope for exact match.

    c1

    vecs

    Chunk vector. Generated by converting the text chunk into a vector using the _polar4ai_text2vec model.

    Note

    _polar4ai_text2vec is a text-to-vector model. It currently supports only 768-dimensional vectors.

    [0.1, 0.2, ...]

    Build vector and tokenization indexes

    The _polar4ai_text2vec model converts text to vectors and currently supports only 768-dimensional vectors. Vectorize the document data in enterprise_context and save it to the RAG index table. When you set to_chunk=1, the chunk_id and chunk_content columns are generated using the segmentation method.

    /*polar4ai*/SELECT chunk_id, chunk_content, file_id, file_name, category_id FROM predict(model _polar4ai_text2vec, SELECT content, file_id, file_name, category_id FROM enterprise_context) 
    WITH (
      x_cols='content',
      primary_key='file_id',
      mode='async',
      vec_col='vecs',
      to_chunk=1,
      chunk_size=128,
      chunk_overlap=16
    )
    INTO file_index_table;

    The result is:

    +--------------------------------------+
    | task_id                              |
    +--------------------------------------+
    | 9a151a68-199f-11f0-b7cf-0b8132326edf |
    +--------------------------------------+

    Check whether the current task ID succeeded. Replace your-task-id with the ID generated by the file_index_table command.

    /*polar4ai*/SHOW TASK `your-task-id`;

    The result is:

    +------------+----------+---------+----------------------------+----------------------------+--------+--------------+----------+
    | taskStatus | filePath | results | startTime                  | endTime                    | errMsg | successBatch | allBatch |
    +------------+----------+---------+----------------------------+----------------------------+--------+--------------+----------+
    | finish     | []       |         | 2025-04-15 10:16:12.430755 | 2025-04-15 10:16:13.249794 |        | 5            | 5        |
    +------------+----------+---------+----------------------------+----------------------------+--------+--------------+----------+
    /*polar4ai*/SELECT * FROM file_index_table;

    The result is:

    +-------------+------------------------------------+----------+-----------------------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------+
    | category_id | file_name                          | file_id  | vecs                              | chunk_content                                                                                                                            | chunk_id       | 
    +-------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------+
    | c1          | Introduction to PolarDB for AI     | doc1     | [-0.0298, 0.0218, -0.0173, ...]   | model evaluation and model inference capabilities. It also provides a suite of built-in machine learning and artificial intelligence algorithms, including classification, regression, and clustering algorithms.                                       |  doc1-2      |
    +-------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------+
    | c2          | PolarDB for AI in search and recommendation    | doc2     | [-0.0309, 0.0180, ...]            | PolarDB for AI transforms traditional DB+AI data intelligence applications into end-to-end data intelligence applications, shifting database services from traditional data engineers and algorithm engineers to business engineers who directly integrate with business systems.           |  doc2-1       |
    +-------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------+
    | c1          | Introduction to PolarDB for AI     | doc1     | [-0.0332, -0.0031, ...]           | PolarDB for AI is a distributed machine learning component built into PolarDB for MySQL.                                                                        |  doc1-1      |
    +-------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------+
    | c1          | Introduction to PolarDB for AI     | doc2     | [-0.0254, -0.0084, ...]           | It breaks down the system wall between databases and business applications and provides an end-to-end data intelligence service powered by database data.                                                                        |  doc1-3      |
    +-------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------+
    | c2          | PolarDB for AI in search and recommendation    | doc2     | [-0.0254, -0.0084, ...]           | algorithms and knowledge graph technology—and combined with Alibaba’s e-commerce strategies—it delivers end-to-end recommendation services for enterprises. This helps enterprises quickly overcome cold-start challenges.                                         |  doc2-2      |
    +-------------+------------------------------------+----------+-----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------+---------------+
    Do not segment text data
    Create an index table

    RAG index tables use fixed parameter names and types. The table schema is described below:

    /*polar4ai*/CREATE TABLE file_index_table(
      file_id varchar(256),
      file_name varchar(256),
      chunk_content text_ik_smart,
      category_id varchar(128),
      vecs vector_768, 
      PRIMARY KEY(file_id)
    );

    The parameters in the RAG index table are described below:

    Parameter

    Description

    Example value

    file_id

    File identifier used for traceability.

    xxx.docx

    file_name

    File name, title, or related statement (optional).

    Core content

    chunk_content

    Text content. Tokenized using a tokenizer. You can use text_ik_smart (coarse-grained tokenization) or text_ik_max_word (fine-grained tokenization).

    Text content

    category_id

    Category ID used to limit the document search scope for exact match.

    c1

    vecs

    Chunk vector. Generated by converting the text chunk into a vector using the _polar4ai_text2vec model.

    Note

    _polar4ai_text2vec is a text-to-vector model. It currently supports only 768-dimensional vectors.

    [0.1, 0.2, ...]

    Build vector and tokenization indexes

    The _polar4ai_text2vec model converts text to vectors and currently supports only 768-dimensional vectors. Vectorize the document data in enterprise_context and save it to the RAG index table.

    /*polar4ai*/SELECT chunk_content, file_id, file_name, category_id FROM predict(model _polar4ai_text2vec, SELECT content as chunk_content, file_id, file_name, category_id FROM enterprise_context) 
    WITH (
      x_cols='chunk_content',
      primary_key='file_id',
      mode='async',
      vec_col='vecs'
    )
    INTO file_index_table;

    The result is:

    +--------------------------------------+
    | task_id                              |
    +--------------------------------------+
    | e0565870-19b8-11f0-9854-13216fb09ecd |
    +--------------------------------------+

    Check whether the current task ID succeeded. Replace your-task-id with the ID generated by the file_index_table command.

    /*polar4ai*/SHOW TASK `your-task-id`;

    The result is:

    +------------+----------+---------+----------------------------+----------------------------+--------+--------------+----------+
    | taskStatus | filePath | results | startTime                  | endTime                    | errMsg | successBatch | allBatch |
    +------------+----------+---------+----------------------------+----------------------------+--------+--------------+----------+
    | finish     | []       |         | 2025-04-15 13:17:07.716503 | 2025-04-15 13:17:08.098476 |        | 2            | 2        |
    +------------+----------+---------+----------------------------+----------------------------+--------+--------------+----------+
    /*polar4ai*/SELECT * FROM file_index_table;

    The result is:

    +-------------+------------------------------------+----------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------+
    | category_id | file_name                          | file_id  | vecs                              | chunk_content                                                                                                                            | 
    +-------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    | c1          | Introduction to PolarDB for AI     | doc1     | [-0.0213, 0.0158, -0.0118, ...]   | PolarDB for AI is a distributed machine learning component built into a database. It provides a suite of MLOps capabilities, including model creation and status checks.                                   |
    +-------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    | c2          | PolarDB for AI in search and recommendation   | doc2     | [-0.0250, 0.0158, -0.0215, ...]   | PolarDB for AI transforms traditional DB+AI data intelligence applications into end-to-end services. It helps enterprises quickly overcome cold-start challenges and delivers personalized solutions.                                 |
    +-------------+------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

Documents to retrieve do not exist in the database

If the documents to retrieve do not exist in the database, first upload them to the database. Then parse their content and vectorize the text.

  1. Create a document knowledge base

    1. Upload document data

      /*polar4ai*/UPLOAD FILE docfile WITH (
          file_id='Polar4AI',
          file_type='.docx',
          src_file_location='https://xxx.aliyuncs.com/Polar4AI-Introduction.docx',
          dest_file_name='Polar4AI-Introduction', 
          metadata='{}'
      );

      The parameters in WITH() are described below:

      Note

      Parameter

      Description

      Example value

      file_id

      File primary key (must be unique).

      'Polar4AI'

      file_type

      File type.

      '.docx'

      src_file_location

      File URL.

      'https://xxx.aliyuncs.com/Polar4AI-Introduction.docx'

      Note

      You can replace this with your actual business address.

      dest_file_name

      Target file name (can be duplicated. Does not support paths or slashes).

      'Polar4AI-Introduction'

      metadata

      Metadata. Reserved for future use.

      '{}'

    2. View uploaded documents

      Use the following SQL syntax to view uploaded documents. Replace unique_file_id with the file ID you specified in the UPLOAD FILE command.

      /*polar4ai*/SHOW FILES;
      /*polar4ai*/SHOW FILE `unique_file_id`;
    3. (Optional) Delete uploaded documents

      /*polar4ai*/DROP FILE `unique_file_id`;
    4. Create a document metadata table

      Create and update the metadata table in the database using the following SQL statements:

      CREATE TABLE file_id_list(
          file_id varchar(256) PRIMARY KEY,
          action_type varchar(10),
          category_id varchar(128)
          # any data format ...
      );	
      
      INSERT INTO file_id_list(file_id, action_type, category_id, ...) VALUES ('unique_file_id', 'add', 'c1', ...);	

      The parameters in the document metadata table are described below:

      Parameter

      Description

      Example value

      file_id

      File primary key specified in UPLOAD FILE.

      'Polar4AI'

      action_type

      Action to perform on the file. Valid values: ['add', 'delete']. If action_type is 'add', add the file content to the index table and recalculate index values. If action_type is 'delete', remove the file content from the index table.

      'add'

      'delete'

      ''

      category_id

      Category identifier for the file.

      'c1'

  2. Parse files and build vector and tokenization indexes

    1. Create an index table

      Note

      If you get the error ERROR 9050 (HY000): table exists when creating the index table, run /*polar4ai*/ SHOW TABLES to list existing index tables and check for duplicates.

      Vector and tokenization index tables use fixed parameter names and types. The SQL statement is:

      /*polar4ai*/CREATE TABLE file_index_table(
        chunk_id varchar(265),
        chunk_content text_ik_smart, 
        file_id varchar(256),
        file_name varchar(256),
        vecs vector_768, 
        PRIMARY KEY(chunk_id)
      );

      The parameters are described below:

      Parameter

      Description

      Example value

      file_id

      Unique file identifier used for traceability.

      'Polar4AI'

      file_name

      File name, title, or related statement.

      'Polar4AI-Introduction'

      chunk_content

      Text chunk. Tokenized using a tokenizer. You can use text_ik_smart (coarse-grained tokenization) or text_ik_max_word (fine-grained tokenization).

      Document text content

      vecs

      Chunk vector. Generated by converting the text chunk into a vector using the _polar4ai_text2vec model.

      [0.1, 0.2, ...]

      chunk_id

      {file_id}-{chunk_order}. A primary key ID assigned to each chunk. Within the same file, IDs increment sequentially.

      'Polar4AI-1'

    2. Build vector and tokenization indexes by file ID

      Select the file_id from the document metadata table that you want to parse and index. Parse the document content and insert it into the index table using the _polar4ai_text2vec model’s predict method:

      /*polar4ai*/SELECT chunk_id, file_id, file_name, chunk_content FROM predict(model _polar4ai_text2vec, SELECT file_id FROM file_id_list) 
      WITH (
          x_cols='chunk_content',
          primary_key='file_id',
          mode='async',
          resource='file',
          to_chunk=1,
          headers_to_split_on=-1,
          chunk_size=512,
          chunk_overlap=64,
          separator=''
      )
      INTO file_index_table;	

      The _polar4ai_text2vec model converts text to vectors and currently supports only 768-dimensional vectors. The parameters in WITH() are described below:

      Parameter

      Description

      Example value or range

      x_cols

      Field that stores text.

      chunk_content

      primary_key

      Primary key of the file list—the document ID.

      id

      mode

      Write mode for document data. Only async (asynchronous) mode is supported.

      async

      resource

      Resource type for the file parsing process. Set to file.

      file

      to_chunk

      Whether to segment text in the file.

      0 or 1

      headers_to_split_on

      When to_chunk=1, split on headings at the specified level.

      • If headers_to_split_on is -1, split on all heading levels in the file.

      • If headers_to_split_on is x, split on headings at level x or lower.

      -1 ≤ x ≤ 6 (integer)

      chunk_size

      Maximum length of each text segment.

      chunk_size ≥ 50

      chunk_overlap

      Number of overlapping characters between adjacent segments.

      chunk_overlap ≤ chunk_size

      separator

      Separator between segments within a chunk.

      Empty string '', English comma ,, Chinese comma ,, etc.

    3. (Optional) Adjust index table content

      Based on the action_type in the file_id_list metadata table, specify whether to add or delete document content. When you pass the category identifier category_id as a parameter, the category information is stored in the vector and tokenization index table. You can then limit the text search scope by setting the category_ids parameter in RAG queries. For example, the file_id_list table specifies the operation type to add or delete documents.

      /*polar4ai*/SELECT chunk_id, file_name, chunk_content, category_id FROM predict(model _polar4ai_text2vec, SELECT file_id, action_type, category_id FROM file_id_list) 
      WITH (
          x_cols='chunk_content',
          primary_key='file_id',
          mode='async',
          resource='file',
          to_chunk=1,
          headers_to_split_on=-1,
          chunk_size=512,
          chunk_overlap=64,
          separator=''
      ) INTO file_index_table;
    4. Check task status and results

      When taskStatus is finish, the file parsing task completed successfully. You can query the chunk information in the index table.

      /*polar4ai*/SHOW TASK `task-id`;
      /*polar4ai*/SELECT * FROM file_index_table LIMIT 10;
    5. (Optional) Delete records from the index table

      /*polar4ai*/DELETE FROM file_index_table WHERE file_id = 'unique_file_id';

Retrieval-augmented generation (RAG)

  1. Use RAG online

    Run the following SQL statement to use RAG online. The query returns the model-generated result, retrieved text, corresponding file name, vector score, tokenization score, and hybrid score:

    Segment text data

    /*polar4ai*/SELECT * FROM PREDICT(MODEL _polar4ai_rag, SELECT 'Query text') WITH (
        index_name='file_index_table',
        primary_key='chunk_id',
        vec_top_k=5,
        vec_score_threshold=0.0,
        pos_top_k=3,
        pos_score_threshold=0.0,
        use_vec=1,
        use_pos=1,
        hybrid_type=0,
        hybrid_score=0.8,
        ranker_model='',
        category_ids='',
        file_id='',
        generate=1
    );

    Unsharded text data

    /*polar4ai*/SELECT * FROM PREDICT(MODEL _polar4ai_rag, SELECT 'Query text') WITH (
        index_name='file_index_table',
        primary_key='file_id',
        vec_top_k=5,
        vec_score_threshold=0.0,
        pos_top_k=3,
        pos_score_threshold=0.0,
        use_vec=1,
        use_pos=1,
        hybrid_type=0,
        hybrid_score=0.8,
        ranker_model='',
        category_ids='',
        file_id='',
        generate=1
    );

    The parameters in WITH() are described below:

    Parameter

    Description

    Example value or range

    index_name

    Name of the index table.

    index_table

    primary_key

    Name of the primary key column in the index table.

    chunk_id, file_id

    Note

    This depends on whether your text data is segmented.

    • Segmented: chunk_id

    • Not segmented: file_id

    vec_top_k

    Keep the top K results with the highest vector similarity scores.

    vec_top_k ≥ 0

    vec_score_threshold

    Threshold for vector similarity scores. Discard results with scores below this threshold.

    vec_score_threshold ≥ 0

    pos_top_k

    Keep the top K results with the highest tokenization similarity scores.

    pos_top_k ≥ 0

    pos_score_threshold

    Threshold for tokenization similarity scores. Discard results with scores below this threshold.

    pos_score_threshold ≥ 0

    use_vec

    Whether to use vector retrieval.

    • 1 (default): Yes

    • 0: No

    0, 1

    use_pos

    Whether to use tokenization retrieval.

    • 1 (default): Yes

    • 0: No

    0, 1

    hybrid_type

    Type of hybrid scoring:

    • 0: Union of both results. Sort by hybrid_score.

    • 1: Union of both results. Prioritize vector retrieval by position.

    • 2: Intersection of both results. Sort by hybrid_score.

    0, 1, 2

    hybrid_score

    Hybrid score formula: hybrid_score*vec_score + (1-hybrid_score)*pos_score.

    0 ≤ hybrid_score ≤ 1

    ranker_model

    Name of the ranker model after creation. Default is empty.

    ''

    category_ids

    Comma-separated list of category IDs.

    'c1, c2'

    file_id

    Specify a file by ID to generate a response.

    'Polar4AI'

    generate

    Whether to use a large language model to generate a response.

    • 1 (default): Yes. Use the LLM to generate an inductive response.

    • 0: No. Return only the retrieved results without LLM generation.

    0, 1

  2. (Optional) Call Qwen

    You can call Qwen to generate a response using RAG retrieval results. For details, see Qwen large language model data inference and interaction.

    The result is:

    ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    | result                                                                                                                                                                                                                                                                                                             |
    +--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    | Hello! I am Qwen, a large-scale language model developed by Alibaba Group. I can answer questions, generate text such as stories, official documents, emails, scripts, logical reasoning, programming, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask me anytime!                                                                                                         |
    +--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+