-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimilarity-search.js
104 lines (89 loc) · 2.32 KB
/
similarity-search.js
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import { getEmbedding } from "./embed-into-supabase.js";
import { createClient } from "@supabase/supabase-js";
import dotenv from "dotenv";
dotenv.config();
const supabaseUrl = process.env.SUPABASE_URL;
const supabaseKey = process.env.SUPABASE_KEY;
const supabase = createClient(supabaseUrl, supabaseKey, {
auth: {
persistSession: false,
},
});
/*
return similarity search in this format
{
text
title
similarity
}
*/
export const similaritySearch = async (query) => {
const embedding = await getEmbedding(query);
const res = [];
const { data: documents, error } = await supabase.rpc("match_highlights", {
query_embedding: embedding,
match_count: 3,
match_threshold: 0.0,
});
for (const document of documents) {
const { data: highlights, error } = await supabase
.from("highlights")
.select("*")
.eq("id", document.id);
const book_id = highlights[0].book_id;
const { data: books, error: bookError } = await supabase
.from("books")
.select("*")
.eq("book_id", book_id);
res.push({
text: highlights[0].text,
title: books[0].title,
similarity: document.similarity,
id: highlights[0].id,
author: books[0].author,
thoughts: highlights[0].thoughts,
});
}
if (error) {
console.log(error);
return;
}
return res;
};
export const similaritySearchWhereBookIDs = async (query, bookIDs) => {
const embedding = await getEmbedding(query);
const res = [];
const { data: documents, error } = await supabase.rpc(
"match_highlights_where_book_ids",
{
query_embedding: embedding,
match_count: 3,
match_threshold: 0.0,
book_ids: bookIDs,
}
);
for (const document of documents) {
const { data: highlights, error } = await supabase
.from("highlights")
.select("*")
.eq("id", document.id);
const book_id = highlights[0].book_id;
const { data: books, error: bookError } = await supabase
.from("books")
.select("*")
.eq("book_id", book_id);
res.push({
text: highlights[0].text,
title: books[0].title,
similarity: document.similarity,
id: highlights[0].id,
author: books[0].author,
thoughts: highlights[0].thoughts,
});
}
if (error) {
console.log(error);
return;
}
return res;
};