简体   繁体   English

使用 SQL 删除 postgres 中 jsonb 列中的长键值对

[英]Remove long key value pairs in jsonb column in postgres with SQL

I am using a materialized view to merge an query 3 json columns because I want to query all of them together with 1 GIN index.我正在使用物化视图来合并查询 3 json 列,因为我想查询所有这些列以及 1 GIN 索引。 The view looks similar to this:该视图类似于以下内容:

CREATE MATERIALIZED VIEW IF NOT EXISTS test_materialized_view AS
SELECT t1.id, (t1.data1 || t1.data2 || COALESCE(t2.data1, '{}'::jsonb)) "data"
FROM table_1 t1 LEFT JOIN table_2 t2 ON (...);

Now it can happen that there are longer key value pairs in the json data which I never want to query and which can be stored 1000 of times because they are in t2.data1.现在可能发生在 json 数据中有更长的键值对,我不想查询这些键值对,因为它们在 t2.data1 中,所以可以存储 1000 次。 Is it possible to filter the merged json and only include key value pairs with a length less than x characters?是否可以过滤合并的 json 并且仅包含长度小于 x 个字符的键值对? Does this even make a difference / reduce saved data?这甚至会产生影响/减少保存的数据吗?

I dont know the json keys of these fields.我不知道这些字段的 json 键。 I basically just want to remove all key value pairs which are longer than x characters or array / nested objects but did not really find a good way to do this in postgres我基本上只是想删除所有长于 x 字符或数组/嵌套对象的键值对,但在 postgres 中并没有真正找到这样做的好方法

There is no built-in function for this.为此没有内置的 function。 You will need to write your own.您将需要自己编写。

Something along the lines:类似的东西:

create function remove_long_values(p_input jsonb, p_maxlen int)
  returns jsonb
as
$$
  select coalesce(jsonb_object_agg(e.ky, e.val), '{}')
  from jsonb_each(p_input) as e(ky,val) 
  where length(e.val::text) <= p_maxlen;
$$
language sql
immutable
parallel safe;

The above does not deal with nested key/value pairs.以上处理嵌套的键/值对。 It only checks this on the first level.它只在第一级检查。

Then use it in the query:然后在查询中使用它:

CREATE MATERIALIZED VIEW IF NOT EXISTS test_materialized_view 
AS
SELECT t1.id, t1.data1 || t1.data2 || remove_long_values(t2.data1,250) as "data"
FROM table_1 t1 
  LEFT JOIN table_2 t2 ON (...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM