-
Notifications
You must be signed in to change notification settings - Fork 0
/
VectorDatabase.py
340 lines (279 loc) · 11.1 KB
/
VectorDatabase.py
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import psycopg2
# Class to represent a publication with attributes id, title, pmc, pubmed, and doi
class Publication:
id = ""
title = ""
pmc = ""
pubmed = ""
doi = ""
def __init__(self, id, title, pmc, pubmed, doi):
self.id = id # (DOI) Unique identifier for the publication
self.title = title # Title of the publication
self.pmc = pmc # PubMed Central (PMC) Link
self.pubmed = pubmed # PubMed Link
self.doi = doi # Digital Object Identifier (DOI) Link for the publication
# Class to represent a fragment of a publication with attributes id, header, content, and vector
class Fragment:
# Class variables to store default values for attributes
id = ""
header = ""
content = ""
vector = ""
def __init__(self, id, header, content, vector):
# Constructor to initialize the attributes of the Fragment object
# Set the attributes of the object with the values provided during instantiation
self.id = id # (DOI) Unique identifier for the fragment
self.header = header # Header or title of the fragment
self.content = content # Content or text of the fragment
self.vector = vector # Vector representation of the fragment
# Lantern class that exposes functionality of database to application
class Lantern:
conn = ""
def __init__(self, database="structdb"):
self.conn = self.connect(database) # Connect to database
self.createTables() # Create tables if necessary
def connect(self, database="structdb"):
# We use the dbname, user, and password
# user and password are established in initialize_database.sh
# local version of postgres/lantern
conn = psycopg2.connect(
dbname=database,
user="postgres",
password="postgres",
host="localhost",
port="5432" # default port for Postgres
)
cursor = conn.cursor()
# Execute the query to load the Lantern extension in
cursor.execute("CREATE EXTENSION IF NOT EXISTS lantern;")
conn.commit()
cursor.close()
return conn
def createTables(self):
self.createFragmentTable()
self.createPublicationTable()
self.createUnreadTable()
"""
Creates a table named 'fragments' in the connected database to store fragment information.
Parameters:
- None (uses the database connection stored in self.conn
Returns:
- None
Notes:
- The 'fragments' table will only be created if it does not already exist.
"""
def createFragmentTable(self):
conn = self.conn
cursor = conn.cursor()
create_table_query = "CREATE TABLE IF NOT EXISTS fragments (id text, header text, content text, vector real[]);"
cursor.execute(create_table_query)
conn.commit()
cursor.close()
"""
Creates a table named 'publications' in the connected database to store publication information.
Parameters:
- None (uses the database connection stored in self.conn)
Returns:
- None
Notes:
- The 'publications' table will only be created if it does not already exist.
"""
def createPublicationTable(self):
conn = self.conn
cursor = conn.cursor()
create_table_query = "CREATE TABLE IF NOT EXISTS publications (id text PRIMARY KEY, title text, pmc text, pubmed text, doi text);"
cursor.execute(create_table_query)
conn.commit()
cursor.close()
"""
Creates a table named 'unread' in the connected database to store unread publication identifiers.
Parameters:
- None (uses the database connection stored in self.conn)
Returns:
- None
Notes:
- The 'unread' table will only be created if it does not already exist.
"""
def createUnreadTable(self):
conn = self.conn
cursor = conn.cursor()
create_table_query = "CREATE TABLE IF NOT EXISTS unread (id text PRIMARY KEY);"
cursor.execute(create_table_query)
conn.commit()
cursor.close()
"""
Inserts a fragment and its embedding into the 'fragments' table in the connected database.
Parameters:
- fragment: Fragment, the fragment object containing information to be inserted.
Returns:
- None
Notes:
- Inserts the provided fragment's id, header, content, and vector into the 'fragments' table.
- Creates an HNSW index on the 'vector' column for efficient cosine distance operations.
"""
def insertEmbedding(self, fragment: Fragment):
conn = self.conn
cursor = conn.cursor()
cursor.execute(
"INSERT INTO fragments (id, header, content, vector) VALUES (%s, %s, %s, %s);",
(fragment.id,
fragment.header,
fragment.content,
fragment.vector))
cursor.execute(
"CREATE INDEX ON fragments USING hnsw (vector dist_cos_ops) WITH (dim=" + str(len(fragment.vector)) + ");")
conn.commit()
cursor.close()
"""
Inserts a list of fragments and their embeddings into the 'fragments' table.
Parameters:
- fragments: List[Fragment], a list of fragment objects containing information to be inserted.
Returns:
- None
Notes:
- If the provided list is empty, prints a message and returns without performing insertion.
- Inserts each fragment's id, header, content, and vector into the 'fragments' table using executemany.
- Creates an HNSW index on the 'vector' column for efficient cosine distance operations.
- Prints an error message if there is an exception during insertion.
"""
def insertEmbeddings(self, fragments: list):
if (len(fragments) < 1):
print("Empty List")
return
conn = self.conn
cursor = conn.cursor()
queries = []
for fragment in fragments:
queries.append(
(fragment.id,
fragment.header,
fragment.content,
fragment.vector))
try:
cursor.executemany(
"INSERT INTO fragments (id, header, content, vector) VALUES (%s, %s, %s, %s);",
queries)
except Exception:
print("Error with insertion")
cursor.execute("CREATE INDEX ON fragments USING hnsw (vector dist_cos_ops) WITH (dim=" +
str(len(fragments[0].vector)) + ");")
conn.commit()
cursor.close()
"""
Inserts a publication and its information into the 'publications' and 'unread' tables.
Parameters:
- p: Publication, the publication object containing information to be inserted.
Returns:
- None
Notes:
- If a publication with the same id already exists, returns without performing insertion.
- Inserts the provided publication's id, title, pmc, pubmed, and doi into the 'publications' table.
- Inserts the id of the publication into the 'unread' table to mark it as unread.
"""
def insertPublication(self, p):
if self.publicationExists(p.id):
return
conn = self.conn
cursor = conn.cursor()
cursor.execute(
"INSERT INTO publications (id, title, pmc, pubmed, doi) VALUES (%s, %s, %s, %s, %s);",
(p.id,
p.title,
p.pmc,
p.pubmed,
p.doi))
query = 'INSERT INTO unread (id) VALUES (\'{:s}\');'.format(p.id)
cursor.execute(query)
conn.commit()
cursor.close()
"""
Retrieves all fragments of a publication from the 'fragments' table.
Parameters:
- id: Text, the unique identifier of the publication.
Returns:
- List[Fragment], a list of Fragment objects representing the fragments of the specified publication.
Notes:
- Queries the 'fragments' table to retrieve all fragments with the provided publication id.
- Constructs a list of Fragment objects from the retrieved data.
"""
def getAllFragmentsOfPublication(self, id):
conn = self.conn
cursor = conn.cursor()
query = 'SELECT * FROM fragments WHERE id=\'{:s}\';'.format(id)
cursor.execute(query)
fragments = cursor.fetchall()
conn.commit()
cursor.close()
fragmentObjects = []
for fragment in fragments:
fragmentObjects.append(
Fragment(
id,
fragment[1],
fragment[2],
fragment[3]))
return fragmentObjects
"""
Retrieves unread publications from the 'publications' table.
Parameters:
- delete_unread_entries: bool, decides if entries are deleted from the "unread" table
Returns:
- List[Publication], a list of Publication objects representing the unread publications.
Notes:
- Performs a left join between 'publications' and 'unread' tables to retrieve unread publications.
- Clears the 'unread' table after retrieving the unread publications.
"""
def getUnreadPublications(self, delete_unread_entries=True):
conn = self.conn
cursor = conn.cursor()
cursor.execute(
'SELECT * FROM publications AS p LEFT JOIN unread AS u ON u.id=p.id;')
publications = cursor.fetchall()
if delete_unread_entries:
cursor.execute('DELETE FROM unread;')
conn.commit()
cursor.close()
publicationObjects = []
for p in publications:
publicationObjects.append(
Publication(p[0], p[1], p[2], p[3], p[4]))
return publicationObjects
"""
Checks if a publication with the given id exists in the 'publications' table.
Parameters:
- id: Text, the unique identifier of the publication.
Returns:
- bool, True if a publication with the provided id exists, False otherwise.
Notes:
- Queries the 'publications' table to count the occurrences of the provided id.
- Returns True if the count is equal to 1 (indicating existence), False otherwise.
"""
def publicationExists(self, id):
conn = self.conn
cursor = conn.cursor()
query = 'SELECT COUNT(*) FROM publications WHERE id=\'{:s}\''.format(
id)
cursor.execute(query)
count = cursor.fetchone()
conn.commit()
cursor.close()
return count[0] == 1
"""
Fetches the content and embeddings of a publication by id
Parameters:
- id: Text, the unique identifier of the publication.
Returns:
- [(text, embedding)] content of a publication's embeddings
Notes:
"""
def get_embeddings_for_pub(self, id):
texts = []
embeddings = []
if not self.publicationExists(id):
return
fragments = self.getAllFragmentsOfPublication(id)
for fragment in fragments:
texts.append(fragment.content)
embeddings.append(fragment.vector)
text_embeddings = list(zip(texts, embeddings))
return text_embeddings