是否可以即时将文本列转换为 json 然后在 postgres 中对其进行查询?
Is it possible to convert text column to json on the fly then query against it in postgres?
我必须使用文本列,但其内容是 json 格式。一个例子:
{"company":"company name","entityName":"entity name","asOfDate":1604725200000}
现在,我正在使用 LIKE 来获得我想要的结果:
select distinct a.company_name from company_table a
where a.json_field LIKE '%' || ?1 || '%'
我希望能够直接查询 json:
select distinct a.company_name from company_table a
where a.json_field ->> company = ?1
第三种选择是获取所有行,然后使用代码解析它们,我相当确定 table 的增长很低,不会达到 10k/年。
虽然 LIKE 方法有效,但我不知道它是否 100% 正确。
有什么建议吗?
就cast
吧:
where (a.json_field::jsonb) ->> company = ?1
如果您的字符串无效,这将出错 JSON。
我建议修复您的架构,并将该列一劳永逸地转换为 JSON,这样您就不必再为此担心了。您可以在一条语句中执行此操作:
alter table company_table
alter column json_field type jsonb
using json_field::jsonb;
我必须使用文本列,但其内容是 json 格式。一个例子:
{"company":"company name","entityName":"entity name","asOfDate":1604725200000}
现在,我正在使用 LIKE 来获得我想要的结果:
select distinct a.company_name from company_table a
where a.json_field LIKE '%' || ?1 || '%'
我希望能够直接查询 json:
select distinct a.company_name from company_table a
where a.json_field ->> company = ?1
第三种选择是获取所有行,然后使用代码解析它们,我相当确定 table 的增长很低,不会达到 10k/年。
虽然 LIKE 方法有效,但我不知道它是否 100% 正确。
有什么建议吗?
就cast
吧:
where (a.json_field::jsonb) ->> company = ?1
如果您的字符串无效,这将出错 JSON。
我建议修复您的架构,并将该列一劳永逸地转换为 JSON,这样您就不必再为此担心了。您可以在一条语句中执行此操作:
alter table company_table
alter column json_field type jsonb
using json_field::jsonb;