Implement text vector retrieval in MaxCompute
This tutorial is for users new to text vector retrieval in MaxCompute. It uses 60 Chinese text samples to demonstrate how to generate vectors with the text-embedding-v4 model, create and rebuild a vector index, and perform semantic search with scalar filtering using natural language queries.
Overview
Convert text into 256-dimensional vectors using
AI_EMBEDDING.Create an append-only Delta Table 2.0 to store vector data.
Create, rebuild, and inspect an HGraph vector index.
Perform batch semantic search using
VECTOR_SEARCH.Use a scalar condition to narrow down the candidate set before vector retrieval.
Before you begin
Complete the following prerequisites:
Prerequisite | Requirement |
Alibaba Cloud account and project | You have an active MaxCompute project. |
Region | The region where your project is located must support the MaxCompute model inference service and the |
Model inference service | The MaxCompute model inference service is activated in the target region. Currently, this service is available only in the following regions. Region and model availability is subject to change. For the latest information, see the Purchase and use the MaxCompute model inference service documentation.
|
Permissions | The current account has permissions to create tables, write data, call models, and manage vector indexes. |
Execution environment |
|
This tutorial consistently uses the text-embedding-v4 model, DEFAULT_VERSION, 256-dimensional vectors, and cosine distance. The corpus vectors, query vectors, and the index distance type must be consistent.
Model inference fees: Calling the text-embedding-v4 model incurs model inference fees (token fees). Executing SQL statements and rebuilding the index also consume computing resources. Monitor your usage and billing.
Use case
This tutorial constructs a lifestyle content library containing 60 records:
Category | Count | Content examples |
Travel | 10 | City weekend getaways, family nature experiences, cultural routes |
Digital | 10 | Laptop battery life, Wi-Fi, phone storage, and headphone usage |
Home | 10 | Organization, cleaning, lighting, and small space layouts |
Pets | 10 | New cat ownership, dog walking, hydration, and daily care |
Sports | 10 | Running, cycling, swimming, and home workouts |
Food | 10 | Breakfast, light meals, coffee, and home cooking |
Each record includes a unique ID, title, content, and category. The content is used to generate vectors, while the title and category are used to display and verify the search results.
The tutorial uses three search queries:
Query ID | Query text |
Q001 | I want to find a place in Hangzhou for a weekend trip with my child that is close to nature but not too tiring. |
Q002 | I'm setting up a long-term home office. How can I make my workspace clean and comfortable while ensuring a stable internet connection for online meetings? |
Q003 | I just brought a kitten home. What supplies do I need to buy first? |
Step 1: Configure the SQL environment
Log in to the MaxCompute console and select a region in the upper-left corner.
In the left-side navigation pane, choose .
On the SQL query page, run the following configuration commands:
SET odps.sql.type.system.odps2=true; SET odps.sql.type.vector.enable=true; SELECT 1;The
odps2setting and the Vector type switch are required to use the MaxCompute vector data type. The subsequent SQL code blocks in this topic retain the required session configurations and can be copied and run individually.If you are using DataWorks, create an ODPS SQL node in the target workspace and select the same MaxCompute project.
Step 2: Create and vectorize the text corpus
Create the text vector table
VECTOR_SEARCH requires the input table to be a Delta Table. This topic uses a primary key-free Append Delta Table, and enables Delta Table 2.0 by using table.format.version=2:
SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;
CREATE TABLE IF NOT EXISTS text_search_corpus (
doc_id STRING,
title STRING,
content STRING,
category STRING,
text_embedding VECTOR(FLOAT, 256),
embedding_model STRING,
model_version STRING
)
TBLPROPERTIES ("table.format.version"="2");
Insert sample data and generate vectors
The following SQL statement uses VALUES to construct 60 records and calls AI_EMBEDDING to process all the text during the write operation:
SET odps.namespace.schema=true;
SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;
SET odps.sql.ai.embedding.dimension=256;
INSERT OVERWRITE TABLE text_search_corpus
SELECT
doc_id,
title,
content,
category,
AI_EMBEDDING(
bigdata_public_modelset.default.`text-embedding-v4`,
DEFAULT_VERSION,
content
) AS text_embedding,
'text-embedding-v4' AS embedding_model,
'DEFAULT_VERSION' AS model_version
FROM (
VALUES
('T001', 'Family Birdwatching at Xixi Wetland', 'Xixi Wetland features a dense water network and gentle paths, making it ideal for parents and children to observe waterfowl and wetland plants in spring and autumn. The main route can be completed in half a day.', 'Travel'),
('T002', 'Morning Walk Route at West Lake', 'Walk from the Broken Bridge along Beishan Street to the Quyuan Garden. There are fewer tourists in the morning, and the path is flat, perfect for those who want a relaxing view of the lake.', 'Travel'),
('T003', 'Night Tour on the Grand Canal', 'Take an evening boat tour on the canal from Wulinmen Pier to see bridges, historic districts, and lights on both banks. It is a good final activity for a city trip.', 'Travel'),
('T004', 'One-Day Visit to Liangzhu Culture Site', 'Visit the Liangzhu Museum in the morning to learn about the civilization, then head to the archaeological park in the afternoon. It is recommended to book in advance and bring sun protection.', 'Travel'),
('T005', 'Beginner Hike in Moganshan', 'Choose a short route that connects bamboo forests and villages with minimal elevation gain. Regular athletic shoes are sufficient, suitable for first-time hikers.', 'Travel'),
('T006', 'Lakeside Cycling at Qiandao Lake', 'The greenway along the lake offers open views. You can choose a 20- to 40-kilometer route based on your fitness level, with several rest stops and viewing platforms along the way.', 'Travel'),
('T007', 'Stroll Through Old Shanghai Architecture', 'Start from Wukang Road and walk through Hunan Road and Fuxing West Road to see residential buildings from different eras. There are also many cafes for a break.', 'Travel'),
('T008', 'Off-Peak Tour of Suzhou Gardens', 'Visit popular gardens right after they open, then walk to smaller, nearby gardens to reduce queuing and experience different spatial scales.', 'Travel'),
('T009', 'Weekend Plan by the Sea in Ningbo', 'Visit the fishing port and coastal walkway on the first day, and arrange a visit to the seafood market and an ancient village on the second. The pace is relaxed, suitable for a two-day trip.', 'Travel'),
('T010', 'Nanjing Museum Route', 'Plan to visit the Nanjing Museum, the city wall ruins, and historic districts in one day. Public transport is convenient, and most of the itinerary can be completed even on a rainy day.', 'Travel'),
('D011', 'Extend Laptop Battery Life', 'When working remotely, lower the screen brightness, turn off unused Bluetooth and background sync programs, and enable the system''s power-saving mode to reduce battery consumption.', 'Digital'),
('D012', 'Improve Home Wi-Fi Network', 'Place the router in a central location and avoid blocking it with metal cabinets. For large homes, add mesh network nodes to reduce signal drop-off in distant rooms.', 'Digital'),
('D013', 'Free Up Phone Storage Space', 'First, check for large files like videos, chat attachments, and duplicate photos. Then, uninstall unused apps and back up important files to the cloud or a computer.', 'Digital'),
('D014', 'Fix Bluetooth Headphone Connection Issues', 'If the headphones won''t pair, delete the old pairing record, restart both your phone and the headphones, and ensure the headphones are in discovery mode.', 'Digital'),
('D015', 'Securely Back Up Phone Photos', 'Even with automatic backup enabled, check the sync status regularly. Store important photos on a computer or another storage device to avoid having only a single copy.', 'Digital'),
('D016', 'More Comfortable Screen Time', 'Adjust the monitor brightness based on ambient light, slightly increase the text size, and position the top of the screen near eye level. Look into the distance periodically.', 'Digital'),
('D017', 'Router Placement Principles', 'Do not place the router on the floor, in a corner, or next to large appliances. Keep the surrounding area open and minimize the number of load-bearing walls between the router and your devices.', 'Digital'),
('D018', 'Phone Overheating During Fast Charging', 'Running demanding games while charging increases heat. It is best to stop high-load applications, use a compatible charger, and keep the device well-ventilated.', 'Digital'),
('D019', 'Daily Cleaning of Mechanical Keyboards', 'After disconnecting the power, use an air blower to clean between the keycaps, then wipe the surface with a slightly damp soft cloth. Avoid letting liquid get into the switches and circuit board.', 'Digital'),
('D020', 'Reduce Background Noise in Video Conferences', 'Use a headset with a microphone, turn off continuous noise sources in the room, and enable echo cancellation and noise reduction in your conferencing software.', 'Digital'),
('H021', 'Small Entryway Organization', 'Use wall hooks, a narrow shoe cabinet, and tiered trays to store coats, shoes, and keys, keeping frequently used items in a fixed place.', 'Home'),
('H022', 'Quickly Clean Kitchen Grease', 'Wipe the stove while it is still warm after cooking. For stubborn grease, apply a mild cleaner and let it sit before wiping with a soft cloth.', 'Home'),
('H023', 'Layered Bedroom Lighting Design', 'In addition to the main light, add a low-brightness reading lamp by the bed and use warm, indirect light to meet different needs like reading, nighttime use, and relaxation.', 'Home'),
('H024', 'Prevent Mold in a Humid Bathroom', 'After showering, turn on the exhaust fan and wipe down wet walls. Regularly clean tile grout to prevent mold caused by long-term moisture.', 'Home'),
('H025', 'Organize Desk Cables', 'Mount a power strip under the desk, use cable clips to separate power and data cords, and leave some slack for frequently unplugged cables.', 'Home'),
('H026', 'Functional Zones in a Small Apartment', 'Use rugs, low cabinets, and lighting to divide work and rest areas. Avoid heavy partitions to maintain open sightlines and good flow.', 'Home'),
('H027', 'Daily Mattress Maintenance', 'Change sheets regularly and use a vacuum cleaner on the surface. Rotate the mattress according to the product instructions and keep the bedroom ventilated and dry.', 'Home'),
('H028', 'Organize Your Refrigerator', 'Store ready-to-eat foods and raw items on separate shelves. Use clear containers to label opening dates and place items with nearing expiration dates in plain sight.', 'Home'),
('H029', 'Hardy Plants for the Balcony', 'For sunny balconies, choose rosemary and mint. For low-light areas, consider pothos. Check soil moisture before watering.', 'Home'),
('H030', 'Organize Seasonal Clothing', 'Wash and completely dry clothes before storing them. Sort them by family member and frequency of use, and add moisture-proofing measures in humid spaces.', 'Home'),
('P031', 'New Kitten Supply Checklist', 'Before bringing a kitten home, prepare a litter box, litter, food and water bowls, age-appropriate food, a scratching post, and a safe hiding spot. Let it acclimate quietly at first.', 'Pets'),
('P032', 'Encourage Your Cat to Drink More Water', 'Place water bowls away from food and the litter box, set up multiple water stations, and change the water daily. Some cats prefer running water.', 'Pets'),
('P033', 'Establish a Stable Dog-Walking Routine', 'Try to go out at the same time each day, adjust the duration based on the dog''s age and energy, and allow time for sniffing and exploring, not just a quick walk.', 'Pets'),
('P034', 'Transitioning Your Pet to a New Food', 'Gradually mix the new food with the old over several days while monitoring appetite and digestion. A sudden switch can cause an upset stomach.', 'Pets'),
('P035', 'Reduce Furniture Scratching', 'Place sturdy scratching posts where your cat often stays and scratches. Use toys and rewards to encourage use, rather than just scolding.', 'Pets'),
('P036', 'Daily Pet Oral Care', 'Start by briefly touching the teeth and gums, then gradually introduce a pet-specific toothbrush and toothpaste. Regularly check for bad breath and tartar.', 'Pets'),
('P037', 'Help Your Pet Get Used to a Carrier', 'Keep the carrier at home with the door open. Place a familiar blanket and treats inside to help your pet see it as a safe space.', 'Pets'),
('P038', 'Reduce Pet Hair at Home', 'Regularly brush your pet to collect loose fur before it sheds. Use a vacuum and lint roller on fabric surfaces, and clean AC and air purifier filters.', 'Pets'),
('P039', 'Adjusting Life for a Senior Dog', 'Provide non-slip mats and an easily accessible resting area. Shorten the duration of each exercise session but maintain a regular routine. Monitor weight, appetite, and mobility.', 'Pets'),
('P040', 'Summer Pet Heat Protection', 'Avoid going out during the hottest part of the day, ensure clean drinking water is always available, and never leave a pet alone in a closed vehicle or in direct sun.', 'Pets'),
('S041', 'Start Running from Scratch', 'Begin with a mix of fast walking and slow jogging two to three times a week. Gradually increase the continuous running time instead of aiming for speed at the start.', 'Sports'),
('S042', 'Dynamic Warm-up Before Exercise', 'Gradually increase your heart rate with leg swings, lunges, and shoulder circles to prepare your joints for activity. Avoid starting directly with high-intensity movements.', 'Sports'),
('S043', 'Urban Cycling Safety Prep', 'Check your tires and brakes before you ride, wear a helmet correctly, use front and rear lights at night, and try to use bike lanes or low-traffic routes.', 'Sports'),
('S044', 'Learning to Breathe While Swimming', 'Practice slowly exhaling underwater and turning your head to the side to inhale in shallow water. Then, coordinate it with kicking and arm strokes to reduce tension from holding your breath.', 'Sports'),
('S045', 'Home Strength Training Plan', 'Squats, push-ups, and glute bridges can cover major muscle groups. Train two to three times a week, increasing reps or resistance once your form is stable.', 'Sports'),
('S046', 'Cool-Down Principles After Exercise', 'After finishing, gradually lower your heart rate with low-intensity activity, followed by gentle stretching. You should not seek sharp pain through intense pressure.', 'Sports'),
('S047', 'Short Hike Gear Checklist', 'Pack well-fitting shoes, sun protection, water, a few energy snacks, and light rain gear. Download the route or an offline map in advance.', 'Sports'),
('S048', 'Office Stretches for Neck and Shoulders', 'Get up and move periodically. Relieve prolonged static posture with shoulder blade squeezes, gentle neck rotations, and thoracic extensions.', 'Sports'),
('S049', 'Jump Rope Training for Beginners', 'Start by mastering low-height double-foot jumps with a steady rhythm. Choose a cushioned surface and practice in short, repeated sets, gradually increasing the total time.', 'Sports'),
('S050', 'Recovery After High-Intensity Training', 'Replenish fluids and eat a normal meal after training. Ensure you get enough sleep and schedule a low-intensity activity the next day. If pain persists, stop increasing the intensity.', 'Sports'),
('F051', 'Ten-Minute Balanced Breakfast', 'Combine whole-wheat bread, eggs, unsweetened yogurt, and fruit. Prepare some ingredients in advance to ensure a good mix of protein and carbs even when time is tight.', 'Food'),
('F052', 'Quick Weeknight Dinner Prep', 'Wash and portion vegetables and meat over the weekend. Use one-pot or quick stir-fry methods on weekdays to reduce time spent on last-minute menu decisions and prep.', 'Food'),
('F053', 'Home Cold Brew Coffee', 'Mix medium-ground coffee powder with cold water and steep in the refrigerator, then filter. Adjust the coffee-to-water ratio to change the strength and taste.', 'Food'),
('F054', 'Make Vegetables More Flavorful', 'Choose stir-frying, roasting, or blanching based on the vegetable''s water content. Add nuts, herbs, and a light dressing to create different layers of flavor.', 'Food'),
('F055', 'Ideas for Work Lunches', 'Prepare the main course, protein, and two vegetables separately, then combine. Let them cool completely before packing, and choose refrigeration or freezing based on storage time.', 'Food'),
('F056', 'Air Fryer Tips', 'Do not overcrowd the basket. Flip the food halfway through for even cooking. For foods with low oil content, lightly brush the surface with oil to improve texture.', 'Food'),
('F057', 'Gradually Increase Whole Grains', 'Start by replacing a portion of refined grains with brown rice, oats, or other whole grains. Adjust the ratio gradually to make the transition in taste and digestion easier.', 'Food'),
('F058', 'Reduce Sugary Drink Intake', 'Start by cutting down on frequency. Replace them with unsweetened tea, sparkling water, or water with fruit slices. Avoid stocking up on sweet drinks at home.', 'Food'),
('F059', 'Manage Frozen Ingredients', 'Portion items into single-use amounts and label with the name and date. Place new items at the back and use older stock first.', 'Food'),
('F060', 'Basic Kitchen Knife Skills', 'Keep the cutting board stable. Curl your fingers and let the knife blade glide along your knuckles. Clean and dry the knife immediately after use.', 'Food')
) sample_data(doc_id, title, content, category)
WHERE content IS NOT NULL
AND TRIM(content) <> '';
Run the following SQL statement to verify that the data and vectors are complete:
SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;
SELECT
COUNT(*) AS total_count,
COUNT(DISTINCT doc_id) AS unique_doc_count,
SUM(CASE WHEN text_embedding IS NOT NULL THEN 1 ELSE 0 END) AS embedding_count
FROM text_search_corpus;
-- Expected result:
+-------------+------------------+-----------------+
| total_count | unique_doc_count | embedding_count |
+-------------+------------------+-----------------+
| 60 | 60 | 60 |
+-------------+------------------+-----------------+If embedding_count is less than 60, stop the subsequent steps and check the model inference service, region, permissions, and input text. The AI_EMBEDDING function returns NULL for NULL or an empty string.
Step 3: Create and rebuild the vector index
A vector index can currently be created only on a Delta Table. Create an HGraph index for the text_embedding column:
-- Before creating a VECTOR INDEX, run the following command to enable Schema Evolution.
SETPROJECT odps.schema.evolution.enable=true;
SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;
CREATE VECTOR INDEX idx_text_search_corpus_embedding
ON text_search_corpus (text_embedding)
IDXPROPERTIES (
'algorithm' = 'hgraph',
'distance_type' = 'cosine',
'build_params' = '{"max_degree": 16, "ef_construction": 128}'
);
CREATE VECTOR INDEX is used to define an index. Refer to the index parameter configuration guide first to achieve optimal resource usage and recall. Because the sample data has already been written to the table, perform a full rebuild:
SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;
ALTER TABLE text_search_corpus
REBUILD INDEX idx_text_search_corpus_embedding;After the rebuild is complete, check the index information:
SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;
DESC INDEX idx_text_search_corpus_embedding
ON text_search_corpus;
-- Expected result:
+------------------------------------------------------------------------------------+
| Index Detail |
+------------------------------------------------------------------------------------+
| name: idx_text_search_corpus_embedding |
| id: e9e97a6****************e8e8bbbdc |
| index_type: VECTOR |
| index_columns: text_embedding |
| status: ACTIVE |
| coverage_percentage: 100% |
| storage_size_bytes: 63353 |
| properties: build_params={"max_degree": 16, "ef_construction": 128}, distance_type=cosine, algorithm=hgraph |
+------------------------------------------------------------------------------------+Expected results:
statusisACTIVE.coverage_percentageis100%.propertiescontainsalgorithm=hgraphanddistance_type=cosine.
The index algorithm specified for VECTOR INDEX is hgraph. max_degree controls the maximum number of connections for a node, and ef_construction controls the size of the candidate list during the build phase. If your target environment lists other algorithms, refer to the documentation for that specific version. Rebuilding an index consumes computing resources. The amount of data used in this tutorial is intended only to verify the procedure and is not suitable for evaluating index performance.
Step 4: Create search queries and generate vectors
Create a query table and generate three query vectors. The queries and the text corpus must use the same model, version, and vector dimension:
SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;
CREATE TABLE IF NOT EXISTS text_search_query (
query_id STRING,
query_text STRING,
query_embedding VECTOR(FLOAT, 256),
embedding_model STRING,
model_version STRING
)
TBLPROPERTIES ("table.format.version"="2");SET odps.namespace.schema=true;
SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;
SET odps.sql.ai.embedding.dimension=256;
INSERT OVERWRITE TABLE text_search_query
SELECT
query_id,
query_text,
AI_EMBEDDING(
bigdata_public_modelset.default.`text-embedding-v4`,
DEFAULT_VERSION,
query_text
) AS query_embedding,
'text-embedding-v4' AS embedding_model,
'DEFAULT_VERSION' AS model_version
FROM (
VALUES
('Q001', 'I want to find a place in Hangzhou for a weekend trip with my child that is close to nature but not too tiring.'),
('Q002', 'I''m setting up a long-term home office. How can I make my workspace clean and comfortable while ensuring a stable internet connection for online meetings?'),
('Q003', 'I just brought a kitten home. What supplies do I need to buy first?')
) query_data(query_id, query_text);
Before running the search, check the query vectors:
SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;
SELECT
query_id,
query_text,
CASE
WHEN query_embedding IS NOT NULL THEN 'READY'
ELSE 'FAILED'
END AS embedding_status
FROM text_search_query
ORDER BY query_id;
-- Expected result:
+----------+--------------------------------------------------------------------------------------------------------------------+------------------+
| query_id | query_text | embedding_status |
+----------+--------------------------------------------------------------------------------------------------------------------+------------------+
| Q001 | I want to find a place in Hangzhou for a weekend trip with my child that is close to nature but not too tiring. | READY |
| Q002 | I'm setting up a long-term home office. How can I make my workspace clean and comfortable while ensuring a stable... | READY |
| Q003 | I just brought a kitten home. What supplies do I need to buy first? | READY |
+----------+--------------------------------------------------------------------------------------------------------------------+------------------+Expected result: The embedding_status for all three records is READY. If any record shows FAILED, check if the query text is empty and confirm that the model, version, and vector dimension match those of the text corpus.
Step 5: Perform semantic search
Execute the following SQL to return the top 3 results for each query. The example explicitly specifies the base and query aliases for the two inputs of VECTOR_SEARCH and uses these aliases to qualify the vector column and the returned fields.
baseandqueryare the input aliases explicitly specified in this example. When two inputs contain columns with the same name, usebase.<column>andquery.<column>to specify the source of the column. If you omit the aliases, the default alias for the first input is_base, and the default alias for the second input is_query.Cosineis an enum value for the distance type and must not be enclosed in quotation marks. SpecifyCosine, not'Cosine'.
SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;
SELECT
query_id,
query_text,
doc_id,
title,
category,
content,
distance,
ROW_NUMBER() OVER (
PARTITION BY query_id
ORDER BY distance ASC
) AS rank_no
FROM (
SELECT
query.query_id AS query_id,
query.query_text AS query_text,
base.doc_id AS doc_id,
base.title AS title,
base.category AS category,
base.content AS content,
distance
FROM VECTOR_SEARCH(
(
SELECT
doc_id,
title,
category,
content,
text_embedding
FROM text_search_corpus
WHERE text_embedding IS NOT NULL
) base,
text_embedding,
(
SELECT
query_id,
query_text,
query_embedding
FROM text_search_query
WHERE query_embedding IS NOT NULL
) query,
query_embedding,
3,
Cosine
)
) search_result
ORDER BY query_id, rank_no;
-- Expected result:
+----------+-------------------------------------------------------------------------------------------------------------+--------+------------------------------------------+----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+------------+
| query_id | query_text | doc_id | title | category | content | distance | rank_no |
+----------+-------------------------------------------------------------------------------------------------------------+--------+------------------------------------------+----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+------------+
| Q001 | I want to find a place in Hangzhou for a weekend trip with my child that is close to nature but not too tiring. | T001 | Family Birdwatching at Xixi Wetland | Travel | Xixi Wetland features a dense water network and gentle paths, making it ideal for parents and children to observe waterfowl and wetland plants in spring and autumn. The main route... | 0.25343477725982666 | 1 |
| Q001 | I want to find a place in Hangzhou for a weekend trip with my child that is close to nature but not too tiring. | T004 | One-Day Visit to Liangzhu Culture Site | Travel | Visit the Liangzhu Museum in the morning to learn about the civilization, then head to the archaeological park in the afternoon. It is recommended to book in advance and bring sun protection. | 0.39122873544692993 | 2 |
| Q001 | I want to find a place in Hangzhou for a weekend trip with my child that is close to nature but not too tiring. | T002 | Morning Walk Route at West Lake | Travel | Walk from the Broken Bridge along Beishan Street to the Quyuan Garden. There are fewer tourists in the morning, and the path is flat, perfect for those who want a relaxing view of the lake. | 0.4272348880767822 | 3 |
| Q002 | I'm setting up a long-term home office. How can I make my workspace clean and comfortable...? | H026 | Functional Zones in a Small Apartment | Home | Use rugs, low cabinets, and lighting to divide work and rest areas. Avoid heavy partitions to maintain open sightlines and good flow. | 0.34322673082351685 | 1 |
| Q002 | I'm setting up a long-term home office. How can I make my workspace clean and comfortable...? | H025 | Organize Desk Cables | Home | Mount a power strip under the desk, use cable clips to separate power and data cords, and leave some slack for frequently unplugged cables. | 0.3543819189071655 | 2 |
| Q002 | I'm setting up a long-term home office. How can I make my workspace clean and comfortable...? | D020 | Reduce Background Noise in Video... | Digital | Use a headset with a microphone, turn off continuous noise sources in the room, and enable echo cancellation and noise reduction in your conferencing software. | 0.37590378522872925 | 3 |
| Q003 | I just brought a kitten home. What supplies do I need to buy first? | P031 | New Kitten Supply Checklist | Pets | Before bringing a kitten home, prepare a litter box, litter, food and water bowls, age-appropriate food, a scratching post, and a safe hiding spot. Let it acclimate quietly at first. | 0.26469898223876953 | 1 |
| Q003 | I just brought a kitten home. What supplies do I need to buy first? | P035 | Reduce Furniture Scratching | Pets | Place sturdy scratching posts where your cat often stays and scratches. Use toys and rewards to encourage use, rather than just scolding. | 0.3960789442062378 | 2 |
| Q003 | I just brought a kitten home. What supplies do I need to buy first? | P032 | Encourage Your Cat to Drink More Water | Pets | Place water bowls away from food and the litter box, set up multiple water stations, and change the water daily. Some cats prefer running water. | 0.40927886962890625 | 3 |
+----------+-------------------------------------------------------------------------------------------------------------+--------+------------------------------------------+----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+------------+
VECTOR_SEARCH does not guarantee the original output order, so an in-query ranking is explicitly generated based on distance. When you use cosine distance, a smaller value indicates that the vectors are closer.
Expected result: Each query returns 3 results, sorted by distance in ascending order. You can usually observe the following:
Q001prioritizes retrieving content related to Hangzhou, Xixi Wetland, parent-child nature experiences, or leisurely walks.Q002retrieves content related to home office space, home network, video conferencing, or desktop organization.Q003prioritizes retrieving content related to supplies for a new cat, litter boxes, staple food, or helping a cat adapt to a new environment.
The actual ranking may vary depending on the model version and the resulting vectors. The titles do not need to match the descriptions above exactly. Verify that the top 3 results are semantically related to the query.
The default value of use_brute_force is false, which allows the system to use available vector indexes. If no index is available, the system may still fall back to a brute-force search. Returning a result does not guarantee that the query hit an index.
Step 6: Narrow the search with a scalar condition
Real-world searches often include both semantic conditions and scalar conditions, such as category, status, region, or time. VECTOR_SEARCH supports using a subquery as the candidate content table. This lets you first narrow the candidate set with standard SQL conditions before calculating vector distances.
The following example uses Q002 to search for content related to working from home, but returns results only from the "Digital" and "Home" categories:
SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;
SELECT
query.query_id AS query_id,
query.query_text AS query_text,
base.doc_id AS doc_id,
base.title AS title,
base.category AS category,
base.content AS content,
distance
FROM VECTOR_SEARCH(
(
SELECT
doc_id,
title,
category,
content,
text_embedding
FROM text_search_corpus
WHERE category IN ('Digital', 'Home')
AND text_embedding IS NOT NULL
) base,
text_embedding,
(
SELECT
query_id,
query_text,
query_embedding
FROM text_search_query
WHERE query_id = 'Q002'
AND query_embedding IS NOT NULL
) query,
query_embedding,
3,
Cosine
)
ORDER BY distance ASC;
-- The expected result should only contain categories 'Digital' or 'Home'.
-- You can typically observe a mix of digital content (like home networking and video conferencing) and home content (like desk organization and space layout). The specific order depends on the vectors generated by the model.
-- Expected result:
+----------+------------------------------------------------------------------------------------------------+--------+------------------------------------------+----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+
| query_id | query_text | doc_id | title | category | content | distance |
+----------+------------------------------------------------------------------------------------------------+--------+------------------------------------------+----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+
| Q002 | I'm setting up a long-term home office. How can I make my workspace clean and comfortable...? | H026 | Functional Zones in a Small Apartment | Home | Use rugs, low cabinets, and lighting to divide work and rest areas. Avoid heavy partitions to maintain open sightlines and good flow. | 0.34322673082351685 |
| Q002 | I'm setting up a long-term home office. How can I make my workspace clean and comfortable...? | H025 | Organize Desk Cables | Home | Mount a power strip under the desk, use cable clips to separate power and data cords, and leave some slack for frequently unplugged cables. | 0.3543819189071655 |
| Q002 | I'm setting up a long-term home office. How can I make my workspace clean and comfortable...? | D020 | Reduce Background Noise in Video... | Digital | Use a headset with a microphone, turn off continuous noise sources in the room, and enable echo cancellation and noise reduction in your conferencing software. | 0.37590378522872925 |
+----------+------------------------------------------------------------------------------------------------+--------+------------------------------------------+----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+The two subqueries have different roles:
In the base subquery,
category IN ('Digital Products', 'Home Goods')specifies the content to search.In the query subquery,
query_id = 'Q002'specifies which Query to use for the current search.
Place the scalar condition in the base subquery so that the top 3 results are selected from the filtered candidates. If you filter by category after searching the entire corpus, you might retrieve fewer than three results and miss more relevant content from the desired categories.
Verify the results
Verify the following:
Data completeness: Verify that the total number of texts, the number of unique
doc_ids, and the number of non-empty vectors are all 60.Index availability: The index status is
ACTIVE, and the coverage is100%.Correct number of results: Each query returns 3 results.
Correct sorting: The results for the same Query are sorted in ascending order by
distance.Semantic relevance: The top 3 results are centered around the query's intent, not just matching keywords.
Effective filtering: All results from the scalar-filtered query belong to the 'Digital' or 'Home' categories.
Vector distance is not a business confidence score, and there is no universal threshold that applies to all datasets. If you change the model, dimension, or text preprocessing method, you must regenerate the vectors for both the text corpus and the queries and then rebuild the index.
Clean up resources
If you no longer need the resources from this tutorial, run the following SQL statements to delete the index and sample tables.
Data cannot be recovered after deletion. Confirm that these objects are no longer needed, and do not run these commands on tables that contain other business data.
SET odps.namespace.schema=true;
SET odps.sql.type.system.odps2=true;
SET odps.sql.type.vector.enable=true;
DROP INDEX idx_text_search_corpus_embedding
ON text_search_corpus;
DROP TABLE IF EXISTS text_search_query;
DROP TABLE IF EXISTS text_search_corpus;
Next steps
To learn about model invocation parameters and return values, see AI_EMBEDDING.
To learn about vector types, dimensions, and limitations, see vector data type.
To learn how to create, rebuild, inspect, and delete an index, see vector index.
To learn about search parameters, return values, and index fallback behavior, see VECTOR_SEARCH.
To learn about the table format and its capabilities, see Delta Table overview.
To learn about supported regions, models, and fees, see Purchase and use the MaxCompute model inference service.