-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathvector-search.ts
More file actions
70 lines (57 loc) · 2.05 KB
/
Copy pathvector-search.ts
File metadata and controls
70 lines (57 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { sql } from "drizzle-orm";
import { closeDb, db, mockItems, setupMockItems } from "./common.js";
import { search } from "../src/index.js";
// In production, compute query embeddings with the same model that produced
// the stored embeddings. This fixed vector stands in for that model.
const queryEmbedding = [-0.02, 0.47, -0.76, 0.13, 0.34, 0.04, 0.19, -0.19];
export async function runVectorSearch(): Promise<void> {
console.log("=".repeat(60));
console.log("Vector Search inside a ParadeDB Index");
console.log("=".repeat(60));
console.log("\nTop-K nearest neighbors served by the paradedb index.");
console.log("A @@@ predicate and a LIMIT are required for index pushdown.");
await setupMockItems();
await nearestNeighbors();
await filteredNearestNeighbors("Footwear");
console.log("\n" + "=".repeat(60));
console.log("Done!");
}
async function nearestNeighbors(): Promise<void> {
console.log("\n--- Nearest neighbors across all items ---");
const distance = search.cosineDistance(mockItems.embedding, queryEmbedding);
for (const item of await db
.select({
description: mockItems.description,
distance: sql<number>`(${distance})::float8`,
})
.from(mockItems)
.where(search.all(mockItems.id))
.orderBy(distance)
.limit(5)) {
console.log(
` • ${item.description.padEnd(40)} (distance: ${item.distance.toFixed(4)})`,
);
}
}
async function filteredNearestNeighbors(category: string): Promise<void> {
console.log(`\n--- Nearest neighbors in category '${category}' ---`);
const distance = search.cosineDistance(mockItems.embedding, queryEmbedding);
for (const item of await db
.select({
description: mockItems.description,
distance: sql<number>`(${distance})::float8`,
})
.from(mockItems)
.where(search.term(mockItems.category, category))
.orderBy(distance)
.limit(5)) {
console.log(
` • ${item.description.padEnd(40)} (distance: ${item.distance.toFixed(4)})`,
);
}
}
try {
await runVectorSearch();
} finally {
await closeDb();
}