Home >Database >Mysql Tutorial >How to Efficiently Index JSON Arrays in PostgreSQL for Faster Element Retrieval?
Efficiently index JSON arrays in PostgreSQL for faster element retrieval
Quickly identifying and retrieving elements within a JSON array in a PostgreSQL table can be challenging. For optimal performance, it's important to understand the indexing technology that's appropriate for your specific data and query requirements.
Using JSONB in PostgreSQL 9.4
PostgreSQL 9.4 introduces the binary JSON data type jsonb, which greatly enhances indexing possibilities. Use jsonb to create GIN indexes directly on JSON arrays.
<code class="language-sql">CREATE TABLE tracks (id serial, artists jsonb); CREATE INDEX tracks_artists_gin_idx ON tracks USING gin (artists);</code>
This enables queries that can use GIN indexes, for example:
<code class="language-sql">SELECT * FROM tracks WHERE artists @> '["The Dirty Heads"]';</code>
where @>
represents the "contains" operator of jsonb.
Alternatively, you can use the jsonb_path_ops GIN operator class (non-default, usually smaller and faster):
<code class="language-sql">CREATE INDEX tracks_artists_gin_idx ON tracks USING gin (artists jsonb_path_ops);</code>
Optimize for unique name values
If your artists
column only contains an array of uniquely named values, it is more efficient to store the values as JSON text primitives, rather than objects. This eliminates the need for redundant keys.
<code class="language-sql">CREATE TABLE tracks (id serial, artistnames jsonb); INSERT INTO tracks VALUES (2, '["The Dirty Heads", "Louis Richards"]'); CREATE INDEX tracks_artistnames_gin_idx ON tracks USING gin (artistnames);</code>
Query example:
<code class="language-sql">SELECT * FROM tracks WHERE artistnames ? 'The Dirty Heads'; SELECT * FROM tracks WHERE artistnames @> '"The Dirty Heads"'::jsonb;</code>
Handling json in PostgreSQL 9.3
For PostgreSQL versions prior to 9.4, invariant functions and GIN indexes can be used.
Create function:
<code class="language-sql">CREATE OR REPLACE FUNCTION json2arr(_j json, _key text) RETURNS text[] LANGUAGE sql IMMUTABLE AS 'SELECT ARRAY(SELECT elem->>_key FROM json_array_elements(_j) elem)';</code>
Then create the function index:
<code class="language-sql">CREATE INDEX tracks_artists_gin_idx ON tracks USING gin (json2arr(artists, 'name'));</code>
Use a query that matches the index expression:
<code class="language-sql">SELECT * FROM tracks WHERE '{"The Dirty Heads"}'::text[]</code>
Always ensure that the functions used in the index are immutable to enable function indexing. Key operators...
The article has rewritten the original text, using more concise language, and adjusted some sentences, but retains the core content of the original text and the location of the pictures.
The above is the detailed content of How to Efficiently Index JSON Arrays in PostgreSQL for Faster Element Retrieval?. For more information, please follow other related articles on the PHP Chinese website!