Multi-Category Vector Search User Guide

Updated at:

Multi-category vector search allows each query to specify a set of categories and searches for similar vectors only in the data for those categories. For example, a product search can specify both Books and Electronics for one query and only Electronics for another, allowing searches with different scopes in a single SQL statement.

Search Semantics

Each row in the base table stores its category in a scalar column. The query input can specify a single target category in a regular scalar column or multiple target categories in an array column. For each query, the system selects up to top_k similar results from the union of the target categories.

Query category value (regular or array column)

Search scope

top_k = 10: Meaning

'Books' or array('Books')

Data in the Books category

Up to 10 results

array('Books', 'Electronics')

Data in the Books or Electronics category

Up to 10 results across both categories

array('Books', 'Electronics', 'Clothing')

The union of the three categories

Up to 10 results across all three categories

TopK is calculated per query, not separately for each category, and does not guarantee that every category appears in the results. Category conditions are applied during candidate filtering. Even a highly similar vector in the base table is not returned if its category falls outside the scope specified by the query.

Here, multi-category refers to multiple possible values of a single category field. The function accepts one pair of category columns, not multiple category fields, and does not support an array as the base table category column.

Syntax and Parameters

SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;

VECTOR_SEARCH(
  { TABLE base_table | (base_query) }, base_vector_column,
  { TABLE query_table | (query_query) }, query_vector_column,
  base_category_column, query_categories_column,
  top_k
  [, distance_type]
  [, options]
)

Compared with a call without category conditions, this call adds two positional parameters after the query vector column and before top_k: the base table category column name and the query category column name (a regular scalar column or an array column). Both parameters must be provided together as column names without single quotation marks. To use a constant or construct an array, generate it in the query-side subquery, assign it a column name, and pass that name to the function.

Parameter

Description

base_table / base_query

The data to search. It must contain the base table vector column, the base table category column, and the fields to return.

base_vector_column

The VECTOR column in the base table.

query_table / query_query

The query input. Each row contains a query vector and a category value (a scalar or an array).

query_vector_column

The VECTOR column in the query input. Its dimensions should match those of the base table vectors.

base_category_column

The single-valued category column in the base table.

query_categories_column

The T or ARRAY<T> category column in the query input. A regular column specifies one category; an array column specifies multiple possible categories.

top_k

A positive integer that specifies the maximum number of results returned per query.

distance_type

EUCLIDEAN, COSINE, or DOT_PRODUCT, without single quotation marks. Default: EUCLIDEAN.

options

An optional JSON string that specifies search options.

Category types must match exactly, as shown in the following table. The type of a regular query column or the element type of a query array column must be the same as the base table category type. No implicit conversion is performed between integer types.

Base table category type

Regular query column type

Query array column type

TINYINT

TINYINT

ARRAY<TINYINT>

SMALLINT

SMALLINT

ARRAY<SMALLINT>

INT

INT

ARRAY<INT>

BIGINT

BIGINT

ARRAY<BIGINT>

STRING

STRING

ARRAY<STRING>

For example:

  • If the base table category type is BIGINT, the query input can use a regular BIGINT column directly or construct query categories with array(cast(1001 as bigint), cast(1002 as bigint)).

  • STRING does not match BIGINT or ARRAY<BIGINT>, and INT does not match BIGINT or ARRAY<BIGINT>.

  • If the types do not match, perform an explicit CAST in the query-side subquery, assign the result a column name, and then pass that name to the function.

  • Types such as FLOAT, DOUBLE, DECIMAL, BOOLEAN, CHAR, and VARCHAR cannot be used directly as the base table category type in this function.

The results contain fields from the query input and the base table, as well as a DOUBLE value named distance. Use _query.column_name and _base.column_name to distinguish fields with the same name on the two sides. If explicit aliases are assigned to the inputs, use those aliases instead. When the query input uses a regular category column, that column retains its original scalar type in the results. SELECT * does not expose an additional internal array column used for the search. Selecting only the fields required by the business is recommended.

