I am trying to make a function in Postgres to make my queries faster compared to Django ORM. But the problem I am facing is results are coming when there is no WHERE
clause in the query.
This is the function and its call which yields 0 rows:
CREATE OR REPLACE FUNCTION public.standard_search(search_term text, similarity_to integer)
RETURNS TABLE(obj_id integer, app_num integer, app_for text, similarity integer)
LANGUAGE 'plpgsql'
AS $BODY$
DECLARE
similarity integer;
BEGIN
RETURN QUERY
SELECT mark.id, mark.app_num, mark.app_for::text, levenshtein($1, focusword.word) AS similarity
FROM mark
INNER JOIN focusword ON (mark.id = focusword.mark_id)
WHERE similarity <= $2
ORDER BY similarity, mark.app_for, mark.app_num;
END
$BODY$;
select * from public.standard_search('millennium', 4)
This is the function and its call which is giving me results but is slow as the filtering is done in the function call:
CREATE OR REPLACE FUNCTION public.standard_search(search_term text, similarity_to integer)
RETURNS TABLE(obj_id integer, app_num integer, app_for text, similarity integer)
LANGUAGE 'plpgsql'
AS $BODY$
DECLARE
similarity integer;
BEGIN
RETURN QUERY
SELECT mark.id, mark.app_num, mark.app_for::text, levenshtein($1, focusword.word) AS similarity
FROM mark
INNER JOIN focusword ON (mark.id = focusword.trademark_id)
ORDER BY similarity, trad.app_for, mark.app_num;
END
$BODY$;
select * from public.standard_search('millennium', 4) where similarity <= 4
Can anyone shed some light on what is actually going wrong here? After this I can work on the performance improvements.
I was unable to perform this via VIEWS as it required at least one parameter, i.e., search_term
to be passed into the levenshtein()
function.
I was also facing a problem of passing a tuple
as a parameter in the function which is again to be used in the where clause like:
WHERE mark.class in (1,2,3,4,5)
I was doing this previously via RawSQL feature of Django ORM, but trying to do it here because of the performance improvement gains.