Perform vector retrieval using the MySQL protocol

Updated at:

PolarDB for MySQL supports efficient vector similarity search in SQL by using built-in vector data types, distance functions, and vector indexes. This feature is suitable for scenarios such as recommendation systems, chatbots, and image retrieval. Vector computing is integrated into the database kernel and supports ACID transactions. With In-Memory Column Index (IMCI) and algorithms such as HNSW, it provides exact KNN search with 100% recall and high-performance approximate (ANN) search.

Scope

Before you use this feature, make sure that your cluster meets the following requirements: The kernel version is MySQL 8.0.2, and the revision version must be 8.0.2.2.30 or later.

Version update history

Supported features vary by kernel version. We recommend that you upgrade to the latest version.

Feature

Minimum kernel version

Description

Basic vector features and the HNSW index algorithm.

8.0.2.2.30

Provides the basic vector search capabilities.

Added the FAISS_HNSW_FLAT and FAISS_HNSW_PQ index algorithms.

8.0.2.2.31

Introduces index algorithms implemented based on FAISS.

Modify or delete vector indexes.

8.0.2.2.32

Allows you to manage vector indexes dynamically by using the ALTER TABLE.

Vector type

Type definition

Define a vector column by using the CREATE TABLE or ALTER TABLE statement with the VECTOR(N) type.

  • N specifies the vector dimension. Valid values: 1 to 16383.

  • Each dimension of a vector is a single-precision floating-point number (4 bytes).

  • The vector type supports equality comparison only with the vector type. Comparison with any other type is not allowed.

  • A vector column cannot be used as a primary key, foreign key, unique key, or partition key.

Example

-- The following example defines column v1 in table t1 with a vector dimension of 4
CREATE TABLE t1 (id INT PRIMARY KEY, v1 VECTOR(4));
Note

If the defined dimension exceeds 16383, the following error is returned: Data size (xxx Bytes, xxx dimensions) exceeds VECTOR max (65532 Bytes, 16383 dimensions) for column: 'xxx'.

Type conversion

PolarDB provides the STRING_TO_VECTOR and VECTOR_TO_STRING functions to convert between the string format and the binary format.

String to binary (STRING_TO_VECTOR)

This function converts a vector in text format into the internal binary format of the database.

  • Input format: a sequence of floating-point numbers enclosed in square brackets [] and separated by , for example '[1.2, 3.4, 5.6]'.

    Note

    If the input string is in an incorrect format, the following error is returned: Data cannot be converted to a valid vector: 'xxx'.

  • Byte order: The converted binary data uses little-endian byte order. For example, the floating-point number 1.0 has the hexadecimal representation 0x3F800000, and after it is stored in the database, its binary HEX value is 0000803F. Pay attention to this when you serialize data across systems.

Example

SELECT STRING_TO_VECTOR('[1,2,3,4]');
+-------------------------------+
| STRING_TO_VECTOR('[1,2,3,4]') |
+-------------------------------+
|   �?   @  @@  �@              |
+-------------------------------+
SELECT HEX(STRING_TO_VECTOR('[1,2,3,4]'));
+------------------------------------+
| HEX(STRING_TO_VECTOR('[1,2,3,4]')) |
+------------------------------------+
| 0000803F000000400000404000008040   |
+------------------------------------+

Binary to string (VECTOR_TO_STRING)

This function converts binary vector data stored in the database into the string format.

Input format: Every 4 bytes represent the binary form of the floating-point number of one dimension of the vector, in little-endian byte order. For example, the floating-point number1.0'shexadecimal representation is0x3F800000,, and after it is stored in the database, its binary HEX value is 0000803F. Pay attention to this when you serialize data across systems.

Note

If the input Binary is in an incorrect format, the following error is returned: Data cannot be converted to a valid vector: ''.

Example

SELECT VECTOR_TO_STRING(0x0000803F000000400000404000008040);
+------------------------------------------------------+
| VECTOR_TO_STRING(0x0000803F000000400000404000008040) |
+------------------------------------------------------+
| [1.00000e+00,2.00000e+00,3.00000e+00,4.00000e+00]    |
+------------------------------------------------------+

Related examples

Create a new table that contains a vector column

