-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathpgvector_migrator.py
321 lines (280 loc) · 11.5 KB
/
pgvector_migrator.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
import asyncio
import json
import warnings
from typing import Any, AsyncIterator, Iterator, Optional, Sequence, TypeVar
from sqlalchemy import RowMapping, text
from sqlalchemy.exc import ProgrammingError, SQLAlchemyError
from ..v2.engine import PGEngine
from ..v2.vectorstores import PGVectorStore
COLLECTIONS_TABLE = "langchain_pg_collection"
EMBEDDINGS_TABLE = "langchain_pg_embedding"
T = TypeVar("T")
async def __aget_collection_uuid(
engine: PGEngine,
collection_name: str,
) -> str:
"""
Get the collection uuid for a collection present in PGVector tables.
Args:
engine (PGEngine): The PG engine corresponding to the Database.
collection_name (str): The name of the collection to get the uuid for.
Returns:
The uuid corresponding to the collection.
"""
query = f"SELECT name, uuid FROM {COLLECTIONS_TABLE} WHERE name = :collection_name"
async with engine._pool.connect() as conn:
result = await conn.execute(
text(query), parameters={"collection_name": collection_name}
)
result_map = result.mappings()
result_fetch = result_map.fetchone()
if result_fetch is None:
raise ValueError(f"Collection, {collection_name} not found.")
return result_fetch.uuid
async def __aextract_pgvector_collection(
engine: PGEngine,
collection_name: str,
batch_size: int = 1000,
) -> AsyncIterator[Sequence[RowMapping]]:
"""
Extract all data belonging to a PGVector collection.
Args:
engine (PGEngine): The PG engine corresponding to the Database.
collection_name (str): The name of the collection to get the data for.
batch_size (int): The batch size for collection extraction.
Default: 1000. Optional.
Yields:
The data present in the collection.
"""
try:
uuid_task = asyncio.create_task(__aget_collection_uuid(engine, collection_name))
query = f"SELECT * FROM {EMBEDDINGS_TABLE} WHERE collection_id = :id"
async with engine._pool.connect() as conn:
uuid = await uuid_task
result_proxy = await conn.execute(text(query), parameters={"id": uuid})
while True:
rows = result_proxy.fetchmany(size=batch_size)
if not rows:
break
yield [row._mapping for row in rows]
except ValueError:
raise ValueError(f"Collection, {collection_name} does not exist.")
except SQLAlchemyError as e:
raise ProgrammingError(
statement=f"Failed to extract data from collection '{collection_name}': {e}",
params={"id": uuid},
orig=e,
) from e
async def __concurrent_batch_insert(
data_batches: AsyncIterator[Sequence[RowMapping]],
vector_store: PGVectorStore,
max_concurrency: int = 100,
) -> None:
pending: set[Any] = set()
async for batch_data in data_batches:
pending.add(
asyncio.ensure_future(
vector_store.aadd_embeddings(
texts=[data.document for data in batch_data],
embeddings=[json.loads(data.embedding) for data in batch_data],
metadatas=[data.cmetadata for data in batch_data],
ids=[data.id for data in batch_data],
)
)
)
if len(pending) >= max_concurrency:
_, pending = await asyncio.wait(
pending, return_when=asyncio.FIRST_COMPLETED
)
if pending:
await asyncio.wait(pending)
async def __amigrate_pgvector_collection(
engine: PGEngine,
collection_name: str,
vector_store: PGVectorStore,
delete_pg_collection: Optional[bool] = False,
insert_batch_size: int = 1000,
) -> None:
"""
Migrate all data present in a PGVector collection to use separate tables for each collection.
The new data format is compatible with the PGVectoreStore interface.
Args:
engine (PGEngine): The PG engine corresponding to the Database.
collection_name (str): The collection to migrate.
vector_store (PGVectorStore): The PGVectorStore object corresponding to the new collection table.
delete_pg_collection (bool): An option to delete the original data upon migration.
Default: False. Optional.
insert_batch_size (int): Number of rows to insert at once in the table.
Default: 1000.
"""
destination_table = vector_store.get_table_name()
# Get row count in PGVector collection
uuid_task = asyncio.create_task(__aget_collection_uuid(engine, collection_name))
query = (
f"SELECT COUNT(*) FROM {EMBEDDINGS_TABLE} WHERE collection_id=:collection_id"
)
async with engine._pool.connect() as conn:
uuid = await uuid_task
result = await conn.execute(text(query), parameters={"collection_id": uuid})
result_map = result.mappings()
collection_data_len = result_map.fetchone()
if collection_data_len is None:
warnings.warn(f"Collection, {collection_name} contains no elements.")
return
# Extract data from the collection and batch insert into the new table
data_batches = __aextract_pgvector_collection(
engine, collection_name, batch_size=insert_batch_size
)
await __concurrent_batch_insert(data_batches, vector_store, max_concurrency=100)
# Validate data migration
query = f"SELECT COUNT(*) FROM {destination_table}"
async with engine._pool.connect() as conn:
result = await conn.execute(text(query))
result_map = result.mappings()
table_size = result_map.fetchone()
if not table_size:
raise ValueError(f"Table: {destination_table} does not exist.")
if collection_data_len["count"] != table_size["count"]:
raise ValueError(
"All data not yet migrated.\n"
f"Original row count: {collection_data_len['count']}\n"
f"Collection table, {destination_table} row count: {table_size['count']}"
)
elif delete_pg_collection:
# Delete PGVector data
query = f"DELETE FROM {EMBEDDINGS_TABLE} WHERE collection_id=:collection_id"
async with engine._pool.connect() as conn:
await conn.execute(text(query), parameters={"collection_id": uuid})
await conn.commit()
query = f"DELETE FROM {COLLECTIONS_TABLE} WHERE name=:collection_name"
async with engine._pool.connect() as conn:
await conn.execute(
text(query), parameters={"collection_name": collection_name}
)
await conn.commit()
print(f"Successfully deleted PGVector collection, {collection_name}")
async def __alist_pgvector_collection_names(
engine: PGEngine,
) -> list[str]:
"""Lists all collection names present in PGVector table."""
try:
query = f"SELECT name from {COLLECTIONS_TABLE}"
async with engine._pool.connect() as conn:
result = await conn.execute(text(query))
result_map = result.mappings()
all_rows = result_map.fetchall()
return [row["name"] for row in all_rows]
except ProgrammingError as e:
raise ValueError(
"Please provide the correct collection table name: " + str(e)
) from e
async def aextract_pgvector_collection(
engine: PGEngine,
collection_name: str,
batch_size: int = 1000,
) -> AsyncIterator[Sequence[RowMapping]]:
"""
Extract all data belonging to a PGVector collection.
Args:
engine (PGEngine): The PG engine corresponding to the Database.
collection_name (str): The name of the collection to get the data for.
batch_size (int): The batch size for collection extraction.
Default: 1000. Optional.
Yields:
The data present in the collection.
"""
iterator = __aextract_pgvector_collection(engine, collection_name, batch_size)
while True:
try:
result = await engine._run_as_async(iterator.__anext__())
yield result
except StopAsyncIteration:
break
async def alist_pgvector_collection_names(
engine: PGEngine,
) -> list[str]:
"""Lists all collection names present in PGVector table."""
return await engine._run_as_async(__alist_pgvector_collection_names(engine))
async def amigrate_pgvector_collection(
engine: PGEngine,
collection_name: str,
vector_store: PGVectorStore,
delete_pg_collection: Optional[bool] = False,
insert_batch_size: int = 1000,
) -> None:
"""
Migrate all data present in a PGVector collection to use separate tables for each collection.
The new data format is compatible with the PGVectorStore interface.
Args:
engine (PGEngine): The PG engine corresponding to the Database.
collection_name (str): The collection to migrate.
vector_store (PGVectorStore): The PGVectorStore object corresponding to the new collection table.
use_json_metadata (bool): An option to keep the PGVector metadata as json in the new table.
Default: False. Optional.
delete_pg_collection (bool): An option to delete the original data upon migration.
Default: False. Optional.
insert_batch_size (int): Number of rows to insert at once in the table.
Default: 1000.
"""
await engine._run_as_async(
__amigrate_pgvector_collection(
engine,
collection_name,
vector_store,
delete_pg_collection,
insert_batch_size,
)
)
def extract_pgvector_collection(
engine: PGEngine,
collection_name: str,
batch_size: int = 1000,
) -> Iterator[Sequence[RowMapping]]:
"""
Extract all data belonging to a PGVector collection.
Args:
engine (PGEngine): The PG engine corresponding to the Database.
collection_name (str): The name of the collection to get the data for.
batch_size (int): The batch size for collection extraction.
Default: 1000. Optional.
Yields:
The data present in the collection.
"""
iterator = __aextract_pgvector_collection(engine, collection_name, batch_size)
while True:
try:
result = engine._run_as_sync(iterator.__anext__())
yield result
except StopAsyncIteration:
break
def list_pgvector_collection_names(engine: PGEngine) -> list[str]:
"""Lists all collection names present in PGVector table."""
return engine._run_as_sync(__alist_pgvector_collection_names(engine))
def migrate_pgvector_collection(
engine: PGEngine,
collection_name: str,
vector_store: PGVectorStore,
delete_pg_collection: Optional[bool] = False,
insert_batch_size: int = 1000,
) -> None:
"""
Migrate all data present in a PGVector collection to use separate tables for each collection.
The new data format is compatible with the PGVectorStore interface.
Args:
engine (PGEngine): The PG engine corresponding to the Database.
collection_name (str): The collection to migrate.
vector_store (PGVectorStore): The PGVectorStore object corresponding to the new collection table.
delete_pg_collection (bool): An option to delete the original data upon migration.
Default: False. Optional.
insert_batch_size (int): Number of rows to insert at once in the table.
Default: 1000.
"""
engine._run_as_sync(
__amigrate_pgvector_collection(
engine,
collection_name,
vector_store,
delete_pg_collection,
insert_batch_size,
)
)