@@ -16,36 +16,20 @@ def __init__(self, session: SyncSession):
1616 def find_similar_query (self , query_embedding : List [float ]) -> CachedQuery | None :
1717 """
1818 Finds a cached query if its embedding is within the similarity threshold.
19- This is done in a single, efficient query.
19+ This is done in a single, efficient query using the ORM .
2020 """
2121
2222 distance_threshold = 1 - SIMILARITY_THRESHOLD
2323
24- stmt = text ( """
25- SELECT id
26- FROM cached_queries
27- WHERE ( question_embedding <=> CAST(: query_embedding AS vector)) < : distance_threshold
28- ORDER BY question_embedding <=> CAST(:query_embedding AS vector)
29- LIMIT 1
30- """ )
24+ stmt = select ( CachedQuery ). options (
25+ selectinload ( CachedQuery . source_chunks )
26+ ). where (
27+ CachedQuery . question_embedding . cosine_distance ( query_embedding ) < distance_threshold
28+ ). order_by (
29+ CachedQuery . question_embedding . cosine_distance ( query_embedding )
30+ ). limit ( 1 )
3131
32- result = self .session .execute (
33- stmt ,
34- {
35- "query_embedding" : query_embedding ,
36- "distance_threshold" : distance_threshold
37- }
38- ).scalar_one_or_none ()
39-
40- if result :
41- similar_query_id = result
42- final_stmt = select (CachedQuery ).options (
43- selectinload (CachedQuery .source_chunks )
44- ).where (CachedQuery .id == similar_query_id )
45-
46- return self .session .execute (final_stmt ).scalar_one_or_none ()
47-
48- return None
32+ return self .session .execute (stmt ).scalar_one_or_none ()
4933
5034 def save_query (self , question_text : str , query_embedding : list [float ], answer : str , source_chunks : list [Chunk ]):
5135 """Saves a new query and links it to its source chunks."""
0 commit comments