CREATE TABLE t1 (id INT PRIMARY KEY, v1 VECTOR(4));

Add a vector column to an existing table

ALTER TABLE t1 ADD COLUMN v1 VECTOR(4);

Insert a vector

  • The vector is inserted as a string by using the STRING_TO_VECTOR function.

    INSERT INTO t1 (id, v1) VALUES (1, STRING_TO_VECTOR('[1.0, 2.0, 3.0, 4.0]'));
  • The vector is inserted in binary form.

    INSERT INTO t1 VALUES (2, 0x0000803F000000400000404000008040);

Insert or update a vector

The vector is inserted or updated as a string by using STRING_TO_VECTOR.

INSERT INTO t1 VALUES (1, STRING_TO_VECTOR('[1.0, 2.0, 3.0, 4.0]')) ON DUPLICATE KEY UPDATE v1 = STRING_TO_VECTOR('[1.0, 2.0, 3.0, 4.0]');

Update a vector

The vector is updated as a string by using STRING_TO_VECTOR. You can also update it directly in binary form.

UPDATE t1 SET v1 = STRING_TO_VECTOR('[1.0, 2.0, 3.0, 4.0]') WHERE id = 1;

Delete a vector

The vector is deleted as a string by using STRING_TO_VECTOR. You can also delete it directly in binary form.

DELETE FROM t1 WHERE v1 = STRING_TO_VECTOR('[1.0, 2.0, 3.0, 4.0]');

Use vector indexes

PolarDBCreate a vector index by defining a specially formatted string in the COMMENT of a column.

Prerequisites

Before you use a vector index, you must first complete the step Add a read-only IMCI node, and create a clustered columnar index for the column or the entire table. Only read-only nodes of the clustered columnar index can build vector indexes to support vector search.

Create a vector index

When you use the CREATE TABLE or ALTER TABLE, define a vector index by modifying the COMMENT of the column.

Syntax

COMMENT 'imci_vector_index=vector_index_algorithm(index_parameter_list) [other notes]'
  • imci_vector_index=: A fixed prefix that declares a vector index definition.

  • vector_index_algorithm: The index algorithm, such as HNSW, FAISS_HNSW_FLAT and FAISS_HNSW_PQ algorithms.

  • index_parameter_list: The parameters in the parentheses are index construction parameters.

    • Separate multiple parameters with spaces, commas, or semicolons. To avoid confusion, we recommend that you use commas consistently.

    • A single parameter is written as parameter_name=parameter_value or parameter_name:parameter_value. For example: HNSW(metric=COSINE,max_degree=16,ef_construction=300)

    • Even when all parameters use their default values, you must specify the parentheses. For example: COMMENT "imci_vector_index=HNSW() other notes"

Index algorithms

Algorithm

Scenario

HNSW

Implemented based onVSAG. It pursues high accuracy and uses more memory.

FAISS_HNSW_FLAT

Implemented based on FAISS. It pursues high accuracy and uses more memory.

FAISS_HNSW_PQ

Implemented based on FAISS. It compresses vectors by using product quantization (PQ) to reduce memory usage, at the cost of some accuracy.

Index parameters

Parameter

Alias

Applicable algorithms

Purpose

Valid values/Range

Default

metric

distance

  • HNSW

  • FAISS_HNSW_FLAT

  • FAISS_HNSW_PQ

The vector similarity metric.

  • COSINE (cosine distance)

  • INNER_PRODUCT (inner product)

  • EUCLIDEAN (Euclidean distance)

Note

Only uppercase is supported.

COSINE

max_degree

M

  • HNSW

  • FAISS_HNSW_FLAT

  • FAISS_HNSW_PQ

The maximum number of connections per node in the graph.

A positive integer. A larger value makes the graph denser, slows down construction, and increases memory usage, but may improve query accuracy. Recommended range: 16 to 64.

16

ef_construction

-

  • HNSW

  • FAISS_HNSW_FLAT

  • FAISS_HNSW_PQ

The number of neighbor nodes searched during index construction.

A positive integer. A larger value improves index quality but increases construction time. Recommended value: 100 to 500.

200

pq_m

-

FAISS_HNSW_PQ

The number of product quantization (PQ) subspaces.

