首页 文章

在sequelize where子句中使用ILIKE(JSON列)

提问于
浏览
0

我有JSON列,我存储的数据如下 -

{ tag : ["as","bs","cs"] }

我想用 ILIKE 在这个列中搜索,我相信JSON数据类型只是字符串所以我使用的查询像 -

SELECT * FROM public."Transactions" WHERE tags::text ILIKE '%as%'

上面的查询在sql中工作正常

我需要使用sequelize model with no success code 来实现这个我使用的是

let searchQuery = [
        {
            payee: {
                [Op.iLike]: '%' + search + '%'
            }
        },
        {
            tags: {
                [Op.iLike]: '%as%'
            }
        }
    ];

gives error as

未处理的拒绝SequelizeDatabaseError:运算符不存在:json ~~ * unknown

1 回答

  • 1

    https://www.postgresql.org/docs/current/static/functions-json.html

    检查运算符列表 - 没有 ~~ - ILIKE 不适用于json . 您必须将json转换为文本:

    t=# select '{ "tag" : ["as","bs","cs"] }'::json::text ilike '%as%';
     ?column?
    ----------
     t
    (1 row)
    

    或使用本机运营商:

    t=# select ('{ "tag" : ["as","bs","cs"] }'::json)->'tag'->>0 = 'as';
     ?column?
    ----------
     t
    (1 row)
    

    或者如果你是9.5及以上 - 强制转换为jsonb并使用其强大的运算符:

    t=# select '{ "tag" : ["as","bs","cs"] }'::json::jsonb @> '{"tag":["as"]}'::jsonb;
     ?column?
    ----------
     t
    (1 row)
    

    https://www.postgresql.org/docs/current/static/functions-json.html

相关问题