Quick Start: Single-Category and Multi-Category Search

Perform the following operations in the same project in this order: create tables → ingest data with distribution and sorting by category → create an index → build the index → search. Use example table names that are not already in use. Execute the data insertion statements only once; repeated execution inserts duplicate data.

Configure Settings and Create Tables

The base table and query tables in this guide are Append Delta Table 2.0 tables without primary keys. After enabling the VECTOR type, create one base table and two query tables: mc_single_category_queries_demo uses the regular category column query_category STRING, and mc_multi_category_queries_demo uses the array category column categories ARRAY<STRING>. For more information about VECTOR type configuration, see VECTOR data type.

SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;

CREATE TABLE mc_category_items_demo (
  item_id STRING,
  category STRING,
  embedding VECTOR(FLOAT, 3)
)
TBLPROPERTIES ('table.format.version'='2', 'transactional'='true');

CREATE TABLE mc_single_category_queries_demo (
  query_id STRING,
  query_category STRING,
  query_embedding VECTOR(FLOAT, 3)
)
TBLPROPERTIES ('table.format.version'='2', 'transactional'='true');

CREATE TABLE mc_multi_category_queries_demo (
  query_id STRING,
  categories ARRAY<STRING>,
  query_embedding VECTOR(FLOAT, 3)
)
TBLPROPERTIES ('table.format.version'='2', 'transactional'='true');

Distribute and Sort Data by Category During Ingestion

For better category search performance, use DISTRIBUTE BY category SORT BY category when writing to the base table. This distributes data in the same category to the same write task and sorts it by category within the task, keeping data in the same category as close together as possible. This approach is also recommended for production data ingestion. It is a performance optimization, not a prerequisite for correct category matching. The benefits depend on the data volume and category distribution. If a single category is very large, pay attention to data skew in the write tasks.

SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;

INSERT INTO mc_category_items_demo
SELECT item_id, category, embedding
FROM (
  SELECT 'B001' AS item_id, 'Books' AS category,
         vector(1.0f, 0.0f, 0.0f) AS embedding
  UNION ALL
  SELECT 'B002', 'Books', vector(0.0f, 1.0f, 0.0f)
  UNION ALL
  SELECT 'D001', 'Electronics', vector(0.8f, 0.6f, 0.0f)
  UNION ALL
  SELECT 'C001', 'Clothing', vector(1.0f, 0.0f, 0.0f)
) src
DISTRIBUTE BY category
SORT BY category;

INSERT INTO mc_single_category_queries_demo
SELECT 'S001', 'Books', vector(1.0f, 0.0f, 0.0f)
UNION ALL
SELECT 'S002', 'Electronics', vector(1.0f, 0.0f, 0.0f);

INSERT INTO mc_multi_category_queries_demo
SELECT 'Q001', array('Books', 'Electronics'), vector(1.0f, 0.0f, 0.0f)
UNION ALL
SELECT 'Q002', array('Electronics'), vector(1.0f, 0.0f, 0.0f);

In mc_single_category_queries_demo, S001 searches only Books, and S002 searches only Electronics. In mc_multi_category_queries_demo, Q001 searches both Books and Electronics, and Q002 searches only Electronics. Although the vector of C001 is identical to the query vector, its category is Clothing, so none of the queries should return it.

Create a Vector Index

Create a vector index on the embedding column in the base table. This guide uses the hgraph algorithm and the cosine distance type, so subsequent searches use COSINE.

SETPROJECT odps.schema.evolution.enable=true;
SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;

CREATE VECTOR INDEX mc_category_items_embedding_idx
ON TABLE mc_category_items_demo
FOR COLUMNS (embedding)
IDXPROPERTIES (
  'algorithm'='hgraph',
  'distance_type'='cosine'
);

CREATE VECTOR INDEX creates the index definition. The next step is still required to build the index for existing data. FOR COLUMNS specifies the vector column embedding. The category column category is specified in the VECTOR_SEARCH call and does not need to be included in the index column list here. The query tables do not require vector indexes.

