I'm new to postgres and I am having trouble finding an example of how to query the following:
{
"Skill": {
"Technical": [
{ "Name": "C#",
"Rating": 4,
"Last Used": "2014-08-21"
},
{ "Name": "ruby",
"Rating": 4,
"Last Used": "2014-08-21"
}
],
"Product": [
{ "Name": "MDM",
"Rating": 4,
"Last Used": "2014-08-21"
},
{ "Name": "UDM",
"Rating": 5,
"Last Used": "2014-08-21"
}
]
}
}
In short I struggling with understanding how to query through maps without having to be explicit about naming each key.
I have a query that does the following, though it seems a bit much to have to do...
Select 'Technical' as SkillType
, json_array_elements(ResourceDocument->'Skill'->'Technical')->>'Name' as SkillName
, json_array_elements(ResourceDocument->'Skill'->'Technical')->>'Rating' as Rating
, json_array_elements(ResourceDocument->'Skill'->'Technical')->>'Last Used' as LastUsed
FROM testdepot.Resource
UNION ALL
Select 'Product' as SkillType
, json_array_elements(ResourceDocument->'Skill'->'Product')->>'Name' as SkillName
, json_array_elements(ResourceDocument->'Skill'->'Product')->>'Rating' as Rating
, json_array_elements(ResourceDocument->'Skill'->'Product')->>'Last Used' as LastUsed
FROM testdepot.Resource
I am trying to find a way to do this in 1 query that allows containing all keys of a map. In this case Product and Technical Something like:
Select 'Product' as SkillType
, json_array_elements(ResourceDocument->'Skill'->*)->>'Name' as SkillName
, json_array_elements(ResourceDocument->'Skill'->*)->>'Rating' as Rating
, json_array_elements(ResourceDocument->'Skill'->*)->>'Last Used' as LastUsed
FROM testdepot.Resource
You can wrap a call to json_object_keys
in a sub-query to first get the keys inside "Skill"
and then use json_array_elements
on the outer query over the result:
SELECT SkillType
, json_array_elements(ResourceDocument->'Skill'->SkillType)->>'Name' AS SkillName
, json_array_elements(ResourceDocument->'Skill'->SkillType)->>'Rating' AS Rating
, json_array_elements(ResourceDocument->'Skill'->SkillType)->>'Last Used' AS LastUsed
FROM (
SELECT json_object_keys(resourcedocument->'Skill') AS SkillType, ResourceDocument
FROM Resource
) t;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.