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. Usehnsw 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.
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_vectoron columnvectorin tablehnsw. -
The following example creates an IVF-PQ index with the recommended syntax. To use the equivalent legacy definition, change
index_typetoivfpq, removequantizer, and renamem_pqtom_ivfpqandnbits_pqtonbits. 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
asyncbuild mode.You can view the asynchronous build progress by queryinginformation_schema.partitions_meta.- When
MIN_VI_BUILT_VERSIONequalsVISIBLE_VERSION, it indicates that the indexes of all tablets within the partition have reached the visible versions. - When
MIN_VI_BUILT_VERSIONis less thanVISIBLE_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_VERSIONis less thanMAX_VI_BUILT_VERSION, it indicates that different tablets vary in index building progress.
- When
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, andivf. Forivf, explicitly setquantizertopq,sq4, orsq8.
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. Useinner_productfor exact evaluation andapprox_inner_productfor vector-index top-k or range queries.
is_vector_normed
- Default: false
- Required: No
- Description: Whether the vectors are normalized. Valid values are
trueandfalse. It takes effect only whenmetric_typeiscosine_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 is1, 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 legacyivfpq) at leastmax(nlist, 256), and for HNSW-PQ at least2^nbits_pq. When omitted, the BE uses its configured threshold and enforces the training minimum for bothivfandivfpq.
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. Uselake_vector_index_build_warehouseto select the build warehouse andlake_vi_build_load_tail_delay_msto 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 ofMdirectly affects the efficiency and accuracy of graph construction and search. During graph construction, each vertex will attempt to establish connections with its nearestMvertices. If a vertex already hasMconnections 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 ofM, 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,efconstructiondefines 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 isefconstruction. The larger the value ofefconstruction, 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 theann_paramsin 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:
flatfor HNSW, none for IVF - Required: Yes for IVF, optional for HNSW
- Description: IVF requires
pq,sq4, orsq8. For example,"index_type" = "ivf", "quantizer" = "sq8"uses 8-bit scalar quantization. HNSW also acceptsflat.flatā no quantization (HNSW default). Equivalent to omitting this property on HNSW.sq4ā 4-bit scalar quantization. Uses half as many bits per dimension assq8.sq8ā 8-bit scalar quantization. Uses one byte per dimension.pqā product quantization. Requiresm_pq; storage scales withm_pq * nbits_pqbits 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 intom_pqequal-length sub-vectors; thereforem_pqmust dividedim. Largerm_pqraises recall at the cost of more bytes per vector. Typical values are in the range 4ā32 depending ondim.
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
8is supported.
nlist
- Default: 16
- Required: No
- Description: Number of clusters, or inverted lists, for
ivfandivfpq. It must be an integer greater than or equal to1. 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 ofnlistwill affect the accuracy and efficiency of the search. The larger the value ofnlist, 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 intoM_IVFPQequal-length subvectors. Therefore, it must be a factor of the value ofdim. The SQL property name isM_IVFPQ;Mis 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 withindex_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
- ORDER BY requirements:
- ORDER BY clause format: The
ORDER BYclause must follow the formatORDER 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_typeisl2_distance, the function name must beapprox_l2_distance. - If
metric_typeiscosine_similarity, the function name must beapprox_cosine_similarity. - If
metric_typeisinner_product, the function name must beapprox_inner_product.
- If
- Parameter requirements for
<vector_index_distance_func>:- One of the column
constant_arraymust be a constantARRAY<FLOAT>with dimensions matching the vector indexdim. - The other column
vector_columnmust be the column corresponding to the vector index.
- One of the column
- Function name requirements for
- ORDER direction requirements:
- If
metric_typeisl2_distance, the order must beASC. - If
metric_typeiscosine_similarity, the order must beDESC. - If
metric_typeisinner_product, the order must beDESC.
- If
- A
LIMIT Nclause is required. - An
OFFSETclause (LIMIT N OFFSET M, orLIMIT M, N) can be added for pagination. The index then returnsN + Mcandidates from each segment so that the TopN above it can skip the firstMrows. IfMis greater than0andN + Mexceedsvector_index_max_paging_depth(default10000), 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.
- ORDER BY clause format: The
- Predicate Requirements:
- All predicates must be
<vector_index_distance_func>expressions, combined usingANDand comparison operators (>or<). The comparison operator direction must align with theASC/DESCorder. Specifically: - Requirement 1:
- If
metric_typeisl2_distance:col_ref <= constant. - If
metric_typeiscosine_similarity:col_ref >= constant. - If
metric_typeisinner_product:col_ref >= constant. The constant can be negative. - Here,
col_refrefers to the result of<vector_index_distance_func>(vector_column, constant_array)and can be cast toFLOATorDOUBLEtypes, 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)
- If
- Requirement 2:
- The predicate must use
AND, with each child predicate meeting Requirement 1.
- The predicate must use
- All predicates must be
How to write the query vector
The query vector can be written either as an array literal or as a string cast toARRAY<FLOAT>:
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 PREPAREand prepare the statement again, to get the per-element form back.SHOW CREATE VIEWreports the original statement text when that text is available, but paths that fall back to the stored definition, including the compatibilitySHOW CREATE VIEWform for a materialized view, display the rewritten form. EXPLAINrenders theQuery Vectorline differently, and the SQL digest becomesCAST(? 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.0element keeps its sign in the string form, whereas the array-literal form silently turns it into0.0. This does not change any distance result.
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:Perform vector search
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 thescore < 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. Forl2_distance, smaller values indicate higher similarity; forcosine_similarity, larger values indicate higher similarity. Therefore, when calculatingtopN, the sorting (ORDER BY) direction should match the similarity direction of the metric. UseORDER BY ASC LIMIT xforl2_distance, andORDER BY DESC LIMIT xforcosine_similarity.
Fine tune index parameters for search
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 theann_params session variable or hints in SQL statements.
For HNSW index
Before proceeding, make sure the vector column is built with the HNSW index.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 usenprobe 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.
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 to0to disable the cap. Range searches ignoremax_codesand can scan every entry in the selected lists even withLIMIT 1.
range_search_confidence
- Default: 0
- Required: No
- Description: Confidence of approximate range searches. Value range: [0, 1]. Setting it to
1produces 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, default1: Multiplies the requested candidate count (LIMIT, orLIMIT + OFFSETwhen anOFFSETclause 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, defaultfalse: For IVF, legacy IVFPQ, and HNSW indexes using thesq4,sq8, orpqquantizer, recomputes exact distances from the original vectors and reranks the candidates. It has no effect on unquantized HNSW indexes (quantizer = flat).pq_refine_factor, default1: For a range search with exact-distance refinement enabled, further multiplies the candidate count afterk_factoris applied.vector_index_max_paging_depth, default10000: The largestLIMIT + OFFSETthat a query with anOFFSETgreater than0can serve from the vector index. Deeper pages fall back to exact computation. Set it to0to route every query with anOFFSETgreater than0to exact computation. Queries withoutOFFSET, or withOFFSET 0, are not affected.
EXPLAIN and check Refine: ON/OFF to verify whether exact-distance refinement is active.
Calculate approximate recall
You can calculate approximate recall by intersecting thetopK elements from brute-force retrieval with those from approximate retrieval: Recall = TP / (TP + FN).
Check if vector indexes take effect
Execute EXPLAIN against the query statement. IfOlapScanNode properties show VECTORINDEX: ON, it indicates that the vector index has been applied to approximate vector searches.
Example: