Skip to main content
Beta feature Advice on use of Beta features This topic introduces the vector index feature of the database and how to perform an approximate nearest neighbor search (ANNS) with it.

Overview

Currently, the database supports vector indexing at the Segment file level. The index maps each search item to its row ID within Segment files, allowing fast data retrieval by directly locating the corresponding data rows without brute-force vector distance calculations. Use hnsw for a graph index or ivf for an inverted file. For new IVF indexes, we recommend index_type = ivf. Specify the encoding separately with quantizer to use product quantization (pq) or scalar quantization (sq4 or sq8) with the same IVF syntax. The database continues to support index_type = ivfpq for compatibility with existing DDL. With matching build parameters, this legacy syntax and index_type = ivf with quantizer = pq build the same type of IVF-PQ index and support the same queries.

Inverted File with Product Quantization (IVFPQ)

Inverted File with Product Quantization (IVFPQ) is a method for approximate nearest neighbor search in large-scale high-dimensional vectors, commonly used in vector retrieval tasks within deep learning and machine learning. IVFPQ consists of two main components: the inverted file and product quantization.
  • Inverted File: This component is an indexing method. It divides the dataset into multiple clusters (or Voronoi cells), each with a centroid (seed point), and assigns each data point (vector) to its nearest cluster center. For a vector search, IVFPQ only needs to search the nearest cluster, significantly reducing the search scope and complexity.
  • Product Quantization: This component is a data compression technique. It splits high-dimensional vectors into subvectors and quantizes each subvector to map it to the nearest point in a predefined set, reducing storage and computation costs while retaining high precision.
By combining inverted files and product quantization, IVFPQ enables efficient approximate nearest neighbor search in large, high-dimensional datasets.

Hierarchical Navigable Small World (HNSW)

Hierarchical Navigable Small World (HNSW) is a graph-based algorithm for high-dimensional nearest neighbor search, also widely used in vector retrieval tasks. HNSW builds a hierarchical graph structure in which each layer is a navigable small world (NSW) graph. In the graph, each vertex represents a data point, and edges indicate similarity between vertices. The higher layers of the graph contain fewer vertices with sparser connections for fast global search, while the lower layers include all vertices with denser connections for precise local search. For a vector search, HNSW searches at the top layer first, quickly identifying an approximate nearest neighbor region, then moves down layer by layer to find the exact nearest neighbor at the bottom layer. HNSW offers both efficiency and precision, making it adaptable to various data and query distributions.

Comparison between IVFPQ and HNSW

  • Data Compression Ratio: IVFPQ has a higher compression ratio (around 1:0.15). The indexing calculation only provides preliminary sorting results after rough ranking because PQ will compress the vectors. It requires additional fine ranking for final sorting results, leading to higher computation and latency. HNSW has a lower compression ratio (around 1:0.8) and provides precise ranking without extra processing, resulting in lower computation costs and latency and higher storage costs.
  • Recall Adjustment: Both indexes support recall rate tuning through parameter adjustments, but IVFPQ incurs higher computation costs at similar recall rates.
  • Caching Strategy: IVFPQ allows balancing memory cost and computation latency by adjusting the cache proportion of index blocks, while HNSW currently only supports full-file caching.

Usage

Prerequisites

  • Each table supports only one vector index.
  • The indexed column must be ARRAY<FLOAT> NOT NULL.
  • Only native DUPLICATE KEY and PRIMARY KEY tables support vector indexing.

Create vector index

This tutorial creates vector indexes while creating tables. You can also append vector indexes to an existing table. See Append vector index for detailed instructions.
  • The following example creates an HNSW vector index hnsw_vector on column vector in table hnsw.
  • The following example creates an IVF-PQ index with the recommended syntax. To use the equivalent legacy definition, change index_type to ivfpq, remove quantizer, and rename m_pq to m_ivfpq and nbits_pq to nbits. Keep the other parameters and their values unchanged.
  • The following example creates an HNSW vector index on a cloud-native table in a shared-data cluster using async build mode.
    You can view the asynchronous build progress by querying information_schema.partitions_meta.
    • When MIN_VI_BUILT_VERSION equals VISIBLE_VERSION, it indicates that the indexes of all tablets within the partition have reached the visible versions.
    • When MIN_VI_BUILT_VERSION is less than VISIBLE_VERSION, it indicates that at least one index is under construction. Queries involving such segments will fall back to a brute-force scan.
    • When MIN_VI_BUILT_VERSION is less than MAX_VI_BUILT_VERSION, it indicates that different tablets vary in index building progress.