Build the Index and Verify Completion

After the data is written successfully and the index definition is created, run the following command to build the index. The initial build also uses the REBUILD INDEX syntax:

SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;

ALTER TABLE mc_category_items_demo
REBUILD INDEX mc_category_items_embedding_idx;

After the SQL job that builds the index completes successfully, run the following command to check the index status:

SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;

DESC INDEX mc_category_items_embedding_idx
ON mc_category_items_demo;

-- Result:
+------------------------------------------------------------------------------------+
| Index Detail                                                                       |
+------------------------------------------------------------------------------------+
| name:                     mc_category_items_embedding_idx                          |
| id:                       c2f2cec703**********1c5f102a8f9                         |
| index_type:               VECTOR                                                   |
| index_columns:            embedding                                                |
| status:                   ACTIVE                                                   |
| coverage_percentage:      100%                                                     |
| storage_size_bytes:       6005                                                     |
| properties:               distance_type=cosine, algorithm=hgraph                   |
+------------------------------------------------------------------------------------+

For the non-partitioned table in this guide, the status should be status: ACTIVE when the build is complete and the index covers the current data. If only the definition has been created and the index has not yet been built, the status may be STALE.

After more data is written, run the preceding REBUILD INDEX command again and wait for it to complete if the index needs to cover the new data. The index definition does not need to be created again.

Search with the Index

Run queries with the index built earlier, using the same distance type as the index. The following examples omit options.

Single-Category Search: Regular Category Column

Use mc_single_category_queries_demo and pass the STRING column query_category directly, without wrapping it in an array. Each query searches only one category.

SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;

SELECT
  _query.query_id,
  _query.query_category,
  _base.item_id,
  _base.category,
  distance
FROM VECTOR_SEARCH(
  TABLE mc_category_items_demo, embedding,
  TABLE mc_single_category_queries_demo, query_embedding,
  category, query_category,
  2, COSINE
)
ORDER BY query_id, distance, item_id;

-- Results:
+----------+----------------+---------+----------+------------+
| query_id | query_category | item_id | category | distance   |
+----------+----------------+---------+----------+------------+
| S001     | Books          | B001    | Books    | 0.0        |
| S001     | Books          | B002    | Books    | 1.0        |
| S002     | Electronics    | D001    | Electronics | 0.19999998807907104 |
+----------+----------------+---------+----------+------------+

The following exact nearest-neighbor reference results are calculated from the example data to illustrate the category scope and distances. Index searches use an approximate nearest-neighbor algorithm, so the actual recall may differ, and floating-point distances may have slight errors.

query_id

query_category

item_id

category

distance (approx.)

S001

Books

B001

Books

0.0

S001

Books

B002

Books

1.0

S002

Electronics

D001

Electronics

0.2

In the reference results, S001 returns B001 and B002 from the Books category, and S002 returns D001 from the Electronics category. top_k is calculated independently for each query, and the returned query_category column remains of type STRING.

Multi-Category Search: Array Category Column

Use mc_multi_category_queries_demo and pass the ARRAY<STRING> column categories. Each query searches the union of the categories specified in the array and returns at most top_k results across all those categories.

SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;

SELECT
  _query.query_id,
  _base.item_id,
  _base.category,
  distance
FROM VECTOR_SEARCH(
  TABLE mc_category_items_demo, embedding,
  TABLE mc_multi_category_queries_demo, query_embedding,
  category, categories,
  2, COSINE
)
ORDER BY query_id, distance, item_id;

-- Results:
+----------+---------+----------+------------+
| query_id | item_id | category | distance   |
+----------+---------+----------+------------+
| Q001     | B001    | Books    | 0.0        |
| Q001     | D001    | Electronics | 0.19999998807907104 |
| Q002     | D001    | Electronics | 0.19999998807907104 |
+----------+---------+----------+------------+

