Integrate PolarDB-X with AI development frameworks
PolarDB-X natively supports the VECTOR data type and HNSW vector indexes, so a single database can serve as both a vector database and a relational database. This topic describes how to use two open-source Python integration packages, langchain-polardbx and llama-index-vector-stores-polardbx, to integrate PolarDB-X with the LangChain and LlamaIndex frameworks for vector storage, similarity search, and optional SQL query capabilities.
Use cases
AI applications that involve RAG knowledge bases, semantic search, and SQL agents typically need to handle two kinds of data: vector data for similarity search, and structured business data such as orders, users, and logs. A common approach is to introduce an additional vector database and synchronize data between it and the existing relational database. As data volume and application complexity grow, this architecture adds storage, synchronization, operations, and consistency costs.
Architecture
PolarDB-X natively supports the VECTOR data type and HNSW vector indexes, which allows vector storage and approximate nearest neighbor (ANN) retrieval to run directly inside the database. At the same time, PolarDB-X retains the SQL queries, transactions, and distributed scaling capabilities of a relational database. Therefore, PolarDB-X can serve as both the vector database and the relational database in many AI scenarios, reducing the number of system components and simplifying the data pipeline of AI applications.
To allow developers to use PolarDB-X directly from familiar AI development frameworks, PolarDB-X provides two Python integration packages. Choose the package that matches the framework you use.
|
Package |
Framework |
Installation command |
|
langchain-polardbx |
LangChain/LangGraph |
|
|
llama-index-vector-stores-polardbx |
LlamaIndex |
|
Procedure
The following steps install dependencies, create a vector table and write data, run a similarity search, and optionally enable SQL query integration. The vector-related code examples in Step 2 and Step 3 use OpenAI Embedding.
Step 1: Install dependencies
Install the package that matches the framework you use.
-
langchain-polardbx requires Python 3.9 or later.
-
llama-index-vector-stores-polardbx requires Python 3.10 or later.
LangChain
-
Requirements
Python 3.9 or later
-
Installation command
pip install langchain-polardbxAsync operations, MMR search, and SQL integration are optional dependencies in langchain-polardbx. Install the extras you need.
pip install langchain-polardbx[async] pip install langchain-polardbx[mmr] pip install langchain-polardbx[sql] -
(Optional) If you use OpenAI Embedding, also install the corresponding embedding package:
pip install langchain-openai -
If you use DashScope Embedding (Qwen):
pip install langchain-community dashscope
LlamaIndex
-
Requirements
Python 3.10 or later
-
Installation command
pip install llama-index-vector-stores-polardbxLlamaIndex includes async operations, MMR search, and SQL integration by default.
-
(Optional) If you use OpenAI Embedding, also install the corresponding embedding package:
pip install llama-index-embeddings-openai -
If you use DashScope Embedding (Qwen):
pip install llama-index-embeddings-dashscope
Step 2: Create a vector table and insert data
-
Enable vector indexes: Before you create a vector table, make sure that the PolarDB-X instance supports the vector index feature. Vector indexes are disabled by default in PolarDB-X. You must run the following command with an administrator account to enable them. The setting takes effect immediately for new connections, and no instance restart is required.
SET GLOBAL vidx_disabled = OFF; -
Example:
Note-
In the following examples, replace
host,port,user,password, anddatabasewith the actual connection information of your instance. -
distance_strategyspecifies the distance strategy. Valid values arecosine,euclidean, andinner_product. Theinner_productdistance strategy and advanced features such as index monitoring require a relatively recent version of PolarDB-X. The integration packages automatically detect the available capabilities and adapt.
LangChain
The following example calls
add_textsto insert text. The integration package automatically calls the embedding model to generate vectors and writes them to PolarDB-X.from langchain_polardbx import PolarDBXVectorStore from langchain_openai import OpenAIEmbeddings embeddings = OpenAIEmbeddings() vectorstore = PolarDBXVectorStore( host="<polardb-x-host>", port=<polardb-x-port>, user="<polardb-x-username>", password="<polardb-x-password>", database="<polardb-x-databasename>", embedding=embeddings, table_name="<polardb-x-tablename>", distance_strategy="cosine", # or "euclidean", "inner_product" ) # Insert text (automatically calls the embedding model to generate vectors and writes them to PolarDB-X) vectorstore.add_texts(["Hello world", "PolarDB-X supports vector search"])LlamaIndex
The following example creates an index from documents. Chunking, embedding, and writing are performed automatically.
from llama_index.vector_stores.polardbx import PolarDBXVectorStore from llama_index.core import StorageContext, VectorStoreIndex, Settings from llama_index.embeddings.openai import OpenAIEmbedding Settings.embed_model = OpenAIEmbedding() vector_store = PolarDBXVectorStore( host="<polardb-x-host>", port=<polardb-x-port>, user="<polardb-x-username>", password="<polardb-x-password>", database="<polardb-x-databasename>", table_name="<polardb-x-tablename>", embed_dim=1536, distance_strategy="cosine", ) # Create an index from documents (automatic chunking, embedding, and writing to PolarDB-X) from llama_index.core import Document documents = [Document(text="PolarDB-X supports vector search")] storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex.from_documents(documents, storage_context=storage_context) -
Step 3: Run a similarity search
After data is written, run a similarity search.
LangChain
results = vectorstore.similarity_search("PolarDB-X", k=2)
for doc in results:
print(doc.page_content)
LlamaIndex
query_engine = index.as_query_engine()
response = query_engine.query("What is PolarDB-X?")
print(response)
Step 4 (optional): Enable SQL queries
Both packages provide the PolarDBXSQLDatabase component, which wraps DDL reflection compatibility handling for PolarDB-X and serves as the base integration layer for the SQL capabilities of the frameworks. The create_partitioned_table helper function is also provided. It supports creating HASH/KEY/RANGE/LIST partitioned tables and broadcast tables.
LangChain
Install the SQL dependency first: pip install langchain-polardbx[sql].
from langchain_polardbx import PolarDBXSQLDatabase
db = PolarDBXSQLDatabase.from_uri(
"mysql+pymysql://<polardb-x-username>:<polardb-x-password>@<polardb-x-host>:<polardb-x-port>/<polardb-x-databasename>"
)
# List available tables
tables = db.get_usable_table_names()
# Get table schema information
info = db.get_table_info(["your_table"])
# Run SQL
result = db.run("SELECT COUNT(*) FROM your_table")
LlamaIndex
LlamaIndex:
from llama_index.vector_stores.polardbx import PolarDBXSQLDatabase
db = PolarDBXSQLDatabase.from_uri(
"mysql+pymysql://<polardb-x-username>:<polardb-x-password>@<polardb-x-host>:<polardb-x-port>/<polardb-x-databasename>"
)
# List available tables
tables = db.get_usable_table_names()
# Get table schema information
info = db.get_single_table_info("your_table")
# Run SQL
result = db.run_sql("SELECT COUNT(*) FROM your_table")
PolarDBXSQLDatabase connects directly to the SQL agent capabilities of the frameworks (such as create_sql_agent in LangChain and NLSQLTableQueryEngine in LlamaIndex) to convert natural language into SQL queries.
When you use SQLDatabase to inspect table schemas, SQLAlchemy may not display the VECTOR INDEX definition and may emit a warning. This is expected behavior and does not affect vector writes or retrieval.
Supported features
|
Feature |
langchain-polardbx |
llama-index-vector-stores-polardbx |
|
Vector storage (HNSW index) |
Yes |
Yes |
|
Distance strategy (cosine/euclidean/inner_product) |
Yes |
Yes |
|
Similarity search |
Yes |
Yes |
|
MMR search |
Yes (requires the |
Yes |
|
Metadata filtering |
Yes (dict + |
Yes ( |
|
|
Yes |
No |
|
Dynamic index management (create/delete/rebuild) |
Yes |
Yes |
|
Index health monitoring (statistics/diagnostics/warm-up) |
Yes |
Yes |
|
Async operations |
Yes (requires the |
Yes |
|
Partitioned vector table |
Yes |
Yes |
|
Custom column names and typed columns |
Yes |
Yes |
|
SQL database integration |
Yes (requires the |
Yes |
|
Partitioned table creation helper |
Yes |
Yes |
The main differences between the two packages are as follows:
-
The
$likefuzzy match is supported only by langchain-polardbx. -
In langchain-polardbx, async operations, MMR search, and SQL integration are optional dependencies and must be installed separately. llama-index-vector-stores-polardbx includes these features by default.
-
The API naming style of the two packages is largely aligned (for example, the distance parameter is
distance_strategyin both), but their framework integration approaches differ. For example, LlamaIndex usesStorageContext+VectorStoreIndex, while LangChain callsVectorStoremethods directly. For details, see the README of each package.
Summary
This topic describes how to use the open-source integration packages langchain-polardbx and llama-index-vector-stores-polardbx to integrate PolarDB-X with LangChain and LlamaIndex for vector storage, similarity search, and SQL query integration. Both packages are open-sourced on GitHub. For complete parameter descriptions, advanced configurations, and more usage examples such as partitioned vector tables, index health monitoring, and async operations, see the README of each package (langchain-polardbx, llama-index-vector-stores-polardbx).