2016-07-26 78 views
0

我希望在我的應用程序中使用搜索功能。如何在postgresql中創建n-gram

我用trigram實現它,它工作正常。

問題是:

巽是創建3字符組的字的序列。 我想在單個對象中有3個以上的字符。 例如:

select show_trgm('abcpqrs'); 

這將返回:{" a"," ab","abc","bcp","cpq","pqr","qrs","rs "}

我想{" a"," ab","abc","bcp","cpq","pqr","qrs","rs ","abcd","bcpq","cpqr"...}

我怎樣才能做到這一點?

+0

您可以創建一個用戶定義的函數來執行此操作。 –

+0

感謝您的回覆,我一定會試試這個。 –

回答

1

試試這個功能。

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; 

我的測試結果。

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) 
+0

謝謝你的回覆,我會試試這個。 –

相關問題