The following exact nearest-neighbor reference results are calculated from the example data to illustrate the category scope and distances. Index searches use an approximate nearest-neighbor algorithm, so the actual recall may differ, and floating-point distances may have slight errors.

query_id

item_id

category

distance (approx.)

Q001

B001

Books

0.0

Q001

D001

Electronics

0.2

Q002

D001

Electronics

0.2

In the reference results, Q001 returns a total of 2 results from all candidates in Books and Electronics. Q002 has only 1 eligible item, so it returns 1 result. A smaller distance indicates greater similarity. Use an explicit ORDER BY when displaying results. The selection order of candidates with equal distances at the TopK boundary should not be treated as a business guarantee.

Other Common Uses

All the following examples reuse the base table populated and indexed in Section 3.

Run a Single Query Without Creating a Query Table

Generate both the query vector and the category array in a subquery, reusing the preceding base table:

SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;

SELECT _base.item_id, _base.category, distance
FROM VECTOR_SEARCH(
  TABLE mc_category_items_demo, embedding,
  (
    SELECT
      array('Books', 'Electronics') AS categories,
      vector(1.0f, 0.0f, 0.0f) AS query_embedding
  ), query_embedding,
  category, categories,
  2, COSINE
)
ORDER BY distance, item_id;

-- Results:
+---------+----------+------------+
| item_id | category | distance   |
+---------+----------+------------+
| B001    | Books    | 0.0        |
| D001    | Electronics | 0.19999998807907104 |
+---------+----------+------------+

To search only one category, replace array('Books', 'Electronics') AS categories with 'Books' AS categories. It has the same category filtering semantics as array('Books') AS categories. The parameter must still be the column name categories, not a string literal.

Use a Regular Category Column

A query table with an existing regular category column can be used directly for searches as described in Section 3.5.1, without manually wrapping the column in an array. 'Books,Electronics' in a regular column is a single category value and is not split at the comma. To search two categories at the same time, use an array column, as described in Section 3.5.2.

Add Base Table Filters

Filter candidate data in a base table subquery, then apply the category condition (a regular or array column) for each query. The following example excludes item B002:

SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;

SELECT _query.query_id, _base.item_id, _base.category, distance
FROM VECTOR_SEARCH(
  (
    SELECT item_id, category, embedding
    FROM mc_category_items_demo
    WHERE item_id <> 'B002'
  ), embedding,
  TABLE mc_multi_category_queries_demo, query_embedding,
  category, categories,
  2, COSINE
)
ORDER BY query_id, distance, item_id;

-- Results:
+----------+---------+----------+------------+
| query_id | item_id | category | distance   |
+----------+---------+----------+------------+
| Q001     | B001    | Books    | 0.0        |
| Q001     | D001    | Electronics | 0.19999998807907104 |
| Q002     | D001    | Electronics | 0.19999998807907104 |
+----------+---------+----------+------------+

The subquery output must retain the vector column and category column passed as parameters. Base table subqueries support simple selections, filters, and aliases, but not complex input plans such as JOINs, aggregations, or UNIONs. Time Travel is also not supported.

If the category is also a partition column in the base table, that partition column can be used as base_category_column. If the partition scope is known, also retain the partition conditions in the base table subquery. The query category column (regular or array) specifies the matching scope for each query and does not imply that static partition pruning has already occurred.

Search Without Category Restrictions

To search all categories, use the original call without the two category parameters:

SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;

SELECT _query.query_id, _base.item_id, distance
FROM VECTOR_SEARCH(
  TABLE mc_category_items_demo, embedding,
  TABLE mc_multi_category_queries_demo, query_embedding,
  2, COSINE
)
ORDER BY query_id, distance, item_id;

-- Results:
+----------+---------+------------+
| query_id | item_id | distance   |
+----------+---------+------------+
| Q001     | B001    | 0.0        |
| Q001     | C001    | 0.0        |
| Q002     | B001    | 0.0        |
| Q002     | C001    | 0.0        |
+----------+---------+------------+