简体   繁体   English

SQL:如何在 jsonb 中找到最常见的键值对?

[英]SQL: How to find most common key-value pair in a jsonb?

Given a table where one of the columns has type jsonb, how does one find the most common key-value pairs among all records in that column?给定其中一列的类型为 jsonb 的表,如何在该列的所有记录中找到最常见的键值对?

The dict is only one level deep.字典只有一层深。

If your json has only one level is ease, here is a test code:如果你的json只有一个级别是easy,这里是一个测试代码:

-- Test Table:
CREATE TEMP TABLE test (id serial,data jsonb);
-- Test Data
INSERT INTO test(data) VALUES
('{"a":{"a1":{"a2":1}},"b":2,"c":3}'::jsonb),
('{"a":1,"b":2,"c":3}'::jsonb),
('{"a":1}'::jsonb);

To get all keys, there is a function called jsonb_object_keys but only gets the set of keys in the outermost JSON object.要获取所有键,有一个名为jsonb_object_keys的函数,但只获取最外层 JSON 对象中的键集。 So the query to get all the keys is:所以获取所有键的查询是:

SELECT DISTINCT key, COUNT(*) OVER(partition by key)
FROM
(SELECT jsonb_object_keys(data) AS key  FROM test)keys;

The result is:结果是:

key | count
----+-------
c   | 2
b   | 2
a   | 3

From that result you can get which key is the most used.从该结果中,您可以得到最常用的键。 f you want to get pairs... you just have to tweak a little this query... It would be better if you give an example data.如果你想得到对......你只需要稍微调整一下这个查询......如果你给出一个示例数据会更好。

If you want to get the keys from a nested json... That's harder.如果你想从嵌套的 json 中获取密钥......那就更难了。 You would have to create a PL code that recursively goes through the JSON to get witch keys are more used.您必须创建一个 PL 代码,该代码递归地遍历 JSON 以获得更多使用的女巫键。

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

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