5.6 Vector Query
Vector Query finds similar records by vector distance on data sources that support vector capabilities. dbVisitor exposes two builder entries: orderBy* for Top-K nearest-neighbor ordering, and vectorBy* for distance range filtering.
Suitable For
- Tables contain embedding, feature-vector, image-vector, or text-vector fields.
- The query needs the N most similar records.
- The query needs all records within a distance threshold.
- Vector predicates need to compose with ordinary scalar predicates.
Not Suitable For
- Complex hybrid ranking requires full SQL control; use JdbcTemplate.
Query Styles
| Style | API | Typical Question | Read |
|---|---|---|---|
| KNN ordering | orderByL2, orderByCosine, orderByIP, orderByMetric | Find the N most similar records. | KNN Ordering |
| Distance range filtering | vectorByL2, vectorByCosine, vectorByIP, and others | Find all records below a distance threshold. | Distance Range Filtering |
| Combined query | Scalar predicates + orderBy* / vectorBy* | Narrow by business predicates, then run vector query. | Combined Queries |
Choose a query style
Need a fixed Top N
|
+-- Use orderBy* ordering
+-- Use initPage to limit result count
Need all records under a threshold
|
+-- Use vectorBy* predicates
+-- Threshold decides result count
Basic Flow
Vector query flow
Create a table with a vector field
|
Configure entity field and TypeHandler
|
Write or read vector values
|
Choose orderBy* or vectorBy*
|
Compose scalar predicates, paging, or ordering
Vector fields are commonly represented as List<Float> in Java and converted to database vector values through a TypeHandler. See Vector Type Mapping for the setup steps.
orderBy vs vectorBy
| Item | orderBy* | vectorBy* |
|---|---|---|
| SQL position | ORDER BY | WHERE |
| Typical question | Find the N most similar records | Find all records under a distance threshold |
| Result count | Usually fixed with initPage | Depends on threshold and data distribution |
| Vector argument | Converted by the field mapping TypeHandler | Converted by the field mapping TypeHandler |
| Condition composition | Sorts after ordinary WHERE predicates | Is itself a WHERE predicate |
Database Support
Vector SQL is generated by the dialect. Supported dialects include PostgreSQL pgvector, Milvus, and ElasticSearch. Available metrics, indexes, and parameter formats vary by database and driver.
Further Reading
- Vector Type Mapping, table fields, entity fields, and TypeHandler configuration.
- KNN Ordering, use
orderBy*to find the N most similar records. - Distance Range Filtering, use
vectorBy*to filter by distance threshold. - Combined Queries, compose vector query with scalar predicates.