2016-12-01 27 views
2

我有包含的標籤,如這些數組記錄:案例insesitive Postgres的查詢與數組包含

id | title | tags --------+-----------------------------------------------+---------------------- 124009 | bridge photo | {bridge,photo,Colors} 124018 | Zoom 5 | {Recorder,zoom} 123570 | Sint et | {Reiciendis,praesentium} 119479 | Architecto consectetur | {quia}

我使用下面的SQL查詢來獲取通過標記特定的記錄(「橋」 , '照片', '顏色'):

SELECT "listings".* FROM "listings" WHERE (tags @> ARRAY['bridge', 'photo', 'Colors']::varchar[]) ORDER BY "listings"."id" ASC LIMIT $1 [["LIMIT", 1]]

這將返回第一條記錄在此表中。

這樣做的問題是,我已經混合型的情況下,我想,如果我搜索到返回相同的結果:bridgephotocolors。本質上,我需要使這個搜索不區分大小寫,但是找不到使用Postgres的方法。

這是SQL查詢我已經試過這是引發錯誤: SELECT "listings".* FROM "listings" WHERE (LOWER(tags) @> ARRAY['bridge', 'photo', 'colors']::varchar[]) ORDER BY "listings"."id" ASC LIMIT $1

這是錯誤:

PG::UndefinedFunction: ERROR: function lower(character varying[]) does not exist HINT: No function matches the given name and argument types. You might need to add explicit type casts.

回答

3

您可以將文本轉換數組元素在這樣的方式爲小寫:

select lower(tags::text)::text[] 
from listings; 

      lower   
-------------------------- 
{bridge,photo,colors} 
{recorder,zoom} 
{reiciendis,praesentium} 
{quia} 
(4 rows) 

使用此在您的查詢:

SELECT * 
FROM listings 
WHERE lower(tags::text)::text[] @> ARRAY['bridge', 'photo', 'colors'] 
ORDER BY id ASC; 

    id | title  |   tags   
--------+--------------+----------------------- 
124009 | bridge photo | {bridge,photo,Colors} 
(1 row) 
+0

'lower(tags :: text):: text []'當然可以在所有情況下工作,但是看起來還是很髒的 – pozs

+0

髒?這是一個品味問題。骯髒但很快! ;) – klin

3

你不能直接適用於LOWER()一個數組,但您可以拆開陣列,將其應用到每個元素,並在完成後重新組裝:

... WHERE ARRAY(SELECT LOWER(UNNEST(tags))) @> ARRAY['bridge', 'photo', 'colors'] 

您也可以安裝citext (case-insensitive text) module;如果您聲明listings.tags類型爲citext[],則您的查詢應該按原樣運行。

+0

謝謝尼克,接受對方的回答,因爲它不」 t需要安裝額外的擴展。 – shime