A positive integer that divides the vector dimension. The vector dimension must be divisible by pq_m. A larger value improves accuracy but uses more memory.

1

pq_nbits

-

FAISS_HNSW_PQ

The number of bits used for the quantization of each subspace in product quantization (PQ).

A positive integer less than or equal to 24. It is usually set to 8, which means that each subspace has 256 centroids.

8

Example 1: Define a vector index when you create a table

-- Option 1: Enable the clustered columnar index for the entire table, and then define a vector index on column v1
CREATE TABLE t1 (
    id INT PRIMARY KEY,
    v1 VECTOR(4) COMMENT 'imci_vector_index=HNSW(metric=COSINE, max_degree=16)'
) COMMENT 'COLUMNAR=1';

-- Option 2: Enable the clustered columnar index and a vector index only for column v1
CREATE TABLE t1 (
    id INT PRIMARY KEY,
    description TEXT,
    v1 VECTOR(4) COMMENT 'COLUMNAR=1, imci_vector_index=HNSW(metric=COSINE)'
);

Example 2: Add a vector index to an existing table

-- Assume that the existing table is t1
CREATE TABLE t1 (
    id int auto_increment PRIMARY KEY,
    v1 vector(4)
);

-- Option 1: Add a table-level clustered columnar index and modify the comment of the VECTOR column to specify the vector index algorithm and parameters
ALTER TABLE t1 comment "COLUMNAR=1", MODIFY COLUMN v1 vector(4) COMMENT "imci_vector_index=HNSW(metric=COSINE,max_degree=16,ef_construction=300)";


-- Option 2: Create a clustered columnar index only for column v1. When the clustered columnar index is initialized, a vector index is automatically created based on the comment of column v1
ALTER TABLE t1 MODIFY COLUMN v1 vector(4) COMMENT "COLUMNAR=1 imci_vector_index=HNSW(metric=COSINE,max_degree=16,ef_construction=300)";

Parameter description

Parameter

Description

imci_enable_inline_vector_index

Specifies whether to allow vector index creation.

  • ON (default): After it is enabled, read-only nodes of the clustered columnar index create vector indexes based on the comments of vector columns when the clustered columnar index is created.

  • OFF: After it is disabled, read-only nodes of the clustered columnar index no longer create vector indexes for vector columns when the clustered columnar index is created. Existing vector indexes created before it is disabled continue to be built, but are no longer loaded or built after a restart.

imci_vector_index_dump_rows_threshold

Controls the incremental write size of vector indexes. Background tasks periodically check the delta between the current vector index snapshot position and the clustered columnar index snapshot position. When the number of incremental rows exceeds this threshold, the background task commits the new data rows to append them to the vector index.

  • Valid values: 1 to 4294967295.

  • Default value: 1000.

  • Unit: rows.

Modify a vector index

Note

Revision version 8.0.2.2.32 or later supports modifying the algorithm and parameters of a vector index by modifying the comment of a column of the vector type.

  • Modify the vector index algorithm.

    CREATE TABLE t1 (
        id int auto_increment PRIMARY KEY,
        v1 vector(4) COMMENT "imci_vector_index=HNSW(metric=COSINE,max_degree=16,ef_construction=300)"
    ) COMMENT 'COLUMNAR=1';
    
    -- Change the index algorithm from HNSW to the FAISS-based HNSW algorithm
    ALTER TABLE t1 modify column v1 vector(4) COMMENT "imci_vector_index=FAISS_HNSW_FLAT(metric=COSINE,max_degree=16,ef_construction=300)";
  • Modify vector index parameters.

    CREATE TABLE t1 (
        id int auto_increment PRIMARY KEY,
        v1 vector(4) COMMENT "imci_vector_index=HNSW(metric=COSINE,max_degree=16,ef_construction=300)"
    ) COMMENT 'COLUMNAR=1';
    
    -- Modify index parameters: change max_degree of HNSW from 16 to 32
    ALTER TABLE t1 modify column v1 vector(4) COMMENT "imci_vector_index=HNSW(metric=COSINE,max_degree=32,ef_construction=300)";

