Repository navigation
Expand file tree
/
Copy pathfix_final.sql
More file actions
90 lines (84 loc) · 2.76 KB
/
Copy pathfix_final.sql
File metadata and controls
90 lines (84 loc) · 2.76 KB
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
-- Final comprehensive fix for the search_similar_chunks RPC function
-- The issue might be with vector dimensions or similarity calculation
-- First, let's check the current function and recreate it properly
DROP FUNCTION IF EXISTS search_similar_chunks(vector, int, float, uuid);
DROP FUNCTION IF EXISTS search_similar_chunks(vector, int, float);
-- Get the actual embedding dimension from existing data
-- Most OpenAI embeddings are 1536 dimensions
-- But let's be flexible and not hardcode the dimension
CREATE OR REPLACE FUNCTION search_similar_chunks(
query_embedding vector,
match_count int DEFAULT 10,
min_similarity float DEFAULT 0.0,
p_user_id uuid DEFAULT NULL
)
RETURNS TABLE (
chunk_id text,
content text,
source_document_id text,
source_title text,
source_url text,
chunk_index int,
start_char int,
end_char int,
metadata jsonb,
created_at timestamptz,
user_id uuid,
distance float
)
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
BEGIN
-- Debug: Check if we have any data at all
RAISE NOTICE 'Function called with user_id: %, match_count: %', p_user_id, match_count;
-- Return all matching chunks with similarity calculation
RETURN QUERY
SELECT
dc.chunk_id,
dc.content,
dc.source_document_id,
rd.title AS source_title,
rd.url AS source_url,
dc.chunk_index,
dc.start_char,
dc.end_char,
dc.metadata,
dc.created_at,
dc.user_id,
CASE
WHEN vector_dims(e.vector) = vector_dims(query_embedding) THEN
(1 - (e.vector <=> query_embedding))::float
ELSE
0.0::float
END AS distance
FROM document_chunks dc
JOIN embeddings e ON dc.chunk_id = e.chunk_id
JOIN raw_documents rd ON dc.source_document_id = rd.page_id
WHERE
(p_user_id IS NULL OR dc.user_id = p_user_id)
AND (
vector_dims(e.vector) != vector_dims(query_embedding) OR
(1 - (e.vector <=> query_embedding)) >= min_similarity
)
ORDER BY
CASE
WHEN vector_dims(e.vector) = vector_dims(query_embedding) THEN
e.vector <=> query_embedding
ELSE
1.0
END
LIMIT match_count;
END;
$$;
-- Grant execute permissions
GRANT EXECUTE ON FUNCTION search_similar_chunks TO authenticated;
GRANT EXECUTE ON FUNCTION search_similar_chunks TO anon;
GRANT EXECUTE ON FUNCTION search_similar_chunks TO service_role;
-- Test the function with a simple call
SELECT search_similar_chunks(
ARRAY[0.0]::vector, -- Single dimension vector for testing
5, -- match_count
0.0, -- min_similarity
'63fa38b9-8daf-4a39-908d-6c498b8cd8ca'::uuid -- user_id
);