When enterprises have large volumes of unstructured documents (such as PDF, Word, and Markdown), traditional database queries cannot effectively use this information. Users find it difficult to obtain quick and precise answers from massive documents by asking simple questions.PolarDB for PostgreSQL integrates all-in-one Retrieval-Augmented Generation (RAG) capabilities within the database by using the polar_ai extension. You can use a simple SQL interface to transform private document data into an intelligent Q&A knowledge base without the need for complex external service integrations. This enables efficient, precise queries on unstructured data and allows you to quickly build enterprise-level intelligent Q&A applications.
Prerequisites
Before you begin, ensure that your environment meets the following requirements:
Engine: PostgreSQL 16 (kernel minor version 2.0.16.10.11.0 or later).
Node: Add an AI node with GPU specifications and set a database account for the AI node. For more information, see Add and manage AI nodes.
NoteIf you added an AI node when you created the cluster, you can directly set the database account for the AI node.
The database account for the AI node must have read and write permissions to access the target database.
Endpoint: Use the cluster endpoint to connect to the PolarDB cluster.
How it works
The core RAG process in PolarDB involves processing and storing external documents, then generating answers by combining vector search with a large language model (LLM).
Data preparation and loading: Load your source documents into a database table.
Document chunking: Call the
polar_ai.ai_rag_chunkingfunction to split long documents into smaller, semantically complete text chunks. This improves retrieval accuracy.Embedding: Call the
polar_ai.ai_rag_text_embeddingfunction to convert each text chunk into a high-dimensional vector, which captures its semantic information, and store it with the original text.Create a vector index: Create an HNSW index on the vector column to significantly accelerate similarity searches.
Retrieval: When a user asks a question, first embed the question itself. Then, perform a vector similarity search in the database to quickly recall the text chunks that are most relevant to the question.
rerank: To further improve relevance, call the
polar_ai.ai_rag_rerankfunction to perform a secondary ranking on the initially recalled text chunks and select the most critical information.Generate answer: Use the top reranked text chunks as context. Submit this context, along with the user's original question, to the large language model (LLM). The model then generates a final, precise, natural-language answer based on the provided context.
Prepare the environment
This section covers the prerequisites for using the RAG feature.
Log on to the cluster with a privileged account.
Get the node token.
Go to the PolarDB console. On the details page of your target cluster, in the Database Nodes section, find the AI node, click View Node Token, and then record the Node Token.
Create the
polar_aiextension and configure the node token.Run the following commands in your database to create the extension and set the key to access large model services.
ImportantEnsure you have set a database account for the AI node.
-- Create the extension. CREATE EXTENSION polar_ai; -- Set your key. Replace sk-xxx with your key for the large model service. SELECT polar_ai._ai_nl2sql_alter_token('sk-xxx');Create the vector extension.
-- Provides vector data types, vector indexes, and similarity calculation capabilities. CREATE EXTENSION vector;
Deploy the RAG service
After you set the database account for the AI node, you can use any account to deploy the RAG service. Run the following command to load and start the models and services required for RAG on the AI node:
SELECT polar_ai.ai_nl2sql_deployModel('RAG');Prepare data
This section uses a PDF document as an example to show how to import, chunk, and embed it in the database.
Log on to the cluster.
Create data tables to store the source document and the processed data. Run the following SQL statements to create two tables.
file_content: Stores the binary content of the uploaded source document.file_chunk: Stores the text content of the document chunks and their corresponding vectors.
-- Stores the source document CREATE TABLE file_content ( id SERIAL PRIMARY KEY, -- Unique identifier for the document name TEXT, -- Document name content BYTEA -- Binary content of the document ); -- Stores chunks and vectors CREATE TABLE file_chunk ( file_id INTEGER, -- Associated document ID chunk_id INTEGER, -- Chunk ID within the document chunk_content TEXT, -- Text content of the chunk embedding VECTOR(1024) -- Chunk vector. The dimension must match the model output. );Load local PDF documents into the
file_contenttable. We recommend using one of the following two methods to import the documents.Method 1 (Recommended): Use the
polar_ai_utilextension to load the binary content of a file from OSS.NoteYou must use a Privileged Account to install the extension.
CREATE EXTENSION polar_ai_util; -- Used to load documents from OSS INSERT INTO file_content(name, content) SELECT 'PolarAI.pdf', polar_ai.AI_LOADFILE('oss://<access-key-id>:<access-key-secret>@oss-cn-beijing-internal.aliyuncs.com/your-bucket/path/to/PolarAI.pdf');Method 2: Use a client program to write the data. You can write a script in any programming language that supports PostgreSQL, such as Python with the
psycopg2library, to read the local file content andINSERTit into thefile_contenttable inbyteaformat.
Chunk the imported document and store the results in the
file_chunktable.INSERT INTO file_chunk(file_id, chunk_id, chunk_content) SELECT id, -- Document ID (polar_ai.ai_rag_chunking(content, 'pdf')).* -- Chunking function FROM file_content;Embed the content to facilitate retrieval.
UPDATE file_chunk SET embedding = polar_ai.ai_rag_text_embedding(chunk_content);Create a high-performance HNSW index on the
embeddingcolumn for faster vector retrieval. HNSW is an efficient approximate nearest neighbor search algorithm suitable for high-dimensional vector data.-- Use an HNSW index and L2 (Euclidean) distance CREATE INDEX ON file_chunk USING HNSW (embedding vector_l2_ops);
Build a RAG query
Integrate vector retrieval, reranking, and LLM calls to implement a complete RAG Q&A process.
RAG execution steps
Convert the question into a vector.
Perform a vector search or hybrid search to find the required text chunks.
Rerank the retrieved text chunks to select the most relevant ones.
Submit the most relevant text chunks to the large language model to generate an answer.
Procedure
Create the custom function
ai_summarize: Create a custom SQL functionai_summarizeto encapsulate the logic for calling a large language model to generate the final answer. This function combines the question and the retrieved context into a structured prompt and calls the underlying text generation function.CREATE OR REPLACE FUNCTION public.ai_summarize(question text, contents text[]) RETURNS text LANGUAGE plpgsql AS $function$ DECLARE body text; BEGIN body = format('Answer the question based on the provided materials: %I. The provided materials are: %I', question, contents::text); RETURN polar_ai.ai_text_generation(body, '_polar4ai/_polar4ai_nl2sql_tongyi'); END; $function$;Execute an end-to-end RAG query. The following SQL statement demonstrates the entire RAG process, from vectorizing the question to generating a final answer:
-- RAG SELECT public.ai_summarize('What are the advantages of PolarAI?', array_agg(chunks)) FROM ( -- rerank SELECT unnest(polar_ai.ai_rag_rerank('What are the advantages of PolarAI?', array_agg(chunk_content))) as chunks FROM ( -- vector search SELECT chunk_content FROM file_chunk ORDER BY -- Vectorize the question polar_ai.ai_rag_text_embedding('What are the advantages of PolarAI?')::vector(1024) <-> embedding ASC LIMIT 10 ) t LIMIT 5 );
Related SQL
SQL | Description |
Parses and chunks the binary content of a document. | |
Converts text content into a vector. | |
Reranks retrieved text chunks based on their relevance to the question. |