Delete a vector index

  • Delete the vector index when you delete the clustered columnar index.

    CREATE TABLE t1 (
        id int auto_increment PRIMARY KEY,
        v1 vector(4) COMMENT "imci_vector_index=HNSW(metric=COSINE,max_degree=16,ef_construction=300)"
    ) COMMENT 'COLUMNAR=1';
    
    -- A vector index cannot exist independently of the clustered columnar index, so it is deleted in cascade
    ALTER TABLE t1 COMMENT 'COLUMNAR=0';
  • Delete only the vector index.

    Note

    Revision version 8.0.2.2.32 or later supports deleting a vector index by deleting the comment of a column of the vector type.

    CREATE TABLE t1 (
        id int auto_increment PRIMARY KEY,
        v1 vector(4) COMMENT "imci_vector_index=HNSW(metric=COSINE,max_degree=16,ef_construction=300)"
    ) COMMENT 'COLUMNAR=1';
    
    -- Delete the vector index by deleting the comment of the column of the vector type
    ALTER TABLE t1 modify column v1 vector(4) COMMENT "";

Vector queries

Approximate nearest neighbor (ANN) search

Approximate nearest neighbor (ANN) search uses vector indexes to accelerate queries.

Usage limits

The optimizer uses a vector index only when it identifies a specific SQL pattern. A query must meet all the following conditions:

  • The query must contain both the ORDER BY and LIMIT clauses.

  • ORDER BY's first expression must be DISTANCE(...).

  • ORDER BY DISTANCE(...)'s sort direction must be ASC.

  • DISTANCE(...) must reference a column that has a usable vector index.

  • DISTANCE(...) expression's distance parameter metric must be consistent with the distance parameter specified in Create a vector index: metric. For example, if the vector index is built with the COSINE distance, DISTANCEE(...) must also specify COSINE.

  • If the query contains JOIN, the execution plan must use a right deep join tree structure, and the column referenced in the DISTANCE(...) expression must come from the driving table of the join.

  • The query cannot contain a GROUP BY clause. If you need aggregation, perform the vector search in a subquery.

Steps to enable ANN search

  1. Enable vector index acceleration
    Run the following command in the session to allow the optimizer to use vector indexes.

    SET imci_enable_vector_search = ON;
  2. Force queries to use the clustered columnar index execution plan
    To ensure that queries can access the vector indexes built on the clustered columnar index, you must force queries to use the clustered columnar index path.

    SET cost_threshold_for_imci = 0;
    Important

    SET cost_threshold_for_imci = 0; is a session-level setting that forces all queries in the session to use the clustered columnar index. This may degrade the performance of queries that would otherwise run efficiently on row store (for example, point queries by primary key). Therefore, we recommend that you use this setting only in sessions that perform vector search, and never set it as a global parameter.

  3. Write a query that meets the ANN trigger conditions
    Execute a SQL statement that meets the constraints to perform approximate nearest neighbor search by using the vector index.

    -- Find the top 5 most similar records
    SELECT id, v1
    FROM t1
    WHERE category_id = 123 -- You can add additional conditions
    ORDER BY DISTANCE(v1, STRING_TO_VECTOR('[...]'), 'COSINE') ASC
    LIMIT 5;

    Correcting a non-compliant query (using GROUP BY as an example):

    -- Incorrect: GROUP BY conflicts with ORDER BY DISTANCE()
    -- SELECT category_id, COUNT(*) FROM t1 GROUP BY category_id ORDER BY DISTANCE(v1, STRING_TO_VECTOR('[...]'), 'COSINE') ASC LIMIT 5;
    
    -- Correct: run the ANN search in a subquery first, and then aggregate the results
    SELECT category_id, COUNT(*)
    FROM (
        SELECT id, category_id
        FROM t1
        ORDER BY DISTANCE(v1, STRING_TO_VECTOR('[...]'), 'COSINE') ASC
        LIMIT 100 -- Recall the 100 nearest neighbors first
    ) AS nearest_neighbors
    GROUP BY category_id;
  4. You can use the EXPLAIN statement to determine whether vector index acceleration for approximate nearest neighbor search takes effect. If the execution plan contains Vector Search, the feature takes effect.

    EXPLAIN SELECT * FROM t1 ORDER BY DISTANCE(v1, STRING_TO_VECTOR('[1.2, 2.3, 3.4, 4.5]'), 'COSINE') LIMIT 2;

    Sample output:

    +----+---------------------------+------+--------+--------+---------------------------------------------------------------------------------------+
    | ID | Operator                  | Name | E-Rows | E-Cost | Extra Info                                                                            |
    +----+---------------------------+------+--------+--------+---------------------------------------------------------------------------------------+
    |  1 | Select Statement          |      |        |        | IMCI Execution Plan (max_dop = 2, max_query_mem = 429496729)                          |
    |  2 | └─Compute Scalar          |      | 2      | 0.00   |                                                                                       |
    |  3 |   └─Limit                 |      | 2      | 0.00   | Offset=0 Limit=2                                                                      |
    |  4 |     └─Sort                |      | 2      | 0.00   | Sort Key: VECTOR_DISTANCE(t1.v1,"[1.200000,2.300000,3.400000,4.500000]","COSINE") ASC |
    |  5 |       └─Vector Search     | t1   | 2      | 0.00   |                                                                                       |
    +----+---------------------------+------+--------+--------+---------------------------------------------------------------------------------------+

