1. Create Table and Prepare Data
First, we need to create a table with vector fields and insert test data.Create Table Structure
Insert Test Data
- Randomly generated 3-dimensional vectors
- Random timestamps within the past 10 days
2. Create Vector Index
To improve vector search performance, we need to create an HNSW index.USING vectors
: Use vector index typevector_l2_ops
: Operator class that calculates squared Euclidean distance (L2 distance)
3. Execute Vector Search
Basic Similarity Search
Find the 5 most similar vectors to the target vector[3,1,2]
:
<->
: Calculate L2 distance between two vectors- Smaller distance indicates higher similarity
Complex Conditional Search
Query data from the past 5 days with similarity scores above a threshold:- Inner query: Filter data from the past 5 days, sort by distance and take top 100 records
- Middle query: Convert distance to similarity score (multiply by 10)
- Outer query: Filter records with similarity greater than 50, return 20 results