-
Notifications
You must be signed in to change notification settings - Fork 65
/
cloudsql_mysql.py
826 lines (752 loc) · 29.2 KB
/
cloudsql_mysql.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
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
from datetime import datetime
from typing import Any, Literal, Optional
import pymysql
from google.cloud.sql.connector import Connector, RefreshStrategy
from pydantic import BaseModel
from sqlalchemy import Engine, create_engine, text
from sqlalchemy.engine.base import Engine
import models
from .. import datastore
MYSQL_IDENTIFIER = "cloudsql-mysql"
class Config(BaseModel, datastore.AbstractConfig):
kind: Literal["cloudsql-mysql"]
project: str
region: str
instance: str
user: str
password: str
database: str
class Client(datastore.Client[Config]):
__pool: Engine
__db_name: str
@datastore.classproperty
def kind(cls):
return MYSQL_IDENTIFIER
def __init__(self, pool: Engine, db_name: str):
self.__pool = pool
self.__db_name = db_name
@classmethod
def create_sync(cls, config: Config) -> "Client":
def getconn() -> pymysql.Connection:
with Connector(refresh_strategy=RefreshStrategy.LAZY) as connector:
conn: pymysql.Connection = connector.connect(
# Cloud SQL instance connection name
f"{config.project}:{config.region}:{config.instance}",
"pymysql",
user=f"{config.user}",
password=f"{config.password}",
db=f"{config.database}",
autocommit=True,
)
return conn
pool = create_engine(
"mysql+pymysql://",
creator=getconn,
)
if pool is None:
raise TypeError("pool not instantiated")
return cls(pool, config.database)
@classmethod
async def create(cls, config: Config) -> "Client":
loop = asyncio.get_running_loop()
pool = await loop.run_in_executor(None, cls.create_sync, config)
return pool
def drop_vector_indexes(self):
with self.__pool.connect() as conn:
s = text("""SELECT index_name FROM mysql.vector_indexes""")
results = (conn.execute(s)).mappings().fetchall()
for r in results:
conn.execute(text(f"CALL mysql.drop_vector_index('{r['index_name']}')"))
def initialize_data_sync(
self,
airports: list[models.Airport],
amenities: list[models.Amenity],
flights: list[models.Flight],
policies: list[models.Policy],
) -> None:
self.drop_vector_indexes()
with self.__pool.connect() as conn:
# If the table already exists, drop it to avoid conflicts
conn.execute(text("DROP TABLE IF EXISTS airports"))
# Create a new table
conn.execute(
text(
"""
CREATE TABLE airports(
id INT PRIMARY KEY,
iata TEXT,
name TEXT,
city TEXT,
country TEXT
)
"""
)
)
# Insert all the data
conn.execute(
text(
"""INSERT INTO airports VALUES (:id, :iata, :name, :city, :country)"""
),
parameters=[
{
"id": a.id,
"iata": a.iata,
"name": a.name,
"city": a.city,
"country": a.country,
}
for a in airports
],
)
# If the table already exists, drop it to avoid conflicts
conn.execute(text("DROP TABLE IF EXISTS amenities CASCADE"))
# Create a new table
conn.execute(
text(
"""
CREATE TABLE amenities(
id INT PRIMARY KEY,
name TEXT,
description TEXT,
location TEXT,
terminal TEXT,
category TEXT,
hour TEXT,
sunday_start_hour TIME,
sunday_end_hour TIME,
monday_start_hour TIME,
monday_end_hour TIME,
tuesday_start_hour TIME,
tuesday_end_hour TIME,
wednesday_start_hour TIME,
wednesday_end_hour TIME,
thursday_start_hour TIME,
thursday_end_hour TIME,
friday_start_hour TIME,
friday_end_hour TIME,
saturday_start_hour TIME,
saturday_end_hour TIME,
content TEXT NOT NULL,
embedding vector(768) USING VARBINARY NOT NULL
)
"""
)
)
# Insert all the data
conn.execute(
text(
"""
INSERT INTO amenities VALUES (:id, :name, :description, :location,
:terminal, :category, :hour, :sunday_start_hour, :sunday_end_hour,
:monday_start_hour, :monday_end_hour, :tuesday_start_hour,
:tuesday_end_hour, :wednesday_start_hour, :wednesday_end_hour,
:thursday_start_hour, :thursday_end_hour, :friday_start_hour,
:friday_end_hour, :saturday_start_hour, :saturday_end_hour, :content, string_to_vector(:embedding))
"""
),
parameters=[
{
"id": a.id,
"name": a.name,
"description": a.description,
"location": a.location,
"terminal": a.terminal,
"category": a.category,
"hour": a.hour,
"sunday_start_hour": a.sunday_start_hour,
"sunday_end_hour": a.sunday_end_hour,
"monday_start_hour": a.monday_start_hour,
"monday_end_hour": a.monday_end_hour,
"tuesday_start_hour": a.tuesday_start_hour,
"tuesday_end_hour": a.tuesday_end_hour,
"wednesday_start_hour": a.wednesday_start_hour,
"wednesday_end_hour": a.wednesday_end_hour,
"thursday_start_hour": a.thursday_start_hour,
"thursday_end_hour": a.thursday_end_hour,
"friday_start_hour": a.friday_start_hour,
"friday_end_hour": a.friday_end_hour,
"saturday_start_hour": a.saturday_start_hour,
"saturday_end_hour": a.saturday_end_hour,
"content": a.content,
"embedding": f"{a.embedding}",
}
for a in amenities
],
)
# Create a vector index for the embeddings column
conn.execute(
text(
f"CALL mysql.create_vector_index('amenities_index', '{self.__db_name}.amenities', 'embedding', '')"
)
)
# If the table already exists, drop it to avoid conflicts
conn.execute(text("DROP TABLE IF EXISTS flights"))
# Create a new table
conn.execute(
text(
"""
CREATE TABLE flights(
id INTEGER PRIMARY KEY,
airline TEXT,
flight_number TEXT,
departure_airport TEXT,
arrival_airport TEXT,
departure_time TIMESTAMP,
arrival_time TIMESTAMP,
departure_gate TEXT,
arrival_gate TEXT
)
"""
)
)
# Insert all the data
conn.execute(
text(
"""
INSERT INTO flights VALUES (:id, :airline, :flight_number,
:departure_airport, :arrival_airport, :departure_time,
:arrival_time, :departure_gate, :arrival_gate)
"""
),
parameters=[
{
"id": f.id,
"airline": f.airline,
"flight_number": f.flight_number,
"departure_airport": f.departure_airport,
"arrival_airport": f.arrival_airport,
"departure_time": f.departure_time,
"arrival_time": f.arrival_time,
"departure_gate": f.departure_gate,
"arrival_gate": f.arrival_gate,
}
for f in flights
],
)
# If the table already exists, drop it to avoid conflicts
conn.execute(text("DROP TABLE IF EXISTS tickets"))
# Create a new table
conn.execute(
text(
"""
CREATE TABLE tickets(
user_id TEXT,
user_name TEXT,
user_email TEXT,
airline TEXT,
flight_number TEXT,
departure_airport TEXT,
arrival_airport TEXT,
departure_time TIMESTAMP,
arrival_time TIMESTAMP
)
"""
)
)
# If the table already exists, drop it to avoid conflicts
conn.execute(text("DROP TABLE IF EXISTS policies"))
# Create a new table
conn.execute(
text(
"""
CREATE TABLE policies(
id INT PRIMARY KEY,
content TEXT NOT NULL,
embedding vector(768) USING VARBINARY NOT NULL
)
"""
)
)
# Insert all the data
conn.execute(
text(
"""
INSERT INTO policies VALUES (:id, :content, string_to_vector(:embedding))
"""
),
parameters=[
{
"id": p.id,
"content": p.content,
"embedding": f"{p.embedding}",
}
for p in policies
],
)
# Create a vector index on the embedding column
conn.execute(
text(
f"CALL mysql.create_vector_index('policies_index', '{self.__db_name}.policies', 'embedding', '')"
)
)
async def initialize_data(
self,
airports: list[models.Airport],
amenities: list[models.Amenity],
flights: list[models.Flight],
policies: list[models.Policy],
) -> None:
loop = asyncio.get_running_loop()
await loop.run_in_executor(
None, self.initialize_data_sync, airports, amenities, flights, policies
)
def export_data_sync(
self,
) -> tuple[
list[models.Airport],
list[models.Amenity],
list[models.Flight],
list[models.Policy],
]:
with self.__pool.connect() as conn:
airport_task = conn.execute(
text("""SELECT * FROM airports ORDER BY id ASC""")
)
amenity_task = conn.execute(
text(
"""
SELECT id,
name,
description,
location,
terminal,
category,
hour,
DATE_FORMAT(sunday_start_hour, '%H:%i') AS sunday_start_hour,
DATE_FORMAT(sunday_end_hour, '%H:%i') AS sunday_end_hour,
DATE_FORMAT(monday_start_hour, '%H:%i') AS monday_start_hour,
DATE_FORMAT(monday_end_hour, '%H:%i') AS monday_end_hour,
DATE_FORMAT(tuesday_start_hour, '%H:%i') AS tuesday_start_hour,
DATE_FORMAT(tuesday_end_hour, '%H:%i') AS tuesday_end_hour,
DATE_FORMAT(wednesday_start_hour, '%H:%i') AS wednesday_start_hour,
DATE_FORMAT(wednesday_end_hour, '%H:%i') AS wednesday_end_hour,
DATE_FORMAT(thursday_start_hour, '%H:%i') AS thursday_start_hour,
DATE_FORMAT(thursday_end_hour, '%H:%i') AS thursday_end_hour,
DATE_FORMAT(friday_start_hour, '%H:%i') AS friday_start_hour,
DATE_FORMAT(friday_end_hour, '%H:%i') AS friday_end_hour,
DATE_FORMAT(saturday_start_hour, '%H:%i') AS saturday_start_hour,
DATE_FORMAT(saturday_end_hour, '%H:%i') AS saturday_end_hour,
content,
vector_to_string(embedding) as embedding
FROM amenities ORDER BY id ASC
"""
)
)
flights_task = conn.execute(
text("""SELECT * FROM flights ORDER BY id ASC""")
)
policy_task = conn.execute(
text(
"""SELECT id, content, vector_to_string(embedding) as embedding FROM policies ORDER BY id ASC"""
)
)
airport_results = (airport_task).mappings().fetchall()
amenity_results = (amenity_task).mappings().fetchall()
flights_results = (flights_task).mappings().fetchall()
policy_results = (policy_task).mappings().fetchall()
airports = [models.Airport.model_validate(a) for a in airport_results]
amenities = [models.Amenity.model_validate(a) for a in amenity_results]
flights = [models.Flight.model_validate(f) for f in flights_results]
policies = [models.Policy.model_validate(p) for p in policy_results]
return airports, amenities, flights, policies
async def export_data(
self,
) -> tuple[
list[models.Airport],
list[models.Amenity],
list[models.Flight],
list[models.Policy],
]:
loop = asyncio.get_running_loop()
res = await loop.run_in_executor(None, self.export_data_sync)
return res
def get_airport_by_id_sync(self, id: int) -> Optional[models.Airport]:
with self.__pool.connect() as conn:
s = text("""SELECT * FROM airports WHERE id=:id""")
params = {"id": id}
result = (conn.execute(s, params)).mappings().fetchone()
if result is None:
return None
res = models.Airport.model_validate(result)
return res
async def get_airport_by_id(self, id: int) -> Optional[models.Airport]:
loop = asyncio.get_running_loop()
res = await loop.run_in_executor(None, self.get_airport_by_id_sync, id)
return res
def get_airport_by_iata_sync(self, iata: str) -> Optional[models.Airport]:
with self.__pool.connect() as conn:
s = text("""SELECT * FROM airports WHERE LOWER(iata) LIKE LOWER(:iata)""")
params = {"iata": iata}
result = (conn.execute(s, params)).mappings().fetchone()
if result is None:
return None
res = models.Airport.model_validate(result)
return res
async def get_airport_by_iata(self, iata: str) -> Optional[models.Airport]:
loop = asyncio.get_running_loop()
res = await loop.run_in_executor(None, self.get_airport_by_iata_sync, iata)
return res
def search_airports_sync(
self,
country: Optional[str] = None,
city: Optional[str] = None,
name: Optional[str] = None,
) -> list[models.Airport]:
with self.__pool.connect() as conn:
s = text(
"""
SELECT * FROM airports
WHERE (:country IS NULL OR LOWER(country) LIKE CONCAT('%', LOWER(:country), '%'))
AND (:city IS NULL OR LOWER(city) LIKE CONCAT('%', LOWER(:city), '%'))
AND (:name IS NULL OR LOWER(name) LIKE CONCAT('%', LOWER(:name), '%'))
LIMIT 10;
"""
)
params = {
"country": country,
"city": city,
"name": name,
}
results = (conn.execute(s, parameters=params)).mappings().fetchall()
res = [models.Airport.model_validate(r) for r in results]
return res
async def search_airports(
self,
country: Optional[str] = None,
city: Optional[str] = None,
name: Optional[str] = None,
) -> list[models.Airport]:
loop = asyncio.get_running_loop()
res = await loop.run_in_executor(
None, self.search_airports_sync, country, city, name
)
return res
def get_amenity_sync(self, id: int) -> Optional[models.Amenity]:
with self.__pool.connect() as conn:
s = text(
"""
SELECT id, name, description, location, terminal, category, hour
FROM amenities WHERE id=:id
"""
)
params = {"id": id}
result = (conn.execute(s, parameters=params)).mappings().fetchone()
if result is None:
return None
res = models.Amenity.model_validate(result)
return res
async def get_amenity(self, id: int) -> Optional[models.Amenity]:
loop = asyncio.get_running_loop()
res = await loop.run_in_executor(None, self.get_amenity_sync, id)
return res
def amenities_search_sync(
self, query_embedding: list[float], similarity_threshold: float, top_k: int
) -> list[Any]:
with self.__pool.connect() as conn:
s = text(
"""
SELECT name, description, location, terminal, category, hour
FROM amenities
WHERE NEAREST(embedding) TO (string_to_vector(:query), :search_options)
"""
)
params = {
"query": f"{query_embedding}",
"search_options": f"num_neighbors={top_k}",
}
results = (conn.execute(s, parameters=params)).mappings().fetchall()
res = [r for r in results]
return res
async def amenities_search(
self, query_embedding: list[float], similarity_threshold: float, top_k: int
) -> list[Any]:
loop = asyncio.get_running_loop()
res = await loop.run_in_executor(
None,
self.amenities_search_sync,
query_embedding,
similarity_threshold,
top_k,
)
return res
def get_flight_sync(self, flight_id: int) -> Optional[models.Flight]:
with self.__pool.connect() as conn:
s = text(
"""
SELECT * FROM flights
WHERE id = :flight_id
"""
)
params = {"flight_id": flight_id}
result = (conn.execute(s, parameters=params)).mappings().fetchone()
if result is None:
return None
res = models.Flight.model_validate(result)
return res
async def get_flight(self, flight_id: int) -> Optional[models.Flight]:
loop = asyncio.get_running_loop()
res = await loop.run_in_executor(None, self.get_flight_sync, flight_id)
return res
def search_flights_by_number_sync(
self,
airline: str,
number: str,
) -> list[models.Flight]:
with self.__pool.connect() as conn:
s = text(
"""
SELECT * FROM flights
WHERE airline = :airline
AND flight_number = :number
LIMIT 10
"""
)
params = {
"airline": airline,
"number": number,
}
results = (conn.execute(s, parameters=params)).mappings().fetchall()
res = [models.Flight.model_validate(r) for r in results]
return res
async def search_flights_by_number(
self,
airline: str,
number: str,
) -> list[models.Flight]:
loop = asyncio.get_running_loop()
res = await loop.run_in_executor(
None, self.search_flights_by_number_sync, airline, number
)
return res
def search_flights_by_airports_sync(
self,
date: str,
departure_airport: Optional[str] = None,
arrival_airport: Optional[str] = None,
) -> list[models.Flight]:
with self.__pool.connect() as conn:
s = text(
"""
SELECT * FROM flights
WHERE (CAST(:departure_airport AS CHAR(255)) IS NULL OR LOWER(departure_airport) LIKE LOWER(:departure_airport))
AND (CAST(:arrival_airport AS CHAR(255)) IS NULL OR LOWER(arrival_airport) LIKE LOWER(:arrival_airport))
AND departure_time >= CAST(:datetime AS DATETIME)
AND (departure_time < DATE_ADD(CAST(:datetime AS DATETIME), interval 1 day))
LIMIT 10
"""
)
params = {
"departure_airport": departure_airport,
"arrival_airport": arrival_airport,
"datetime": datetime.strptime(date, "%Y-%m-%d"),
}
results = (conn.execute(s, parameters=params)).mappings().fetchall()
res = [models.Flight.model_validate(r) for r in results]
return res
async def search_flights_by_airports(
self,
date: str,
departure_airport: Optional[str] = None,
arrival_airport: Optional[str] = None,
) -> list[models.Flight]:
loop = asyncio.get_running_loop()
res = await loop.run_in_executor(
None,
self.search_flights_by_airports_sync,
date,
departure_airport,
arrival_airport,
)
return res
def validate_ticket_sync(
self,
airline: str,
flight_number: str,
departure_airport: str,
departure_time: str,
) -> Optional[models.Flight]:
with self.__pool.connect() as conn:
s = text(
"""
SELECT * FROM flights
WHERE LOWER(airline) LIKE LOWER(:airline)
AND LOWER(flight_number) LIKE LOWER(:flight_number)
AND LOWER(departure_airport) LIKE LOWER(:departure_airport)
AND departure_time = CAST(:departure_time AS DATETIME)
LIMIT 10
"""
)
params = {
"airline": airline,
"flight_number": flight_number,
"departure_airport": departure_airport,
"departure_time": departure_time,
}
result = (conn.execute(s, parameters=params)).mappings().fetchone()
if result is None:
return None
res = models.Flight.model_validate(result)
return res
async def validate_ticket(
self,
airline: str,
flight_number: str,
departure_airport: str,
departure_time: str,
) -> Optional[models.Flight]:
loop = asyncio.get_running_loop()
res = await loop.run_in_executor(
None,
self.validate_ticket_sync,
airline,
flight_number,
departure_airport,
departure_time,
)
return res
def insert_ticket_sync(
self,
user_id: str,
user_name: str,
user_email: str,
airline: str,
flight_number: str,
departure_airport: str,
arrival_airport: str,
departure_time: str,
arrival_time: str,
):
with self.__pool.connect() as conn:
s = text(
"""
INSERT INTO tickets (
user_id,
user_name,
user_email,
airline,
flight_number,
departure_airport,
arrival_airport,
departure_time,
arrival_time
) VALUES (
:user_id,
:user_name,
:user_email,
:airline,
:flight_number,
:departure_airport,
:arrival_airport,
:departure_time,
:arrival_time
);
"""
)
params = {
"user_id": user_id,
"user_name": user_name,
"user_email": user_email,
"airline": airline,
"flight_number": flight_number,
"departure_airport": departure_airport,
"arrival_airport": arrival_airport,
"departure_time": departure_time,
"arrival_time": arrival_time,
}
conn.execute(s, params).mappings()
async def insert_ticket(
self,
user_id: str,
user_name: str,
user_email: str,
airline: str,
flight_number: str,
departure_airport: str,
arrival_airport: str,
departure_time: str,
arrival_time: str,
):
loop = asyncio.get_running_loop()
await loop.run_in_executor(
None,
self.insert_ticket_sync,
user_id,
user_name,
user_email,
airline,
flight_number,
departure_airport,
arrival_airport,
departure_time,
arrival_time,
)
def list_tickets_sync(
self,
user_id: str,
) -> list[models.Ticket]:
with self.__pool.connect() as conn:
s = text(
"""
SELECT * FROM tickets
WHERE user_id = :user_id
"""
)
params = {
"user_id": user_id,
}
results = (conn.execute(s, parameters=params)).mappings().fetchall()
res = [models.Ticket.model_validate(r) for r in results]
return res
async def list_tickets(
self,
user_id: str,
) -> list[models.Ticket]:
loop = asyncio.get_running_loop()
res = await loop.run_in_executor(None, self.list_tickets_sync, user_id)
return res
def policies_search_sync(
self, query_embedding: list[float], similarity_threshold: float, top_k: int
) -> list[str]:
with self.__pool.connect() as conn:
s = text(
"""
SELECT content
FROM policies
WHERE NEAREST(embedding) TO (string_to_vector(:query), :search_options)
"""
)
params = {
"query": f"{query_embedding}",
"search_options": f"num_neighbors={top_k}",
}
results = (conn.execute(s, parameters=params)).mappings().fetchall()
res = [r["content"] for r in results]
return res
async def policies_search(
self, query_embedding: list[float], similarity_threshold: float, top_k: int
) -> list[str]:
loop = asyncio.get_running_loop()
res = await loop.run_in_executor(
None,
self.policies_search_sync,
query_embedding,
similarity_threshold,
top_k,
)
return res
async def close(self):
self.__pool.dispose()