Parameter description

Parameter

Description

imci_enable_vector_search

The switch that controls whether vector indexes accelerate approximate nearest neighbor (ANN) search.

  • ON (default): Enables vector index acceleration for approximate nearest neighbor (ANN) search.

  • OFF: Disables vector index acceleration for approximate nearest neighbor (ANN) search.

imci_hnswpq_k_factor

When the vector index uses the FAISS_HNSW_PQ algorithm, the multiplier for expanded recall in vector search.

  • Valid values: 1 to UINT32_MAX.

  • Default value: 1.

  • Unit: multiple.

Note

When a vector query recalls K approximate nearest neighbors (ANNs), the executor recalls K * imci_hnswpq_k_factor results from the HNSW PQ index, precisely sorts these results by using the original vectors, and returns the top K results in order.

View vectors

SELECT VECTOR_TO_STRING(v1) FROM t1;

Distance calculation

You can use the DISTANCE function to calculate the similarity between two vectors in the specified way.

DISTANCE(vector1, vector2, '<metric>')

metricParameter description

Parameter

Description

COSINE

Cosine similarity. Measures the directional similarity between two vectors. The result is the cosine of the angle between the vectors. A smaller value indicates higher similarity.

EUCLIDEAN

Euclidean distance. Measures the straight-line distance between two vectors or points in Euclidean space. A smaller value indicates higher similarity.

DOT

Dot product. The sum of the products of the corresponding components of two vectors. A smaller value indicates higher similarity.

Example

SELECT DISTANCE(v1, STRING_TO_VECTOR('[1.2,2.3,3.4,4.5]'), 'COSINE') FROM t1;

Exact nearest neighbor (KNN) search

Exact search scans all data to calculate distances and guarantees 100% recall. It does not depend on vector indexes and is suitable for small datasets.

-- Find the 10 records most similar to the target
SELECT id, VECTOR_TO_STRING(v1) FROM t1
ORDER BY DISTANCE(v1, STRING_TO_VECTOR('[...]'), 'COSINE') LIMIT 10;

Example

SELECT id, VECTOR_TO_STRING(v1) FROM t1 ORDER BY DISTANCE(v1, STRING_TO_VECTOR('[1.2,2.3,3.4,4.5]'), 'COSINE') LIMIT 1;

Vector queries with predicates

You can use additional columns as predicates to filter vector query results. For example:

SELECT * FROM t1 WHERE id < 10 ORDER BY DISTANCE(v1, STRING_TO_VECTOR('[1.2, 2.3, 3.4, 4.5]'), 'COSINE') LIMIT 2;

When you perform vector queries by using SQL statements that contain predicates, you can adjust the values of related parameters to control the order of vector index recall and predicate filtering.

Execution methods