Index construction parameters

USING VECTOR
  • Default: N/A
  • Required: Yes
  • Description: Creates a vector index.
index_type
  • Default: N/A
  • Required: Yes
  • Description: Valid values are hnsw, ivfpq, and ivf. For ivf, explicitly set quantizer to pq, sq4, or sq8.
dim
  • Default: N/A
  • Required: Yes
  • Description: Dimension of the index. After the index is built, vectors that do not meet the dimension requirements will be rejected for loading into the base column. It must be an integer greater than or equal to 1.
metric_type
  • Default: N/A
  • Required: Yes
  • Description: Metric type (measurement function) of the vector index. Valid values:
    • l2_distance: Euclidean distance. The smaller the value, the higher the similarity.
    • cosine_similarity: Cosine similarity. The larger the value, the higher the similarity.
    • inner_product: Inner product. The larger the value, the higher the similarity. Unlike cosine similarity, inner product preserves vector magnitude. Use inner_product for exact evaluation and approx_inner_product for vector-index top-k or range queries.
is_vector_normed
  • Default: false
  • Required: No
  • Description: Whether the vectors are normalized. Valid values are true and false. It takes effect only when metric_type is cosine_similarity. If the vectors are normalized, the value of the calculated distances will be within [-1, 1]. The vectors must satisfy that the sum of the squares is 1, otherwise an error is returned.
index_build_threshold
  • Default: 10000 (determined by the BE configuration item config_vector_index_default_build_threshold)
  • Required: No
  • Description: Minimum number of segment rows to build the index. Smaller segments use brute-force search. An explicit threshold must be a positive integer. For IVF-SQ it must be at least nlist, for IVF-PQ (including legacy ivfpq) at least max(nlist, 256), and for HNSW-PQ at least 2^nbits_pq. When omitted, the BE uses its configured threshold and enforces the training minimum for both ivf and ivfpq.
index_build_mode
  • Default: sync
  • Required: No
  • Description: Index build mode for shared-data clusters. Valid values:
    • sync: Builds the index during data writes. Queries can use the index immediately, at the cost of higher load latency.
    • async: Builds the index in the background after the write finishes. Until the build completes, queries over the affected segments automatically fall back to brute-force search. Use lake_vector_index_build_warehouse to select the build warehouse and lake_vi_build_load_tail_delay_ms to control load-tail dispatch delay.
M
  • Default: 16
  • Required: No
  • Description: HNSW-specific parameter. The number of bi-directional connections created for every new element during graph construction. It must be an integer greater than or equal to 2. The value of M directly affects the efficiency and accuracy of graph construction and search. During graph construction, each vertex will attempt to establish connections with its nearest M vertices. If a vertex already has M connections but finds a closer vertex, the farthest connection will be deleted and a new connection will be established with the closer vertex. A vector search will start from an entry point and find the nearest neighbor along the vertices connected to it. Therefore, the larger the value of M, the larger the search scope for each vertex, the higher the search efficiency, but the higher the cost of graph construction and storage.
efconstruction
  • Default: 40
  • Required: No
  • Description: HNSW-specific parameter. The size of the candidate list containing the nearest neighbors. It must be an integer greater than or equal to 1. It is used to control the search depth during the graph construction process. Specifically, efconstruction defines the size of the search list (also known as the candidate list) for each vertex during the graph construction process. This candidate list is used to store the neighbor candidates of the current vertex, and the size of the list is efconstruction. The larger the value of efconstruction, the more candidates is considered as the neighbors of the vertex during the graph construction process, and, as a result, the better quality (such as better connectivity) of the graph, but also the higher time consumption and computation complexity of graph construction.
