Use built-in AI models for in-database inference
Moving data to external ML services adds pipeline complexity, increases latency, and creates data governance overhead. The pgml extension for AnalyticDB for PostgreSQL V7.0 lets you run inference directly on your database data using pre-trained models — no data movement required. This document shows you how to use pgml for text embedding, text classification, and named entity recognition (NER).
If you need a model that is not in the supported list, submit a ticket to request it from the development team.
Prerequisites
Before you begin, ensure that you have:
An AnalyticDB for PostgreSQL V7.0 instance
The
pgmlextension enabled on your instance
Choose a function
The pgml extension provides two functions. Which one to use depends on your task:
| Task | Function | When to use |
|---|---|---|
| Text embedding | pgml.embed() | Converting text to vectors for similarity search, RAG pipelines, or clustering |
| Text classification, NER | pgml.transform() | All other inference tasks — sentiment analysis, entity extraction, labeling |
Text embedding
Text embedding converts natural language text into floating-point vectors. These vectors power similarity search, Retrieval-Augmented Generation (RAG), and other semantic tasks.
Supported models
| Model | Language | Max tokens | Dimensions | Size | Best for |
|---|---|---|---|---|---|
thenlper/gte-large-zh | Chinese | 512 | 1024 | 1.25 GB | High-quality Chinese embeddings |
thenlper/gte-small-zh | Chinese | 512 | 512 | 0.12 GB | Low-latency Chinese embeddings |
thenlper/gte-large | English | 512 | 1024 | 1.25 GB | High-quality English embeddings |
thenlper/gte-small | English | 512 | 512 | 0.21 GB | Low-latency English embeddings |
Alibaba-NLP/gte-Qwen2-7B-instruct | Multiple languages | 32,000 | 3,584 | 26.45 GB | Long documents and multilingual content |
Alibaba-NLP/gte-Qwen2-1.5B-instruct | Multiple languages | 32,000 | 1,536 | 6.62 GB | Multilingual content with lower resource use |
Syntax
-- Single input: returns real[]
pgml.embed(transformer TEXT, inputs TEXT, kwargs jsonb DEFAULT '{}')
-- Batch input: returns real[][]
pgml.embed(transformer TEXT, inputs TEXT[], kwargs jsonb DEFAULT '{}')Currently, only CPU inference is supported. GPU inference is not available.
Parameters
| Parameter | Description | Example |
|---|---|---|
transformer | The pre-trained model to use. See model names in the table above. | 'thenlper/gte-large' |
inputs | A single text string or an array of strings to embed. | 'The self-attention mechanism is widely used in neural networks.' |
kwargs | Optional JSONB parameters, such as the inference device. For available options, see the Hugging Face model documentation. | '{"device": "cpu"}' |
Examples
Embed a single string
SELECT pgml.embed('thenlper/gte-small-zh', 'The self-attention mechanism is widely used in neural networks.');Result:
embed
------------------------------------------------------------
{0.011534364,-0.029397607, ... -0.00056651415,-0.05465962}Embed multiple strings in one call
SELECT pgml.embed(
'thenlper/gte-small-zh',
ARRAY[
'The self-attention mechanism is widely used in neural networks.',
'The core idea is to allow models to consider other elements in the sequence when processing a single element'
]
);Result:
embed
------------------------------------------------------------
{0.011534364,-0.029397607, ... -0.00056651415,-0.05465962}
{0.024123996,0.0360483154, ... -0.029659372,-0.0198373856}Embed existing table data
Generate embeddings from a column and store the results in a new table.
-- Source table
CREATE TABLE dump_table (id int, content text);
-- id | content
-- ---+--------------------------------------------------------
-- 1 | The self-attention mechanism generates attention scores...
-- 2 | Attention weights are generated by calculating the dot product...
-- Generate embeddings and save to result_table
CREATE TABLE result_table AS
SELECT id, content, pgml.embed('thenlper/gte-small-zh', content) AS embed
FROM dump_table;
-- Preview the first two dimensions of each embedding
SELECT id, content, embed[1:2] FROM result_table;Result:
id | content | embed
----+-------------------------------------------------+-------------------
1 | The self-attention mechanism generates... | {-0.020080239,...}
2 | Attention weights are generated by calculating..| {-0.036033697,...}
(2 rows)Text classification
Text classification assigns text to predefined categories. Common uses include sentiment analysis, automatic data labeling, and content review.
Supported models
| Model | Language | Max tokens | Size | Best for |
|---|---|---|---|---|
lxyuan/distilbert-base-multilingual-cased-sentiments-student | Multiple languages | 512 | 541 MB | Positive/negative sentiment classification |
Alibaba-NLP/gte-multilingual-reranker-base | Multiple languages | 8,192 | 306 MB | Text identification |
Syntax
CREATE FUNCTION pgml."transform"(
"task" jsonb,
"args" jsonb DEFAULT '{}',
"inputs" TEXT[] DEFAULT ARRAY[]::TEXT[],
"cache" bool DEFAULT false
) RETURNS jsonb
IMMUTABLE STRICT PARALLEL SAFE
LANGUAGE c;For text classification, set "task" to "text-classification" in the task parameter.
Parameters
| Parameter | Description | Example |
|---|---|---|
task | JSONB object specifying the task type and model. Set "task" to "text-classification". | '{"task": "text-classification", "model": "lxyuan/distilbert-base-multilingual-cased-sentiments-student"}' |
args | Optional JSONB with additional inference parameters. For available options, see the Hugging Face model documentation. | '{"max_new_tokens": 32}' |
inputs | Array of text strings to classify. | ARRAY['The product quality is good'] |
cache | Whether to cache the loaded model in memory. Set to true to speed up repeated calls. | true |
Examples
Classify a single string
SELECT pgml.transform(
task => '{"task": "text-classification",
"model": "lxyuan/distilbert-base-multilingual-cased-sentiments-student"}'::JSONB,
inputs => ARRAY['The product quality is good']
) AS positivity;The result shows a label of "positive" with a confidence score of 0.9924:
positivity
-----------------------------------------------------
[{"label": "positive", "score": 0.992497742176056}]
(1 row)Classify existing table data
Read rows from dump_table, classify the content column, and save a boolean pos flag to result_table.
CREATE TABLE result_table AS
SELECT
id,
content,
pgml.transform(
task => '{"task": "text-classification",
"model": "lxyuan/distilbert-base-multilingual-cased-sentiments-student"}'::JSONB,
inputs => ARRAY[content]::text[]
)->0->>'label' = 'positive' AS pos
FROM dump_table;Named entity recognition
Named entity recognition (NER) identifies and categorizes named entities in text — people (PER), locations (LOC), organizations (ORG), and more. Use this to extract structured information from unstructured text before further analysis.
Supported models
| Model | Language | Size | Best for |
|---|---|---|---|
Babelscape/wikineural-multilingual-ner | Multiple languages | 709 MB | Labeling people, places, and organizations in text |
Syntax
NER uses the same pgml.transform() function as text classification. Pass "token-classification" as the task type:
CREATE FUNCTION pgml."transform"(
"task" jsonb,
"args" jsonb DEFAULT '{}',
"inputs" TEXT[] DEFAULT ARRAY[]::TEXT[],
"cache" bool DEFAULT false
) RETURNS jsonb
IMMUTABLE STRICT PARALLEL SAFE
LANGUAGE c;Parameters
| Parameter | Description | Example |
|---|---|---|
task | JSONB object specifying the task type and model. Set "task" to "token-classification". | '{"task": "token-classification", "model": "Babelscape/wikineural-multilingual-ner"}' |
args | Optional JSONB with additional inference parameters. | '{"max_new_tokens": 32}' |
inputs | Array of text strings to extract entities from. | ARRAY['Li Ming arrived in Hangzhou yesterday'] |
cache | Whether to cache the loaded model in memory. | true |
Examples
Extract entities from a single string
SELECT pgml.transform(
task => '{"task": "token-classification",
"model": "Babelscape/wikineural-multilingual-ner"}'::JSONB,
inputs => ARRAY['Li Ming arrived in a city yesterday']
);Result:
transform
------------------------------------------------------------
[[{"end": 1, "word": "Li", "index": 1, "score": 0.9668, "start": 0, "entity": "B-PER"},
{"end": 2, "word": "Ming", "index": 2, "score": 0.9899, "start": 1, "entity": "I-PER"},
{"end": 8, "word": "Some", "index": 8, "score": 0.9998, "start": 7, "entity": "B-LOC"},
{"end": 9, "word": "City", "index": 9, "score": 0.9989, "start": 8, "entity": "I-LOC"}]]
(1 row)Each object in the result array describes one recognized token:
| Field | Description | Example |
|---|---|---|
word | The recognized token from the input text | "Li" |
entity | NER tag: B- marks the start of an entity, I- marks continuation. Types: PER (person), LOC (location), ORG (organization) | "B-PER" |
score | Confidence score between 0 and 1 | 0.9668 |
start / end | Character offsets of the token in the input string | 0 / 1 |
index | Token position in the tokenized sequence | 1 |
Extract entities from existing table data
CREATE TABLE result_table AS
SELECT
id,
content,
pgml.transform(
task => '{"task": "token-classification",
"model": "Babelscape/wikineural-multilingual-ner"}'::JSONB,
inputs => ARRAY[content]
) AS result
FROM dump_table;
SELECT * FROM result_table;Result:
id | content | result
----+-------------------------------------------+-------------------------------------------------------
1 | My name IS Wolfgang AND I live IN Berlin. | [[{"word": "Wolfgang", "entity": "B-PER", ...},
| | {"word": "Berlin", "entity": "B-LOC", ...}]]
2 | Li Ming will go to a certain city today. | [[{"word": "Li", "entity": "B-PER", ...},
| | {"word": "Ming", "entity": "I-PER", ...}, ...]]
(2 rows)Limits
| Limit | Detail |
|---|---|
| Inference device | Only CPU is supported. GPU inference is not available. |
| Unsupported models | If a model you need is not in the supported lists above, submit a ticket to request it. |