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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
|
import json
import logging
import os
import time
from typing import Literal, Optional, Union
from sqlalchemy import exc, text
from sqlalchemy.engine.url import make_url
from r2r.base import (
DocumentInfo,
UserStats,
VectorDBConfig,
VectorDBProvider,
VectorEntry,
VectorSearchResult,
)
from r2r.vecs.client import Client
from r2r.vecs.collection import Collection
logger = logging.getLogger(__name__)
class PGVectorDB(VectorDBProvider):
def __init__(self, config: VectorDBConfig) -> None:
super().__init__(config)
try:
import r2r.vecs
except ImportError:
raise ValueError(
f"Error, PGVectorDB requires the vecs library. Please run `pip install vecs`."
)
# Check if a complete Postgres URI is provided
postgres_uri = self.config.extra_fields.get(
"postgres_uri"
) or os.getenv("POSTGRES_URI")
if postgres_uri:
# Log loudly that Postgres URI is being used
logger.warning("=" * 50)
logger.warning(
"ATTENTION: Using provided Postgres URI for connection"
)
logger.warning("=" * 50)
# Validate and use the provided URI
try:
parsed_uri = make_url(postgres_uri)
if not all([parsed_uri.username, parsed_uri.database]):
raise ValueError(
"The provided Postgres URI is missing required components."
)
DB_CONNECTION = postgres_uri
# Log the sanitized URI (without password)
sanitized_uri = parsed_uri.set(password="*****")
logger.info(f"Connecting using URI: {sanitized_uri}")
except Exception as e:
raise ValueError(f"Invalid Postgres URI provided: {e}")
else:
# Fall back to existing logic for individual connection parameters
user = self.config.extra_fields.get("user", None) or os.getenv(
"POSTGRES_USER"
)
password = self.config.extra_fields.get(
"password", None
) or os.getenv("POSTGRES_PASSWORD")
host = self.config.extra_fields.get("host", None) or os.getenv(
"POSTGRES_HOST"
)
port = self.config.extra_fields.get("port", None) or os.getenv(
"POSTGRES_PORT"
)
db_name = self.config.extra_fields.get(
"db_name", None
) or os.getenv("POSTGRES_DBNAME")
if not all([user, password, host, db_name]):
raise ValueError(
"Error, please set the POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_HOST, POSTGRES_DBNAME environment variables or provide them in the config."
)
# Check if it's a Unix socket connection
if host.startswith("/") and not port:
DB_CONNECTION = (
f"postgresql://{user}:{password}@/{db_name}?host={host}"
)
logger.info("Using Unix socket connection")
else:
DB_CONNECTION = (
f"postgresql://{user}:{password}@{host}:{port}/{db_name}"
)
logger.info("Using TCP connection")
# The rest of the initialization remains the same
try:
self.vx: Client = r2r.vecs.create_client(DB_CONNECTION)
except Exception as e:
raise ValueError(
f"Error {e} occurred while attempting to connect to the pgvector provider with {DB_CONNECTION}."
)
self.collection_name = self.config.extra_fields.get(
"vecs_collection"
) or os.getenv("POSTGRES_VECS_COLLECTION")
if not self.collection_name:
raise ValueError(
"Error, please set a valid POSTGRES_VECS_COLLECTION environment variable or set a 'vecs_collection' in the 'vector_database' settings of your `config.json`."
)
self.collection: Optional[Collection] = None
logger.info(
f"Successfully initialized PGVectorDB with collection: {self.collection_name}"
)
def initialize_collection(self, dimension: int) -> None:
self.collection = self.vx.get_or_create_collection(
name=self.collection_name, dimension=dimension
)
self._create_document_info_table()
self._create_hybrid_search_function()
def _create_document_info_table(self):
with self.vx.Session() as sess:
with sess.begin():
try:
# Enable uuid-ossp extension
sess.execute(
text('CREATE EXTENSION IF NOT EXISTS "uuid-ossp";')
)
except exc.ProgrammingError as e:
logger.error(f"Error enabling uuid-ossp extension: {e}")
raise
# Create the table if it doesn't exist
create_table_query = f"""
CREATE TABLE IF NOT EXISTS document_info_"{self.collection_name}" (
document_id UUID PRIMARY KEY,
title TEXT,
user_id UUID NULL,
version TEXT,
size_in_bytes INT,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
metadata JSONB,
status TEXT
);
"""
sess.execute(text(create_table_query))
# Add the new column if it doesn't exist
add_column_query = f"""
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1
FROM information_schema.columns
WHERE table_name = 'document_info_"{self.collection_name}"'
AND column_name = 'status'
) THEN
ALTER TABLE "document_info_{self.collection_name}"
ADD COLUMN status TEXT DEFAULT 'processing';
END IF;
END $$;
"""
sess.execute(text(add_column_query))
sess.commit()
def _create_hybrid_search_function(self):
hybrid_search_function = f"""
CREATE OR REPLACE FUNCTION hybrid_search_{self.collection_name}(
query_text TEXT,
query_embedding VECTOR(512),
match_limit INT,
full_text_weight FLOAT = 1,
semantic_weight FLOAT = 1,
rrf_k INT = 50,
filter_condition JSONB = NULL
)
RETURNS SETOF vecs."{self.collection_name}"
LANGUAGE sql
AS $$
WITH full_text AS (
SELECT
id,
ROW_NUMBER() OVER (ORDER BY ts_rank(to_tsvector('english', metadata->>'text'), websearch_to_tsquery(query_text)) DESC) AS rank_ix
FROM vecs."{self.collection_name}"
WHERE to_tsvector('english', metadata->>'text') @@ websearch_to_tsquery(query_text)
AND (filter_condition IS NULL OR (metadata @> filter_condition))
ORDER BY rank_ix
LIMIT LEAST(match_limit, 30) * 2
),
semantic AS (
SELECT
id,
ROW_NUMBER() OVER (ORDER BY vec <#> query_embedding) AS rank_ix
FROM vecs."{self.collection_name}"
WHERE filter_condition IS NULL OR (metadata @> filter_condition)
ORDER BY rank_ix
LIMIT LEAST(match_limit, 30) * 2
)
SELECT
vecs."{self.collection_name}".*
FROM
full_text
FULL OUTER JOIN semantic
ON full_text.id = semantic.id
JOIN vecs."{self.collection_name}"
ON vecs."{self.collection_name}".id = COALESCE(full_text.id, semantic.id)
ORDER BY
COALESCE(1.0 / (rrf_k + full_text.rank_ix), 0.0) * full_text_weight +
COALESCE(1.0 / (rrf_k + semantic.rank_ix), 0.0) * semantic_weight
DESC
LIMIT
LEAST(match_limit, 30);
$$;
"""
retry_attempts = 5
for attempt in range(retry_attempts):
try:
with self.vx.Session() as sess:
# Acquire an advisory lock
sess.execute(text("SELECT pg_advisory_lock(123456789)"))
try:
sess.execute(text(hybrid_search_function))
sess.commit()
finally:
# Release the advisory lock
sess.execute(
text("SELECT pg_advisory_unlock(123456789)")
)
break # Break the loop if successful
except exc.InternalError as e:
if "tuple concurrently updated" in str(e):
time.sleep(2**attempt) # Exponential backoff
else:
raise # Re-raise the exception if it's not a concurrency issue
else:
raise RuntimeError(
"Failed to create hybrid search function after multiple attempts"
)
def copy(self, entry: VectorEntry, commit=True) -> None:
if self.collection is None:
raise ValueError(
"Please call `initialize_collection` before attempting to run `copy`."
)
serializeable_entry = entry.to_serializable()
self.collection.copy(
records=[
(
serializeable_entry["id"],
serializeable_entry["vector"],
serializeable_entry["metadata"],
)
]
)
def copy_entries(
self, entries: list[VectorEntry], commit: bool = True
) -> None:
if self.collection is None:
raise ValueError(
"Please call `initialize_collection` before attempting to run `copy_entries`."
)
self.collection.copy(
records=[
(
str(entry.id),
entry.vector.data,
entry.to_serializable()["metadata"],
)
for entry in entries
]
)
def upsert(self, entry: VectorEntry, commit=True) -> None:
if self.collection is None:
raise ValueError(
"Please call `initialize_collection` before attempting to run `upsert`."
)
self.collection.upsert(
records=[
(
str(entry.id),
entry.vector.data,
entry.to_serializable()["metadata"],
)
]
)
def upsert_entries(
self, entries: list[VectorEntry], commit: bool = True
) -> None:
if self.collection is None:
raise ValueError(
"Please call `initialize_collection` before attempting to run `upsert_entries`."
)
self.collection.upsert(
records=[
(
str(entry.id),
entry.vector.data,
entry.to_serializable()["metadata"],
)
for entry in entries
]
)
def search(
self,
query_vector: list[float],
filters: dict[str, Union[bool, int, str]] = {},
limit: int = 10,
*args,
**kwargs,
) -> list[VectorSearchResult]:
if self.collection is None:
raise ValueError(
"Please call `initialize_collection` before attempting to run `search`."
)
measure = kwargs.get("measure", "cosine_distance")
mapped_filters = {
key: {"$eq": value} for key, value in filters.items()
}
return [
VectorSearchResult(id=ele[0], score=float(1 - ele[1]), metadata=ele[2]) # type: ignore
for ele in self.collection.query(
data=query_vector,
limit=limit,
filters=mapped_filters,
measure=measure,
include_value=True,
include_metadata=True,
)
]
def hybrid_search(
self,
query_text: str,
query_vector: list[float],
limit: int = 10,
filters: Optional[dict[str, Union[bool, int, str]]] = None,
# Hybrid search parameters
full_text_weight: float = 1.0,
semantic_weight: float = 1.0,
rrf_k: int = 20, # typical value is ~2x the number of results you want
*args,
**kwargs,
) -> list[VectorSearchResult]:
if self.collection is None:
raise ValueError(
"Please call `initialize_collection` before attempting to run `hybrid_search`."
)
# Convert filters to a JSON-compatible format
filter_condition = None
if filters:
filter_condition = json.dumps(filters)
query = text(
f"""
SELECT * FROM hybrid_search_{self.collection_name}(
cast(:query_text as TEXT), cast(:query_embedding as VECTOR), cast(:match_limit as INT),
cast(:full_text_weight as FLOAT), cast(:semantic_weight as FLOAT), cast(:rrf_k as INT),
cast(:filter_condition as JSONB)
)
"""
)
params = {
"query_text": str(query_text),
"query_embedding": list(query_vector),
"match_limit": limit,
"full_text_weight": full_text_weight,
"semantic_weight": semantic_weight,
"rrf_k": rrf_k,
"filter_condition": filter_condition,
}
with self.vx.Session() as session:
result = session.execute(query, params).fetchall()
return [
VectorSearchResult(id=row[0], score=1.0, metadata=row[-1])
for row in result
]
def create_index(self, index_type, column_name, index_options):
pass
def delete_by_metadata(
self,
metadata_fields: list[str],
metadata_values: list[Union[bool, int, str]],
logic: Literal["AND", "OR"] = "AND",
) -> list[str]:
if logic == "OR":
raise ValueError(
"OR logic is still being tested before official support for `delete_by_metadata` in pgvector."
)
if self.collection is None:
raise ValueError(
"Please call `initialize_collection` before attempting to run `delete_by_metadata`."
)
if len(metadata_fields) != len(metadata_values):
raise ValueError(
"The number of metadata fields must match the number of metadata values."
)
# Construct the filter
if logic == "AND":
filters = {
k: {"$eq": v} for k, v in zip(metadata_fields, metadata_values)
}
else: # OR logic
# TODO - Test 'or' logic and remove check above
filters = {
"$or": [
{k: {"$eq": v}}
for k, v in zip(metadata_fields, metadata_values)
]
}
return self.collection.delete(filters=filters)
def get_metadatas(
self,
metadata_fields: list[str],
filter_field: Optional[str] = None,
filter_value: Optional[Union[bool, int, str]] = None,
) -> list[dict]:
if self.collection is None:
raise ValueError(
"Please call `initialize_collection` before attempting to run `get_metadatas`."
)
results = {tuple(metadata_fields): {}}
for field in metadata_fields:
unique_values = self.collection.get_unique_metadata_values(
field=field,
filter_field=filter_field,
filter_value=filter_value,
)
for value in unique_values:
if value not in results:
results[value] = {}
results[value][field] = value
return [
results[key] for key in results if key != tuple(metadata_fields)
]
def upsert_documents_overview(
self, documents_overview: list[DocumentInfo]
) -> None:
for document_info in documents_overview:
db_entry = document_info.convert_to_db_entry()
# Convert 'None' string to None type for user_id
if db_entry["user_id"] == "None":
db_entry["user_id"] = None
query = text(
f"""
INSERT INTO "document_info_{self.collection_name}" (document_id, title, user_id, version, created_at, updated_at, size_in_bytes, metadata, status)
VALUES (:document_id, :title, :user_id, :version, :created_at, :updated_at, :size_in_bytes, :metadata, :status)
ON CONFLICT (document_id) DO UPDATE SET
title = EXCLUDED.title,
user_id = EXCLUDED.user_id,
version = EXCLUDED.version,
updated_at = EXCLUDED.updated_at,
size_in_bytes = EXCLUDED.size_in_bytes,
metadata = EXCLUDED.metadata,
status = EXCLUDED.status;
"""
)
with self.vx.Session() as sess:
sess.execute(query, db_entry)
sess.commit()
def delete_from_documents_overview(
self, document_id: str, version: Optional[str] = None
) -> None:
query = f"""
DELETE FROM "document_info_{self.collection_name}"
WHERE document_id = :document_id
"""
params = {"document_id": document_id}
if version is not None:
query += " AND version = :version"
params["version"] = version
with self.vx.Session() as sess:
with sess.begin():
sess.execute(text(query), params)
sess.commit()
def get_documents_overview(
self,
filter_document_ids: Optional[list[str]] = None,
filter_user_ids: Optional[list[str]] = None,
):
conditions = []
params = {}
if filter_document_ids:
placeholders = ", ".join(
f":doc_id_{i}" for i in range(len(filter_document_ids))
)
conditions.append(f"document_id IN ({placeholders})")
params.update(
{
f"doc_id_{i}": str(document_id)
for i, document_id in enumerate(filter_document_ids)
}
)
if filter_user_ids:
placeholders = ", ".join(
f":user_id_{i}" for i in range(len(filter_user_ids))
)
conditions.append(f"user_id IN ({placeholders})")
params.update(
{
f"user_id_{i}": str(user_id)
for i, user_id in enumerate(filter_user_ids)
}
)
query = f"""
SELECT document_id, title, user_id, version, size_in_bytes, created_at, updated_at, metadata, status
FROM "document_info_{self.collection_name}"
"""
if conditions:
query += " WHERE " + " AND ".join(conditions)
with self.vx.Session() as sess:
results = sess.execute(text(query), params).fetchall()
return [
DocumentInfo(
document_id=row[0],
title=row[1],
user_id=row[2],
version=row[3],
size_in_bytes=row[4],
created_at=row[5],
updated_at=row[6],
metadata=row[7],
status=row[8],
)
for row in results
]
def get_document_chunks(self, document_id: str) -> list[dict]:
if not self.collection:
raise ValueError("Collection is not initialized.")
table_name = self.collection.table.name
query = text(
f"""
SELECT metadata
FROM vecs."{table_name}"
WHERE metadata->>'document_id' = :document_id
ORDER BY CAST(metadata->>'chunk_order' AS INTEGER)
"""
)
params = {"document_id": document_id}
with self.vx.Session() as sess:
results = sess.execute(query, params).fetchall()
return [result[0] for result in results]
def get_users_overview(self, user_ids: Optional[list[str]] = None):
user_ids_condition = ""
params = {}
if user_ids:
user_ids_condition = "WHERE user_id IN :user_ids"
params["user_ids"] = tuple(
map(str, user_ids)
) # Convert UUIDs to strings
query = f"""
SELECT user_id, COUNT(document_id) AS num_files, SUM(size_in_bytes) AS total_size_in_bytes, ARRAY_AGG(document_id) AS document_ids
FROM "document_info_{self.collection_name}"
{user_ids_condition}
GROUP BY user_id
"""
with self.vx.Session() as sess:
results = sess.execute(text(query), params).fetchall()
return [
UserStats(
user_id=row[0],
num_files=row[1],
total_size_in_bytes=row[2],
document_ids=row[3],
)
for row in results
if row[0] is not None
]
|