efsearch
  • Default: 40
  • Required: No
  • Description: HNSW-specific parameter. Parameter that controls the precision-speed tradeoff. During a hierarchical graph structure search, this parameter controls the size of the candidate list during the search. The larger the value of efsearch, the higher the accuracy, but the lower the speed. This parameter can be specified during index creation. If the ann_params in a query does not contain this parameter, the system will perform adaptive scaling based on this value. An explicit query-level value takes precedence and bypasses adaptive scaling.
quantizer
  • Default: flat for HNSW, none for IVF
  • Required: Yes for IVF, optional for HNSW
  • Description: IVF requires pq, sq4, or sq8. For example, "index_type" = "ivf", "quantizer" = "sq8" uses 8-bit scalar quantization. HNSW also accepts flat.
    • flat — no quantization (HNSW default). Equivalent to omitting this property on HNSW.
    • sq4 — 4-bit scalar quantization. Uses half as many bits per dimension as sq8.
    • sq8 — 8-bit scalar quantization. Uses one byte per dimension.
    • pq — product quantization. Requires m_pq; storage scales with m_pq * nbits_pq bits per vector.
m_pq
  • Required: Required when quantizer = pq; rejected otherwise.
  • Description: Number of product-quantization sub-quantizers for HNSW or IVF with quantizer = pq. The original vector is split into m_pq equal-length sub-vectors; therefore m_pq must divide dim. Larger m_pq raises recall at the cost of more bytes per vector. Typical values are in the range 4–32 depending on dim.
nbits_pq
  • Default: 8
  • Required: No (only allowed when quantizer = pq; rejected otherwise).
  • Description: Bits per PQ sub-quantizer. HNSW accepts 4–16. IVF supports 8.
nbits
  • Default: 8
  • Required: No
  • Description: IVFPQ-specific parameter. Number of bits used by Product Quantization (PQ). Currently, only 8 is supported.
nlist
  • Default: 16
  • Required: No
  • Description: Number of clusters, or inverted lists, for ivf and ivfpq. It must be an integer greater than or equal to 1. With IVFPQ, the dataset is divided into clusters, and the centroid of each cluster corresponds to an inverted list. A vector search will first find the cluster centroid closest to the data point, and then retrieve the nearest neibors in the corresponding inverted list. Therefore, the value of nlist will affect the accuracy and efficiency of the search. The larger the value of nlist, the finer the granularity of clustering, thus the higher the search accuracy, but also the higher the search complexity.
M_IVFPQ
  • Default: N/A
  • Required: Yes
  • Description: IVFPQ-specific parameter. Number of the subvectors the original vector will be split into. The IVFPQ index will divide a dim-dimensional vector into M_IVFPQ equal-length subvectors. Therefore, it must be a factor of the value of dim. The SQL property name is M_IVFPQ; M is a different, HNSW-only property.

Append vector index

You can also add vector indexes to an existing table using CREATE INDEX or ALTER TABLE ADD INDEX. Note For cloud-native tables in shared-data clusters, ALTER TABLE ADD INDEX statements will rewrite the existing data and build the index on it. Even with index_build_mode set to async, the system will finish the index building before the Schema Change completes. Example:

Manage vector indexes

View vector index

You can view the definition of a vector index using the SHOW CREATE TABLE statement: Example:

Drop vector index

You can drop vector indexes using DROP INDEX or ALTER TABLE DROP INDEX.

Perform ANNS with vector indexes

Requirements for vector index-based queries