Vector search is usually accompanied by filtering on other attributes. The optimizer intelligently chooses an execution strategy based on the selectivity of the filter conditions:

  • Prefilter: When the filter conditions greatly reduce the amount of data (for example, when the number of matching rows is less than imci_vector_search_prefilter_rows, default: 10000), the system first filters the entire table by using the predicate to obtain the matching records, then sorts these records, and finally returns the number of records specified by LIMIT in order.

  • Postfilter: When the selectivity of the filter conditions is low (for example, when the match ratio is higher than imci_vector_search_filter_pct, default: 20%), the system first uses the vector index for recall, and then applies the predicate filter to the recalled results. If the number of results after filtering is less than the number specified by LIMIT, the process is repeated.

  • Inline filter: If the optimizer does not choose prefilter or postfilter, it uses the inline filter method. The system first filters the entire table by using the predicate and builds a bitmap filter based on the row IDs of the matching records. Then, it performs recall by using the vector index. During vector index search, the system uses the bitmap filter to screen results so that the returned most similar records meet the predicate conditions.

Adaptive execution optimization

Because the optimizer may misestimate the number of rows matched by predicate filtering, the selected execution method may not be optimal. Therefore, adaptive execution is used to dynamically switch the execution method based on the actual number of matching rows during execution.

When an inline filter is used to execute a vector query that contains a predicate, if the actual number of matching records after filtering the entire table is less than imci_vector_search_prefilter_rows, the execution method is dynamically switched to prefilter.

Partition optimization

Vector queries usually contain predicates such as tenant IDs or tags. For such queries, you can use the LIST DEFAULT HASH partitioning method to create separate LIST partitions for tenants or tags with large amounts of data, and create DEFAULT HASH partitions for other tenants or tags. The optimizer can identify such queries and, based on the partition pruning result, choose postfilter for vector queries of large tenants or tags, and choose prefilter or inline filter for vector queries of other tenants, so that the optimal execution method is selected for tenants or tags of different sizes.

Parameter description

Parameter

Description

imci_vector_search_filter_pct

When the estimated selectivity of predicate filtering is greater than or equal to this value, vector index recall is preferred.

  • Valid values: 0 to 100.

  • Default value: 20.

  • Unit: %.

With the current default value, when the estimated selectivity of the predicate is greater than or equal to 20%, the system first uses the vector index for recall, and then applies the predicate filter to the recalled results.

imci_enable_vector_search_inline_filter

The switch that controls whether vector queries with predicates use the inline filter.

  • OFF (default): Disabled.

  • ON: Enabled.

imci_vector_search_prefilter_rows

When the estimated number of rows matched by predicate filtering is less than this value, prefilter is preferred for recall.

  • Valid values: 0 to UINT64_MAX.

  • Default value: 10000.

  • Unit: rows.

With the current default value, when the estimated number of rows matched by predicate filtering is less than 10,000, prefilter is preferred to recall the matching records; the records are then sorted and the number of rows specified by LIMIT is returned.

Monitor vector index status

Vector index data building and clustered columnar index snapshot advancement are different background tasks. With continuous writes, the vector index snapshot position may lag behind the clustered columnar index data snapshot. Before you perform vector search, you must confirm that the vector index is available. System views show the vector index status, including the vector index snapshot position and the status of vector indexes on vector columns.

Vector index snapshot position

INFORMATION_SCHEMA.IMCI_INDEX_STATS view: The VECTOR_ROWS column shows the number of vectors in the vector index snapshot loaded by the clustered columnar index. If the value is 0, no vector index is available on the current clustered columnar index: the table may not have any vector index yet, or the vector index that was just created has not generated a valid vector index snapshot.

You can also compare this value with the INFORMATION_SCHEMA.IMCI_INDEXES view's ROW_ID column to roughly estimate the vector index data build delay. Even if a delay exists, the vector index remains available. During search, the system automatically handles data that has not yet been written to the vector index.

Physical vector index status

INFORMATION_SCHEMA.IMCI_VECTOR_INDEX_STATS system view shows the status information of each physical vector index in the vector index snapshot. The table schema is described as follows:

Column

Description

SCHEMA_NAME

The database name.

TABLE_NAME

The table name.

COLUMN_NAME

The vector column name.

VECTORS

The actual number of vectors in the vector index. Because NULL marker values and rows deleted during construction are excluded, this value is usually smaller than VECTOR_ROWS.

MEMORY_USAGE

Memory usage.

STORAGE_USAGE

The size of the persisted file.

INDEX_TYPE

The index type. Currently, only HNSW is supported.

INDEX_PARAMETERS

The vector index construction parameters in JSON format.

