PostgreSQLで配列型の検索


タグ機能を実装する際に、PostgreSQLの配列型を利用し検索に躓いたのでメモです。
配列型について

検索する項目が1つならANYを使えばなんとでもなりますが、複数検索したい場合どうしたらいいんだ?
と思ったのでまとめてみました。

まず適当にテーブルを用意します。

CREATE TABLE tb_news(
    id bigserial NOT NULL PRIMARY KEY,
    news_datetime timestamp without time zone,
    title text,
    comment text,
    tags text[], -- タグ
    delete_flag BOOLEAN NOT NULL DEFAULT FALSE,
    created timestamp without time zone DEFAULT now() NOT NULL,
    modified timestamp without time zone
);
INSERT INTO tb_news(news_datetime, title, comment, tags)
VALUES (now(), 'hogehoge', 'comment', '{1,2}');

これで用意ができたので実際に問い合わせしてみます。
配列関数と演算子
今回試したのは、重複する項目です。

SELECT * FROM tb_news_test WHERE tags && ARRAY[1,2];

何も考えずに問い合わせすると、エラーになります。

HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.

textの配列型なのにint型で問い合わせしているのでそりゃ怒られます。
キャストして上げる必要があります。

SELECT * FROM tb_news_test WHERE tags && ARRAY[1,2]::text[];

これで、無事取得出来ました。


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>