To use vector index in queries, all the following requirements must be met:
  • ORDER BY requirements:
    • ORDER BY clause format: The ORDER BY clause must follow the format ORDER BY <vector_index_distance_func>(vector_column, constant_array) without including additional ORDER BY columns.
      • Function name requirements for <vector_index_distance_func>:
        • If metric_type is l2_distance, the function name must be approx_l2_distance.
        • If metric_type is cosine_similarity, the function name must be approx_cosine_similarity.
        • If metric_type is inner_product, the function name must be approx_inner_product.
      • Parameter requirements for <vector_index_distance_func>:
        • One of the column constant_array must be a constant ARRAY<FLOAT> with dimensions matching the vector index dim.
        • The other column vector_column must be the column corresponding to the vector index.
    • ORDER direction requirements:
      • If metric_type is l2_distance, the order must be ASC.
      • If metric_type is cosine_similarity, the order must be DESC.
      • If metric_type is inner_product, the order must be DESC.
    • A LIMIT N clause is required.
    • An OFFSET clause (LIMIT N OFFSET M, or LIMIT M, N) can be added for pagination. The index then returns N + M candidates from each segment so that the TopN above it can skip the first M rows. If M is greater than 0 and N + M exceeds vector_index_max_paging_depth (default 10000), the query does not use the vector index and computes exact distances instead. Because each page is a separate approximate search, a row near a page boundary may appear on two consecutive pages or on neither.
  • Predicate Requirements:
    • All predicates must be <vector_index_distance_func> expressions, combined using AND and comparison operators (> or <). The comparison operator direction must align with the ASC/DESC order. Specifically:
    • Requirement 1:
      • If metric_type is l2_distance: col_ref <= constant.
      • If metric_type is cosine_similarity: col_ref >= constant.
      • If metric_type is inner_product: col_ref >= constant. The constant can be negative.
      • Here, col_ref refers to the result of <vector_index_distance_func>(vector_column, constant_array) and can be cast to FLOAT or DOUBLE types, for example:
        • approx_l2_distance(v1, [1,2,3])
        • CAST(approx_l2_distance(v1, [1,2,3]) AS FLOAT)
        • CAST(approx_l2_distance(v1, [1,2,3]) AS DOUBLE)
    • Requirement 2:
      • The predicate must use AND, with each child predicate meeting Requirement 1.

How to write the query vector

The query vector can be written either as an array literal or as a string cast to ARRAY<FLOAT>:
Both forms produce the same vector and the same results for every case verified so far. For high-dimensional vectors the string form is cheaper for the FE to process, because an array literal is parsed and typed element by element while the string is parsed once. Prefer it for vectors with hundreds of dimensions, and use CAST(? AS ARRAY<FLOAT>) in a prepared statement. From v4.2.0 onwards the FE can do that conversion for you instead of you rewriting existing SQL. Set the session variable enable_vector_literal_auto_cast to true, and when every element of the array literal is a numeric literal the FE rewrites the literal into the string form, which removes the per-element expression building. Lexing and parsing still walk every number, so the rewritten literal does not become quite as cheap as a hand-written string. An array literal that contains anything else, such as a column reference, an expression, or NULL, keeps the per-element form. The variable defaults to false. Enable it deliberately rather than relying on an upgrade to turn it on, because the rewrite changes what gets stored and what some surfaces display, and turning it back off does not undo either:
  • A view or materialized view created while it is on stores the string form in its definition text, and an already prepared statement keeps using the rewritten form. Recreate the view or materialized view, or DEALLOCATE PREPARE and prepare the statement again, to get the per-element form back. SHOW CREATE VIEW reports the original statement text when that text is available, but paths that fall back to the stored definition, including the compatibility SHOW CREATE VIEW form for a materialized view, display the rewritten form.
  • EXPLAIN renders the Query Vector line differently, and the SQL digest becomes CAST(? AS ARRAY<FLOAT>) instead of a per-element [?, ?, ...]. After enabling it, recreate SQL digest blacklist entries and SPM baselines that target vector queries, and expect a one-time discontinuity in audit statistics aggregated by digest.
  • A -0.0 element keeps its sign in the string form, whereas the array-literal form silently turns it into 0.0. This does not change any distance result.
Independently of that variable, every element of the query vector must be a finite number within the FLOAT range in both forms. From v4.2.0 onwards an element that is NaN, infinite, or too large for FLOAT (for example 1e39) makes the query fail with Non-finite float in vector array literal instead of being silently narrowed to infinity.

Preparation

