Skip to content

Instantly share code, notes, and snippets.

@pirosuke
Created August 23, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pirosuke/c4785f30b60b1edf133d to your computer and use it in GitHub Desktop.
Save pirosuke/c4785f30b60b1edf133d to your computer and use it in GitHub Desktop.
Function for checking list similarities on PostgreSQL
CREATE OR REPLACE FUNCTION SF_GET_LIST_SIMILARITY(
p_list1 text[],
p_list2 text[]
) RETURNS NUMERIC(19,4) AS $$
DECLARE
w_list text[] := '{}';
BEGIN
IF p_list1 IS NULL OR p_list2 IS NULL THEN
RETURN 0;
END IF;
IF array_length(p_list1, 1) = 0 OR array_length(p_list2, 1) = 0 THEN
RETURN 0;
END IF;
FOR i IN 1..array_length(p_list1, 1) LOOP
IF p_list1[i] = ANY(p_list2) THEN
w_list := array_append(w_list, p_list1[i]);
END IF;
END LOOP;
RETURN array_length(w_list, 1)::numeric(19,4) / array_length(p_list1, 1)::numeric(19,4);
END;
$$ LANGUAGE plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment