Use built-in AI models for in-database inference

更新时间:
复制 MD 格式

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 pgml extension enabled on your instance

Choose a function

The pgml extension provides two functions. Which one to use depends on your task:

TaskFunctionWhen to use
Text embeddingpgml.embed()Converting text to vectors for similarity search, RAG pipelines, or clustering
Text classification, NERpgml.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

ModelLanguageMax tokensDimensionsSizeBest for
thenlper/gte-large-zhChinese51210241.25 GBHigh-quality Chinese embeddings
thenlper/gte-small-zhChinese5125120.12 GBLow-latency Chinese embeddings
thenlper/gte-largeEnglish51210241.25 GBHigh-quality English embeddings
thenlper/gte-smallEnglish5125120.21 GBLow-latency English embeddings
Alibaba-NLP/gte-Qwen2-7B-instructMultiple languages32,0003,58426.45 GBLong documents and multilingual content
Alibaba-NLP/gte-Qwen2-1.5B-instructMultiple languages32,0001,5366.62 GBMultilingual 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

ParameterDescriptionExample
transformerThe pre-trained model to use. See model names in the table above.'thenlper/gte-large'
inputsA single text string or an array of strings to embed.'The self-attention mechanism is widely used in neural networks.'
kwargsOptional 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

ModelLanguageMax tokensSizeBest for
lxyuan/distilbert-base-multilingual-cased-sentiments-studentMultiple languages512541 MBPositive/negative sentiment classification
Alibaba-NLP/gte-multilingual-reranker-baseMultiple languages8,192306 MBText 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

ParameterDescriptionExample
taskJSONB object specifying the task type and model. Set "task" to "text-classification".'{"task": "text-classification", "model": "lxyuan/distilbert-base-multilingual-cased-sentiments-student"}'
argsOptional JSONB with additional inference parameters. For available options, see the Hugging Face model documentation.'{"max_new_tokens": 32}'
inputsArray of text strings to classify.ARRAY['The product quality is good']
cacheWhether 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

ModelLanguageSizeBest for
Babelscape/wikineural-multilingual-nerMultiple languages709 MBLabeling 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

ParameterDescriptionExample
taskJSONB object specifying the task type and model. Set "task" to "token-classification".'{"task": "token-classification", "model": "Babelscape/wikineural-multilingual-ner"}'
argsOptional JSONB with additional inference parameters.'{"max_new_tokens": 32}'
inputsArray of text strings to extract entities from.ARRAY['Li Ming arrived in Hangzhou yesterday']
cacheWhether 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:

FieldDescriptionExample
wordThe recognized token from the input text"Li"
entityNER tag: B- marks the start of an entity, I- marks continuation. Types: PER (person), LOC (location), ORG (organization)"B-PER"
scoreConfidence score between 0 and 10.9668
start / endCharacter offsets of the token in the input string0 / 1
indexToken position in the tokenized sequence1

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

LimitDetail
Inference deviceOnly CPU is supported. GPU inference is not available.
Unsupported modelsIf a model you need is not in the supported lists above, submit a ticket to request it.