PostgreSQL provides powerful functions for working with JSONB data, a binary representation of JSON data. JSONB functions enable querying, manipulation, and transformation of JSONB data within PostgreSQL. Here's an exploration of some commonly used PostgreSQL JSONB functions:
1. JSONB Creation:
- jsonb_build_object: Creates a JSONB object from key-value pairs.
SELECT jsonb_build_object('name', 'John', 'age', 30);
- jsonb_build_array: Creates a JSONB array from values.
SELECT jsonb_build_array('apple', 'banana', 'orange');
2. JSONB Accessors:
- ->: Gets the value of a specified key in a JSONB object.
SELECT '{"name": "John", "age": 30}'->'name';
- ->>: Gets the value of a specified key in a JSONB object as text.
SELECT '{"name": "John", "age": 30}'->>'name';
3. JSONB Manipulation:
- jsonb_set: Sets a value at a specified path within a JSONB object.
SELECT jsonb_set('{"name": "John", "age": 30}'::jsonb, '{name}', '"David"');
- jsonb_delete: Deletes a key or keys from a JSONB object.
SELECT jsonb_delete('{"name": "John", "age": 30}'::jsonb, '{name}');
4. JSONB Aggregation:
- jsonb_object_agg: Aggregates key-value pairs into a JSONB object.
SELECT jsonb_object_agg(key, value) FROM (VALUES ('name', 'John'), ('age', 30)) AS data(key, value);
5. JSONB Querying:
- jsonb_path_query: Executes a path query against a JSONB value.
SELECT jsonb_path_query('{"person": {"name": "John", "age": 30}}', '$.person');
- jsonb_path_query_array: Executes a path query against a JSONB array.
SELECT jsonb_path_query_array('[{"name": "John"}, {"name": "David"}]', '$[*].name');
6. JSONB Indexing:
- GIN Indexes: PostgreSQL supports GIN (Generalized Inverted Index) indexes for efficient querying of JSONB data.
CREATE INDEX idx_data ON my_table USING GIN (data);
PostgreSQL JSONB functions provide a wide range of capabilities for working with JSONB data. Whether you need to create JSONB objects, access specific keys, manipulate JSONB data, aggregate values, or query JSONB documents, PostgreSQL offers a rich set of functions to meet your requirements. Experiment with these functions to leverage the flexibility and power of JSONB data in PostgreSQL.
No comments:
Post a Comment