This view outputs the memory status and statistics of the vector index for each column with vector indexes enabled, and is not directly related to vector index availability.

Note
  • Approximate vector search cannot be performed on any column that is not included in the query results of this view.

  • In this view, if the VECTORS column displays 0, the vector index is not necessarily unavailable. This usually happens because no incremental build or approximate query has been executed since the cluster restarted, so the persisted vector index data has not been loaded and the exact vector count cannot be obtained temporarily. Use the INFORMATION_SCHEMA.IMCI_INDEX_STATS view's VECTOR_ROWS column as the authoritative source of vector snapshot information.

Example

  1. To ensure that the vector index can be built properly with a small amount of data in the following example, go to the PolarDB console and set the imci_vector_index_dump_rows_thresholdvalue to 1.

  2. Create a test table and insert data:

    CREATE TABLE t1 (
        id int auto_increment PRIMARY KEY,
        v1 vector(4) COMMENT "imci_vector_index=HNSW(metric=COSINE,max_degree=16,ef_construction=300)"
    ) comment "COLUMNAR=1";
    
    INSERT INTO t1 VALUES(1, STRING_TO_VECTOR('[1.1,1.2,1.3,1.4]')), (2, STRING_TO_VECTOR('[2,2.2,2.4,2.6]'));
  3. Check the index snapshot status and the vector index status:

    SELECT schema_name,table_name,row_id FROM information_schema.imci_indexes;
    +-------------+------------+--------+
    | schema_name | table_name | row_id |
    +-------------+------------+--------+
    | test        | t1         |      2 |
    +-------------+------------+--------+
    1 row in set (0.00 sec)
    
    SELECT schema_name,table_name,vector_rows FROM information_schema.imci_index_stats;
    +-------------+------------+-------------+
    | schema_name | table_name | vector_rows |
    +-------------+------------+-------------+
    | test        | t1         |           2 |
    +-------------+------------+-------------+
    1 row in set (0.00 sec)
    
    SELECT schema_name,table_name,column_name,vectors FROM information_schema.imci_vector_index_stats;
    +-------------+------------+-------------+---------+
    | schema_name | table_name | column_name | vectors |
    +-------------+------------+-------------+---------+
    | test        | t1         | v1          |       2 |
    +-------------+------------+-------------+---------+
    1 row in set (0.00 sec)
  4. Then execute the following write:

    INSERT INTO t1 VALUES(3, STRING_TO_VECTOR("[8.8,8.88,8.888,8.8888]"));

    You can observe that in the query results of INFORMATION_SCHEMA.IMCI_VECTOR_INDEX_STATS the value of the VECTORS field is 3 (increased by 1), which indicates that the data inserted by the preceding INSERT statement has been written to the vector index by the background task:

    SELECT schema_name,table_name,column_name,vectors FROM information_schema.imci_vector_index_stats;
    +-------------+------------+-------------+---------+
    | schema_name | table_name | column_name | vectors |
    +-------------+------------+-------------+---------+
    | test        | t1         | v1          |       3 |
    +-------------+------------+-------------+---------+
    1 row in set (0.00 sec)
  5. Then restart the read-only node of the clustered columnar index and check the index status:

    Important

    Restarting the read-only node of the clustered columnar index makes the node unavailable for a short period of time.

    SELECT schema_name,table_name,row_id,state FROM information_schema.imci_indexes;
    +-------------+------------+--------+-----------+
    | schema_name | table_name | row_id | state     |
    +-------------+------------+--------+-----------+
    | test        | t1         |      3 | COMMITTED |
    +-------------+------------+--------+-----------+
    1 row in set (0.00 sec)
    
    SELECT schema_name,table_name,vector_rows FROM information_schema.imci_index_stats;
    +-------------+------------+-------------+
    | schema_name | table_name | vector_rows |
    +-------------+------------+-------------+
    | test        | t1         |           3 |
    +-------------+------------+-------------+
    1 row in set (0.00 sec)
    
    SELECT schema_name,table_name,column_name,vectors FROM information_schema.imci_vector_index_stats;
    +-------------+------------+-------------+---------+
    | schema_name | table_name | column_name | vectors |
    +-------------+------------+-------------+---------+
    | test        | t1         | v1          |       0 |
    +-------------+------------+-------------+---------+
    1 row in set (0.00 sec)

    You can see that IMCI_VECTOR_INDEX_STATS in the system view, VECTORS is 0, while the vector index snapshot position is 3. Use the execution plan to confirm vector index availability, and check the vector index status again after executing an approximate query:

    SET cost_threshold_for_imci = 0;
    
    
    EXPLAIN SELECT * FROM t1 ORDER BY DISTANCE(v1, STRING_TO_VECTOR("[1.2, 2.3, 3.4, 4.5]"), "COSINE") LIMIT 1;
    +----+-----------------------+------+--------+--------+---------------------------------------------------------------------------------------+
    | ID | Operator              | Name | E-Rows | E-Cost | Extra Info                                                                            |
    +----+-----------------------+------+--------+--------+---------------------------------------------------------------------------------------+
    |  1 | Select Statement      |      |        |        | IMCI Execution Plan (max_dop = 4, max_query_mem = 858993459)                          |
    |  2 | +-Compute Scalar      |      |        |        |                                                                                       |
    |  3 |   +-Limit             |      |        |        | Offset=0 Limit=1                                                                      |
    |  4 |     +-Sort            |      |        |        | Sort Key: VECTOR_DISTANCE(t1.v1,"[1.200000,2.300000,3.400000,4.500000]","COSINE") ASC |
    |  5 |       +-Vector Search | t1   |        |        |                                                                                       |
    +----+-----------------------+------+--------+--------+---------------------------------------------------------------------------------------+
    5 rows in set (0.00 sec)
    
    SELECT id, vector_to_string(v1) FROM t1 ORDER BY DISTANCE(v1, STRING_TO_VECTOR("[1.2, 2.3, 3.4, 4.5]"), "COSINE") LIMIT 1;
    +----+---------------------------------------------------+
    | id | vector_to_string(v1)                              |
    +----+---------------------------------------------------+
    |  2 | [2.00000e+00,2.20000e+00,2.40000e+00,2.60000e+00] |
    +----+---------------------------------------------------+
    1 row in set (0.00 sec)
    
    SELECT schema_name,table_name,column_name,vectors FROM information_schema.imci_vector_index_stats;
    +-------------+------------+-------------+---------+
    | schema_name | table_name | column_name | vectors |
    +-------------+------------+-------------+---------+
    | test        | t1         | v1          |       3 |
    +-------------+------------+-------------+---------+
    1 row in set (0.00 sec)

    You can observe that after the approximate query is executed, the vector index is loaded into memory and the number of vectors returns to 3.

FAQ

Why is the index not used for my vector query?

Troubleshoot the issue by following these steps:

  1. Confirm that you have executed SET imci_enable_vector_search = ON; and SET cost_threshold_for_imci = 0;.

  2. Use EXPLAIN to check the execution plan and confirm that the Extra Info column contains the Vector Search operator.

  3. Check whether the SQL statement meets all the constraints listed in Approximate nearest neighbor (ANN) search. A common mistake is missing LIMIT or using the wrong sort direction of ORDER BY.

  4. Check whether the DISTANCE(...) expression's distance parameter metric is exactly the same as the distance parameter specified in Create a vector index: metric. For example, if the vector index is built with the COSINE distance, DISTANCEE(...) must also specify COSINE

Error when creating a vectorERROR 9040 (HY000): Data size exceeds VECTOR max. What is the cause?

The defined vector dimension exceeds the maximum limit of 16383. Decrease the value of N in VECTOR(N).

After you restart the read-only node of the clustered columnar index, the number of vectors shown in monitoringVECTORSis 0. Is the index lost?

The index is not lost. This is expected behavior. Index data is persisted on disk and is loaded into memory when the first query is executed after the restart. For the diagnostic procedure, see Monitor vector index status.

pq_mrequires the vector dimension to be divisible. What if the dimension is a prime number, such as 1023?

In this case, you cannot use the FAISS_HNSW_PQ index. You have the following options:

  1. Choose another index: Use HNSW or FAISS_HNSW_FLAT, which do not have this limitation but use more memory.

  2. Adjust the data dimension: In the application layer, reduce or pad the vector dimension so that it is divisible by pq_m (for example, 8, 16, or 32).