sql >> Database teknologi >  >> RDS >> PostgreSQL

Sådan opretter du n-gram i postgresql

Prøv denne funktion.

CREATE OR REPLACE FUNCTION myngram(mystr TEXT, n INT) RETURNS TEXT[]
AS $$
DECLARE
str VARCHAR;
arr TEXT[];
BEGIN

  str := lpad(mystr, n - 1 + char_length(mystr), ' ');
  str := rpad(str, n - 1 + char_length(str), ' ');

  arr := array[]::TEXT[];
  FOR i IN 1 .. char_length(str) - n + 1 LOOP
    arr := arr || substring(str from i for n);
  END LOOP;
  RETURN arr;
END
$$
LANGUAGE plpgsql;

Resultater fra min test.

testdb=# SELECT myngram('abcpqrs', 4);
                             myngram                             
-----------------------------------------------------------------
 {"   a","  ab"," abc",abcp,bcpq,cpqr,pqrs,"qrs ","rs  ","s   "}
(1 row)

testdb=# SELECT myngram('abcpqrs', 5);
                                       myngram                                       
-------------------------------------------------------------------------------------
 {"    a","   ab","  abc"," abcp",abcpq,bcpqr,cpqrs,"pqrs ","qrs  ","rs   ","s    "}
(1 row)



  1. ROWIDTONCHAR() Funktion i Oracle

  2. PL/SQL Hvordan returnerer alle attributter i ROW

  3. SELECT-forespørgsel med bogstavelige tegn (kolon, semikolon) i Oracle

  4. Er det muligt at definere globale variabler i postgresql