Create tables with vector indexes and insert vector data into them:
Approximate search
Approximate searches will hit the vector index and thereby accelerate the search process. The following example searches for the top 1 approximate nearest neighbor of the vector [1,1,1,1,1].
Scalar-vector joint search
You can combine scalar search with vector search.
Range search
You can perform range search on vector data. The following example pushes the score < 40 condition down to the index and filters vectors by score range.
Precise calculation
Precise calculations will ignore the vector index, and directly calculate distances between the vectors for precise results.
NOTE Different distance metric functions define ā€œsimilarityā€ differently. For l2_distance, smaller values indicate higher similarity; for cosine_similarity, larger values indicate higher similarity. Therefore, when calculating topN, the sorting (ORDER BY) direction should match the similarity direction of the metric. Use ORDER BY ASC LIMIT x for l2_distance, and ORDER BY DESC LIMIT x for cosine_similarity.
Parameter tuning is essential in vector search, as it affects both performance and accuracy. It is recommended to tune the search paramters on a small dataset and move to large datasets only when expected recall and latency are achieved. Search parameters are passed through the ann_params session variable or hints in SQL statements.
For HNSW index
Before proceeding, make sure the vector column is built with the HNSW index.
Parameter:
efsearch
  • Default: 40
  • Required: No
  • Description: Parameter that controls precision-speed tradeoff. During a hierarchical graph structure search, this parameter controls the size of the candidate list during the search. The larger the value of efsearch, the higher the accuracy, but the lower the speed.
For IVF and IVFPQ indexes
All IVF encodings use nprobe for both top-k and range searches. Only top-k searches apply max_codes. Set IVF search parameters at query time with ann_params. Only IVF-PQ uses range_search_confidence for range searches. IVF-SQ uses full-index caching. This example performs a top-k search on an IVF-PQ index.
Parameter:
nprobe
  • Default: 1
  • Required: No
  • Description: Number of inverted lists checked during the search. The larger the value of nprobe, the higher the accuracy, but the lower the speed.
max_codes
  • Default: 0
  • Required: No
  • Description: Maximum total number of encoded vectors a top-k search examines per segment across the inverted lists selected by nprobe. A tighter cap can reduce search time and recall. Set it to 0 to disable the cap. Range searches ignore max_codes and can scan every entry in the selected lists even with LIMIT 1.
range_search_confidence
  • Default: 0
  • Required: No
  • Description: Confidence of approximate range searches. Value range: [0, 1]. Setting it to 1 produces the most accurate results.

Tune candidate count and result refinement

The following session variables control the number of candidates returned by the index and whether the database recomputes their exact distances:
  • k_factor, default 1: Multiplies the requested candidate count (LIMIT, or LIMIT + OFFSET when an OFFSET clause is present) to determine the number of candidates requested from each segment. A larger value can improve recall after results from multiple segments are merged, but increases CPU, memory, and downstream work.
  • enable_vector_index_refine, default false: For IVF, legacy IVFPQ, and HNSW indexes using the sq4, sq8, or pq quantizer, recomputes exact distances from the original vectors and reranks the candidates. It has no effect on unquantized HNSW indexes (quantizer = flat).
  • pq_refine_factor, default 1: For a range search with exact-distance refinement enabled, further multiplies the candidate count after k_factor is applied.
  • vector_index_max_paging_depth, default 10000: The largest LIMIT + OFFSET that a query with an OFFSET greater than 0 can serve from the vector index. Deeper pages fall back to exact computation. Set it to 0 to route every query with an OFFSET greater than 0 to exact computation. Queries without OFFSET, or with OFFSET 0, are not affected.
For example:
Higher candidate multipliers generally improve recall at the cost of more index, I/O, and distance-computation work. Use EXPLAIN and check Refine: ON/OFF to verify whether exact-distance refinement is active.

Calculate approximate recall

You can calculate approximate recall by intersecting the topK elements from brute-force retrieval with those from approximate retrieval: Recall = TP / (TP + FN).
In the preceding example, approximate retrieval returns 8, 9, 7, and 5. However, the correct result is 8, 9, 5, 7, and 10. In this case, recall is 4/5=80%.

Check if vector indexes take effect

Execute EXPLAIN against the query statement. If OlapScanNode properties show VECTORINDEX: ON, it indicates that the vector index has been applied to approximate vector searches. Example: