Using JSONB in PostgreSQL: How to Effectively Store & Index JSON Data in PostgreSQL
Tags: postgres, json, sql, database
Published: 2020-07-17 20:13:50

---
title: Using JSONB in PostgreSQL: How to Effectively Store & Index JSON Data in PostgreSQL
published: true
description: In this post, we show you tips and techniques on how to effectively store and index JSON data in PostgreSQL. Learn more about JSONB PostgreSQL - ScaleGrid Blog
tags: PostgreSQL, JSON, SQL, Database,
//cover_image: https://scalegrid.io/blog/wp-content/uploads/2020/07/Using-JSONB-in-PostgreSQL-How-to-Effectively-Store-and-Index-JSON-Data-in-PostgreSQL-ScaleGrid-Blog.jpg
---
<link rel="canonical" href="https://scalegrid.io/blog/using-jsonb-in-postgresql-how-to-effectively-store-index-json-data-in-postgresql/" />
<a href="https://scalegrid.io/blog/using-jsonb-in-postgresql-how-to-effectively-store-index-json-data-in-postgresql/"><img src="https://scalegrid.io/blog/wp-content/uploads/2020/07/Using-JSONB-in-PostgreSQL-How-to-Effectively-Store-and-Index-JSON-Data-in-PostgreSQL-ScaleGrid-Blog.jpg" width="100%" height="auto"></a>
<p style="text-align: justify; padding-bottom: 15px;">JSON stands for JavaScript Object Notation. It is an open standard format which organizes data into key/value pairs and arrays detailed in <a style="color: #2da964;" href="https://tools.ietf.org/html/rfc7159" target="_blank">RFC 7159</a>. JSON is the most common format used by web services to exchange data, store documents, unstructured data, etc. In this post, we are going to show you tips and techniques on how to <a style="color: #2da964;" href="https://scalegrid.io/blog/using-jsonb-in-postgresql-how-to-effectively-store-index-json-data-in-postgresql/" target="_blank">effectively store and index JSON data in PostgreSQL</a>.</p>
<a href="https://scalegrid.io/blog/using-jsonb-in-postgresql-how-to-effectively-store-index-json-data-in-postgresql/" target="_blank"><img class="alignleft size-large wp-image-5657" src="https://scalegrid.io/blog/wp-content/uploads/2020/07/json-popularity-1024x604.jpg" alt="json popularity" width="100%" height="auto" /></a>
<p style="text-align: justify; padding: 20px;">You can also check out our <a style="color: #2da964;" href="https://postgresconf.org/conferences/postgres-webinar-series/program/proposals/working-with-json-data-in-postgresql-vs-mongodb-b32a65a2-1ffa-4e30-8423-7244d6ab8f8d" target="_blank">Working with JSON Data in PostgreSQL vs. MongoDB</a> webinar in partnership with PostgresConf to learn more on the topic, and check out our SlideShare page to <a style="color: #2da964;" href="https://www.slideshare.net/ScaleGrid/working-with-json-data-in-postgresql-vs-mongodb" target="_blank">download the slides</a>.

<table style="border:solid 20px #def5fe;" width="100%">
<tbody>
<tr>
<th style="padding: 20px 30px 20px 30px;">
<h2 style="padding-bottom:10px;">What's in this article?</h2>
<ul>
	<li style="padding-bottom:10px;"><a style="color: #2da964; text-decoration: underline;" href="https://scalegrid.io/blog/using-jsonb-in-postgresql-how-to-effectively-store-index-json-data-in-postgresql/#1">Why Store JSON in PostgreSQL?</a></li>
	<li style="padding-bottom:10px;"><a style="color: #2da964; text-decoration: underline;" href="https://scalegrid.io/blog/using-jsonb-in-postgresql-how-to-effectively-store-index-json-data-in-postgresql/#2">Timeline of JSON Support in PostgreSQL</li>
	<li style="padding-bottom:10px;"><a style="color: #2da964; text-decoration: underline;" href="https://scalegrid.io/blog/using-jsonb-in-postgresql-how-to-effectively-store-index-json-data-in-postgresql/#3">JSONB Patterns &amp; Antipatterns</li>
	<li style="padding-bottom:10px;"><a style="color: #2da964; text-decoration: underline;" href="https://scalegrid.io/blog/using-jsonb-in-postgresql-how-to-effectively-store-index-json-data-in-postgresql/#4">JSONB Data Structures</li>
	<li style="padding-bottom:10px;"><a style="color: #2da964; text-decoration: underline;" href="https://scalegrid.io/blog/using-jsonb-in-postgresql-how-to-effectively-store-index-json-data-in-postgresql/#5">JSONB Operators &amp; Functions</li>
	<li style="padding-bottom:10px;"><a style="color: #2da964; text-decoration: underline;" href="https://scalegrid.io/blog/using-jsonb-in-postgresql-how-to-effectively-store-index-json-data-in-postgresql/#6">JSONB Indexes</li>
	<li style="padding-bottom:10px;"><a style="color: #2da964; text-decoration: underline;" href="https://scalegrid.io/blog/using-jsonb-in-postgresql-how-to-effectively-store-index-json-data-in-postgresql/#7">SQL/JSON &amp; JSONPath</li>
</ul>
</th>
</tr>
</tbody>
</table>



<h2 style="padding-top: 20px;"><a id="1"></a>Why Store JSON in PostgreSQL?</h2>
<p style="text-align: justify; padding-bottom: 10px;">Why should a relational database even care about unstructured data? It turns out that there are a few scenarios where it is useful.</p>

<ol>
	<li style="text-align: justify; padding-bottom: 5px;">
<h4>Schema flexibility</h4>
One of the main reasons to store data using the JSON format is schema flexibility. Storing your data in JSON is useful when your schema is fluid and is changing frequently. If you store each of the keys as columns, it will result in frequent DML operations - this can be difficult when your data set is large - for example, event tracking, analytics, tags, etc. Note: If a particular key is always present in your document, it might make sense to store it as a first class column. We discuss more about this approach in section "JSON Patterns &amp; Antipatterns" below.</li>
	<li style="text-align: justify; padding-bottom: 5px;">
<h4>Nested objects</h4>
If your data set has nested objects (single or multi-level), in some cases, it is easier to handle them in JSON instead of denormalizing the data into columns or multiple tables.</li>
	<li style="text-align: justify;">
<h4>Syncing with external data sources</h4>
Often times an external system is providing data as JSON, so it might be a temporary store before data is ingested into other parts of the system. For example, Stripe transactions.</li>
</ol>
<h2 style="padding-top: 15px;"><a id="2"></a>Timeline of JSON Support in PostgreSQL</h2>
<p style="text-align: justify; padding-bottom: 10px;">JSON support in <a style="color: #2da964;" href="https://scalegrid.io/postgresql.html" target="blank">PostgreSQL</a> was introduced in 9.2 and has steadily improved in every release going forward.</p>

<ul>
	<li style="text-align: justify; padding-bottom: 5px;">
<h4>Wave 1: PostgreSQL 9.2  (2012) added support for JSON data type</h4>
JSON database in 9.2 was fairly limited (and probably overhyped at that point) - basically a glorified string with some JSON validation thrown in. It is useful to validate incoming JSON and store in the database. More details are provided below.</li>
	<li style="text-align: justify; padding-bottom: 5px;">
<h4>Wave 2: PostgreSQL 9.4 (2014) added support for JSONB data type</h4>
JSONB stands for "JSON Binary" or "JSON better" depending on whom you ask. It is a decomposed binary format to store JSON. JSONB supports indexing the JSON data, and is very efficient at parsing and querying the JSON data. In most cases, when you work with JSON in PostgreSQL, you should be using JSONB.</li>
	<li style="text-align: justify; padding-bottom: 10px;">
<h4>Wave 3: PostgreSQL 12 (2019) added support for SQL/JSON standard and JSONPATH queries</h4>
JSONPath brings a powerful JSON query engine to PostgreSQL.</li>
</ul>
<a href="https://scalegrid.io/blog/using-jsonb-in-postgresql-how-to-effectively-store-index-json-data-in-postgresql/" target="blank"><img class="alignnone size-full wp-image-5707" src="https://scalegrid.io/blog/wp-content/uploads/2020/07/PostgreSQL-Version-Timeline-JSON-Support.jpg" alt="PostgreSQL Version Timeline for JSON Support - ScaleGrid Blog" width="100%" height="auto" /></a>
<h3 style="padding-top: 10px;">When Should You Use JSON vs. JSONB?</h3>
<p style="text-align: justify; padding-bottom: 10px;">In most cases, JSONB is what you should be using. However, there are some specific cases where JSON works better:</p>

<ul>
	<li style="text-align: justify; padding-bottom: 5px;">JSON preserves the original formatting (a.k.a whitespace) and ordering of the keys.</li>
	<li style="text-align: justify; padding-bottom: 5px;">JSON preserves duplicate keys.</li>
	<li style="text-align: justify;">JSON is faster to ingest vs. JSONB - however, if you do any further processing, JSONB will be faster.</li>
</ul>
<p style="text-align: justify;">For example, if you're just ingesting JSON logs and not querying them in any way, then JSON might be a better option for you. For the purposes of this blog, when we refer to JSON support in PostgreSQL, we will refer to JSONB going forward.</p>

<h2 style="padding-top: 15px;"><a id="3"></a>JSONB Patterns &amp; Antipatterns</h2>
<p style="text-align: justify; padding-bottom: 10px;">If PostgreSQL has great support for JSONB, why do we need columns anymore? Why not just create a table with a JSONB blob and get rid of all columns like the schema below:</p>


<pre><code>CREATE TABLE test(id int, data JSONB, PRIMARY KEY (id));</code></pre>

<p style="text-align: justify; padding: 10px 0px;">At the end of the day, columns are still the most efficient technique to work with your data. JSONB storage has some drawbacks vs. traditional columns:</p>

<ul style="text-align: justify;">
	<li style="padding-bottom: 5px;">
<h4>PostreSQL does not store column statistics for JSONB columns</h4>
PostgreSQL maintains statistics about the distributions of values in each column of the table - most common values (MCV), NULL entries, histogram of distribution. Based on this data, the PostgreSQL query planner makes smart decisions on the plan to use for the query. At this point, PostgreSQL does not store any stats for JSONB columns or keys. This can sometimes result in poor choices like using nested loop joins vs. hash joins, etc. A more detailed example of this is provided in this blog post - <a style="color: #2da964;" href="https://heap.io/blog/engineering/when-to-avoid-jsonb-in-a-postgresql-schema" target="_blank">When To Avoid JSONB In A PostgreSQL Schema</a>.</li>
	<li style="padding-bottom: 5px;">
<h4>JSONB storage results in a larger storage footprint</h4>
JSONB storage does not deduplicate the key names in the JSON. This can result in considerably larger storage footprint compared to MongoDB BSON on WiredTiger or traditional column storage. I ran a simple test with the below JSONB model storing about 10 million rows of data, and here are the results - In some ways this is similar to the MongoDB MMAPV1 storage model where the keys in JSONB were stored as-is without any compression. One long-term fix is to move the key names to a table level dictionary and refer this dictionary instead of storing the key names repeatedly. Until then, the workaround might be to use more compact names (unix-style) instead of more descriptive names. For example, if you're storing millions of instances of a particular key, it would be better storage-wise to name it "pb" instead of "publisherName".</li>
</ul>
<p style="text-align: justify;">The most efficient way to leverage JSONB in PostgreSQL is to combine columns and JSONB. If a key appears very frequently in your JSONB blobs, it is probably better off being stored as a column. Use JSONB as a "catch all" to handle the variable parts of your schema while leveraging traditional columns for fields that are more stable.</p>

<h2 style="padding-top: 15px;"><a id="4"></a>JSONB Data Structures</h2>
<a href="https://scalegrid.io/blog/using-jsonb-in-postgresql-how-to-effectively-store-index-json-data-in-postgresql/"><img class="alignleft wp-image-5614 size-medium" style="float: left; padding: 0px 30px 30px 0px;" src="https://scalegrid.io/blog/wp-content/uploads/2020/07/jsonb1-246x300.png" alt="JSON Implementation Structure" width="400px" height="auto" /></a>
<p style="text-align: justify;">Both JSONB and MongoDB BSON are essentially tree structures, using multi-level nodes to store the parsed JSONB data. MongoDB BSON has a very similar structure.</p>
<p style="text-align: justify;">Images <a style="color: #2da964;" href="https://erthalion.info/2017/12/21/advanced-json-benchmarks/" target="blank">source</a></p>
<a href="https://scalegrid.io/blog/using-jsonb-in-postgresql-how-to-effectively-store-index-json-data-in-postgresql/"><img class="alignleft wp-image-5615 size-large" src="https://scalegrid.io/blog/wp-content/uploads/2020/07/jsonb2-1024x771.png" alt="JSONB Implementation Structure" width="100%" height="auto" /></a>
<h3 style="padding-top: 10px;">JSONB &amp; TOAST</h3>
<p style="text-align: justify; padding-bottom: 10px;">Another important consideration for storage is how JSONB interacts with TOAST (The Oversize Attribute Storage Technique). Typically, when the size of your column exceeds the TOAST_TUPLE_THRESHOLD (2kb default), PostgreSQL will attempt to compress the data and fit in 2kb. If that doesn't work, the data is moved to out-of-line storage. This is what they call "TOASTing" the data. When the data is fetched, the reverse process "deTOASTting" needs to happen. You can also control the TOAST storage strategy:</p>

<ul style="text-align: justify;">
	<li style="padding-bottom: 5px;"><strong>Extended</strong> - Allows for out-of-line storage and compression (using pglz). This is the default option.</li>
	<li style="padding-bottom: 5px;"><strong>External</strong> - Allows for out-of-line storage, but not compression.</li>
</ul>
<p style="text-align: justify;">If you're experiencing delays due to the TOAST compression or decompression, one option is to proactively set the column storage to 'EXTENDED'. For all of the details, please refer to this <a style="color: #2da964;" href="https://www.postgresql.org/docs/current/storage-toast.html" target="_blank">PostgreSQL doc</a>.</p>

<h2 style="padding-top: 15px;"><a id="5"></a>JSONB Operators &amp; Functions</h2>
<p style="text-align: justify; padding-bottom: 10px;">PostgreSQL provides a variety of operators to work on JSONB. From the <a style="color: #2da964;" href="https://www.postgresql.org/docs/12/functions-json.html#FUNCTIONS-JSON-PROCESSING">docs</a>:</p>

<table width="100%">
<tbody>
<tr>
<th style="width: 20%; background-color: #def5fe; padding: 10px;"><b>Operator</b></th>
<th style="width: 80%; background-color: #def5fe; padding: 10px;"><b>Description</b></th>
</tr>
<tr>
<td style="border: 1px solid #eee; padding: 6px 10px; background: #f9f9f9;">-&gt;</td>
<td style="border: 1px solid #eee; padding: 6px 10px;">Get JSON array element (indexed from zero, negative integers count from the end)</td>
</tr>
<tr>
<td style="border: 1px solid #eee; padding: 6px 10px; background: #f9f9f9;">-&gt;</td>
<td style="border: 1px solid #eee; padding: 6px 10px;">Get JSON object field by key</td>
</tr>
<tr>
<td style="border: 1px solid #eee; padding: 6px 10px; background: #f9f9f9;">-&gt;&gt;</td>
<td style="border: 1px solid #eee; padding: 6px 10px;">Get JSON array element as text</td>
</tr>
<tr>
<td style="border: 1px solid #eee; padding: 6px 10px; background: #f9f9f9;">-&gt;&gt;</td>
<td style="border: 1px solid #eee; padding: 6px 10px;">Get JSON object field as text</td>
</tr>
<tr>
<td style="border: 1px solid #eee; padding: 6px 10px; background: #f9f9f9;">#&gt;</td>
<td style="border: 1px solid #eee; padding: 6px 10px;">Get JSON object at the specified path</td>
</tr>
<tr>
<td style="border: 1px solid #eee; padding: 6px 10px; background: #f9f9f9;">#&gt;&gt;</td>
<td style="border: 1px solid #eee; padding: 6px 10px;">Get JSON object at the specified path as text</td>
</tr>
<tr>
<td style="border: 1px solid #eee; padding: 6px 10px; background: #f9f9f9;">@&gt;</td>
<td style="border: 1px solid #eee; padding: 6px 10px;">Does the left JSON value contain the right JSON path/value entries at the top level?</td>
</tr>
<tr>
<td style="border: 1px solid #eee; padding: 6px 10px; background: #f9f9f9;">&lt;@</td>
<td style="border: 1px solid #eee; padding: 6px 10px;">Are the left JSON path/value entries contained at the top level within the right JSON value?</td>
</tr>
<tr>
<td style="border: 1px solid #eee; padding: 6px 10px; background: #f9f9f9;">?</td>
<td style="border: 1px solid #eee; padding: 6px 10px;">Does the <i>string</i> exist as a top-level key within the JSON value?</td>
</tr>
<tr>
<td style="border: 1px solid #eee; padding: 6px 10px; background: #f9f9f9;">?|</td>
<td style="border: 1px solid #eee; padding: 6px 10px;">Do any of these array <i>strings</i> exist as top-level keys?</td>
</tr>
<tr>
<td style="border: 1px solid #eee; padding: 6px 10px; background: #f9f9f9;">?&amp;</td>
<td style="border: 1px solid #eee; padding: 6px 10px;">Do all of these array <i>strings</i> exist as top-level keys?</td>
</tr>
<tr>
<td style="border: 1px solid #eee; padding: 6px 10px; background: #f9f9f9;">||</td>
<td style="border: 1px solid #eee; padding: 6px 10px;">Concatenate two jsonb values into a new jsonb value</td>
</tr>
<tr>
<td style="border: 1px solid #eee; padding: 6px 10px; background: #f9f9f9;">-</td>
<td style="border: 1px solid #eee; padding: 6px 10px;">Delete key/value pair or <i>string</i> element from left operand. Key/value pairs are matched based on their key value.</td>
</tr>
<tr>
<td style="border: 1px solid #eee; padding: 6px 10px; background: #f9f9f9;">-</td>
<td style="border: 1px solid #eee; padding: 6px 10px;">Delete multiple key/value pairs or <i>string</i> elements from left operand. Key/value pairs are matched based on their key value.</td>
</tr>
<tr>
<td style="border: 1px solid #eee; padding: 6px 10px; background: #f9f9f9;">-</td>
<td style="border: 1px solid #eee; padding: 6px 10px;">Delete the array element with specified index (Negative integers count from the end). Throws an error if top level container is not an array.</td>
</tr>
<tr>
<td style="border: 1px solid #eee; padding: 6px 10px; background: #f9f9f9;">#-</td>
<td style="border: 1px solid #eee; padding: 6px 10px;">Delete the field or element with specified path (for JSON arrays, negative integers count from the end)</td>
</tr>
<tr>
<td style="border: 1px solid #eee; padding: 6px 10px; background: #f9f9f9;">@?</td>
<td style="border: 1px solid #eee; padding: 6px 10px;">Does JSON path return any item for the specified JSON value?</td>
</tr>
<tr>
<td style="border: 1px solid #eee; padding: 6px 10px; background: #f9f9f9;">@@</td>
<td style="border: 1px solid #eee; padding: 6px 10px;">Returns the result of JSON path predicate check for the specified JSON value. Only the first item of the result is taken into account. If the result is not Boolean, then null is returned.</td>
</tr>
</tbody>
</table>
<p style="text-align: justify; padding-top: 10px;">PostgreSQL also provides a variety of <a style="color: #2da964;" href="https://www.postgresql.org/docs/12/functions-json.html#FUNCTIONS-JSON-CREATION-TABLE" target="_blank">Creation Functions</a> and <a style="color: #2da964;" href="https://www.postgresql.org/docs/12/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE" target="_blank">Processing Functions</a> to work with the JSONB data.</p>

<h2 style="padding-top: 15px;"><a id="6"></a>JSONB Indexes</h2>
<p style="text-align: justify;">JSONB provides a wide array of options to index your JSON data. At a high-level, we are going to dig into 3 different types of indexes - GIN, BTREE and HASH. Not all index types support all operator classes, so planning is needed to design your indexes based on the type of operators and queries that you plan on using.</p>

<h3 style="padding-top: 10px;">GIN Indexes</h3>
<p style="text-align: justify;">GIN stands for "Generalized Inverted indexes". From the <a style="color: #2da964;" href="http://www.postgresql.org/docs/12/static/gin-intro.html" target="_blank">docs</a>:</p>
<p style="text-align: justify; padding-bottom: 10px;">"GIN is designed for handling cases where the items to be indexed are composite values, and the queries to be handled by the index need to search for element values that appear within the composite items. For example, the items could be documents, and the queries could be searches for documents containing specific words."</p>
<p style="text-align: center;"><a href="https://bitnine.net/blog-postgresql/postgresql-internals-jsonb-type-and-its-indexes/" target="blank"><img class="alignnone size-full wp-image-5706" src="https://scalegrid.io/blog/wp-content/uploads/2020/07/PostgreSQL-GIN-Structure-ScaleGrid-Blog.png" alt="PostgreSQL GIN Structure - ScaleGrid Blog" width="100%" height="auto" /></a></p>
<p style="text-align: justify; padding-top: 10px;">GIN supports two operator classes:</p>

<ul style="text-align: justify;">
	<li style="padding-bottom: 5px;">jsonb_ops (default) - ?, ?|, ?&amp;, @&gt;, @@, @? [Index each key and value in the JSONB element]</li>
	<li style="padding-bottom: 15px;">jsonb_pathops - @&gt;, @@, @? [Index only the values in the JSONB element]</li>
</ul>

<pre><code>CREATE INDEX datagin ON books USING gin (data);
</code></pre>

<h4 style="padding-top: 10px;">Existence Operators (?, ?|, ?&amp; )</h4>
<p style="text-align: justify; padding-bottom: 10px;">These operators can be used to check for the existence of top-level keys in the JSONB. Let's create a GIN index on the data JSONB column. For example, find all books that are available in braille. The JSON looks something like this:</p>


<pre><code>"{"tags": {"nk594127": {"ik71786": "iv678771"}}, "braille": false, "keywords": ["abc", "kef", "keh"], "hardcover": true, "publisher": "EfgdxUdvB0", "criticrating": 1}</code></pre>


<pre><code>demo=# select * from books where data ? 'braille';
id | author | isbn | rating | data

---------+-----------------+------------+--------+------------------------------------------------------------------------------------------------------------------------------------------------------
------------------
1000005 | XEI7xShT8bPu6H7 | 2kD5XJDZUF | 0 | {"tags": {"nk455671": {"ik937456": "iv506075"}}, "braille": true, "keywords": ["abc", "kef", "keh"], "hardcover": false, "publisher": "zSfZIAjGGs", "
criticrating": 4}
.....

demo=# explain analyze select * from books where data ? 'braille';
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------
Bitmap Heap Scan on books (cost=12.75..1005.25 rows=1000 width=158) (actual time=0.033..0.039 rows=15 loops=1)
Recheck Cond: (data ? 'braille'::text)
Heap Blocks: exact=2
-&amp;amp;amp;amp;amp;gt; Bitmap Index Scan on datagin (cost=0.00..12.50 rows=1000 width=0) (actual time=0.022..0.022 rows=15 loops=1)
Index Cond: (data ? 'braille'::text)
Planning Time: 0.102 ms
Execution Time: 0.067 ms
(7 rows)</code></pre>

<p style="text-align: justify; padding: 10px 0px;">As you can see from the explain output, the GIN index that we created is being used for the search. What if we wanted to find books that were in braille or in hardcover?</p>


<pre><code>demo=# explain analyze select * from books where data ?| array['braille','hardcover'];
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------
Bitmap Heap Scan on books (cost=16.75..1009.25 rows=1000 width=158) (actual time=0.029..0.035 rows=15 loops=1)
Recheck Cond: (data ?| '{braille,hardcover}'::text[])
Heap Blocks: exact=2
-&amp;amp;amp;amp;amp;gt; Bitmap Index Scan on datagin (cost=0.00..16.50 rows=1000 width=0) (actual time=0.023..0.023 rows=15 loops=1)
Index Cond: (data ?| '{braille,hardcover}'::text[])
Planning Time: 0.138 ms
Execution Time: 0.057 ms
(7 rows)</code></pre>

<p style="text-align: justify; padding: 10px 0px;">The GIN index supports the "existence" operators only on "top-level" keys. If the key is not at the top level, then the index will not be used. It will result in a sequential scan:</p>


<pre><code>demo=# select * from books where data-&amp;amp;amp;amp;amp;gt;'tags' ? 'nk455671';
id | author | isbn | rating | data

---------+-----------------+------------+--------+------------------------------------------------------------------------------------------------------------------------------------------------------
------------------
1000005 | XEI7xShT8bPu6H7 | 2kD5XJDZUF | 0 | {"tags": {"nk455671": {"ik937456": "iv506075"}}, "braille": true, "keywords": ["abc", "kef", "keh"], "hardcover": false, "publisher": "zSfZIAjGGs", "
criticrating": 4}
685122 | GWfuvKfQ1PCe1IL | jnyhYYcF66 | 3 | {"tags": {"nk455671": {"ik615925": "iv253423"}}, "publisher": "b2NwVg7VY3", "criticrating": 0}
(2 rows)

demo=# explain analyze select * from books where data-&amp;amp;amp;amp;amp;gt;'tags' ? 'nk455671';
QUERY PLAN
----------------------------------------------------------------------------------------------------------
Seq Scan on books (cost=0.00..38807.29 rows=1000 width=158) (actual time=0.018..270.641 rows=2 loops=1)
Filter: ((data -&amp;amp;amp;amp;amp;gt; 'tags'::text) ? 'nk455671'::text)
Rows Removed by Filter: 1000017
Planning Time: 0.078 ms
Execution Time: 270.728 ms
(5 rows)</code></pre>

<p style="text-align: justify; padding: 10px 0px;">The way to check for existence in nested docs is to use "expression indexes". Let's create an index on data-&gt;tags:</p>


<pre><code>CREATE INDEX datatagsgin ON books USING gin (data-&amp;amp;amp;amp;amp;gt;'tags');</code></pre>


<pre><code>demo=# select * from books where data-&amp;amp;amp;amp;amp;gt;'tags' ? 'nk455671';
id | author | isbn | rating | data

---------+-----------------+------------+--------+------------------------------------------------------------------------------------------------------------------------------------------------------
------------------
1000005 | XEI7xShT8bPu6H7 | 2kD5XJDZUF | 0 | {"tags": {"nk455671": {"ik937456": "iv506075"}}, "braille": true, "keywords": ["abc", "kef", "keh"], "hardcover": false, "publisher": "zSfZIAjGGs", "
criticrating": 4}
685122 | GWfuvKfQ1PCe1IL | jnyhYYcF66 | 3 | {"tags": {"nk455671": {"ik615925": "iv253423"}}, "publisher": "b2NwVg7VY3", "criticrating": 0}
(2 rows)

demo=# explain analyze select * from books where data-&amp;amp;amp;amp;amp;gt;'tags' ? 'nk455671';
QUERY PLAN
------------------------------------------------------------------------------------------------------------------------
Bitmap Heap Scan on books (cost=12.75..1007.75 rows=1000 width=158) (actual time=0.031..0.035 rows=2 loops=1)
Recheck Cond: ((data -&amp;amp;amp;amp;amp;gt;'tags'::text) ? 'nk455671'::text)
Heap Blocks: exact=2
-&amp;amp;amp;amp;amp;gt; Bitmap Index Scan on datatagsgin (cost=0.00..12.50 rows=1000 width=0) (actual time=0.021..0.021 rows=2 loops=1)
Index Cond: ((data -&amp;amp;amp;amp;amp;gt;'tags'::text) ? 'nk455671'::text)
Planning Time: 0.098 ms
Execution Time: 0.061 ms
(7 rows)</code></pre>

<p style="text-align: justify; padding: 10px 0px;">Note: An alternative here is to use the @&gt; operator:</p>


<pre><code>select * from books where data @&amp;amp;amp;amp;amp;gt; '{"tags":{"nk455671":{}}}'::jsonb;</code></pre>

<p style="text-align: justify; padding-top: 10px;">However, this only works if the value is an object. So, if you're unsure if the value is an object or a primitive value, it could lead to incorrect results.</p>

<h4 style="padding-top: 10px;">Path Operators @&gt;, &lt;@</h4>
<p style="text-align: justify; padding-bottom: 10px;">The "path" operator can be used for multi-level queries of your JSONB data. Let's use it similar to the ? operator above:</p>


<pre><code>select * from books where data @&amp;amp;amp;amp;amp;gt; '{"braille":true}'::jsonb;
demo=# explain analyze select * from books where data @&amp;amp;amp;amp;amp;gt; '{"braille":true}'::jsonb;
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------
Bitmap Heap Scan on books (cost=16.75..1009.25 rows=1000 width=158) (actual time=0.040..0.048 rows=6 loops=1)
Recheck Cond: (data @&amp;amp;amp;amp;amp;gt; '{"braille": true}'::jsonb)
Rows Removed by Index Recheck: 9
Heap Blocks: exact=2
-&amp;amp;amp;amp;amp;gt; Bitmap Index Scan on datagin (cost=0.00..16.50 rows=1000 width=0) (actual time=0.030..0.030 rows=15 loops=1)
Index Cond: (data @&amp;amp;amp;amp;amp;gt; '{"braille": true}'::jsonb)
Planning Time: 0.100 ms
Execution Time: 0.076 ms
(8 rows)</code></pre>

<p style="text-align: justify; padding: 10px 0px;">The path operators support querying nested objects or top-level objects:</p>

<pre><code>demo=# select * from books where data @&amp;amp;amp;amp;amp;gt; '{"publisher":"XlekfkLOtL"}'::jsonb;
id | author | isbn | rating | data
-----+-----------------+------------+--------+-------------------------------------------------------------------------------------
346 | uD3QOvHfJdxq2ez | KiAaIRu8QE | 1 | {"tags": {"nk88": {"ik37": "iv161"}}, "publisher": "XlekfkLOtL", "criticrating": 3}
(1 row)

demo=# explain analyze select * from books where data @&amp;amp;amp;amp;amp;gt; '{"publisher":"XlekfkLOtL"}'::jsonb;
QUERY PLAN
--------------------------------------------------------------------------------------------------------------------
Bitmap Heap Scan on books (cost=16.75..1009.25 rows=1000 width=158) (actual time=0.491..0.492 rows=1 loops=1)
Recheck Cond: (data @&amp;amp;amp;amp;amp;gt; '{"publisher": "XlekfkLOtL"}'::jsonb)
Heap Blocks: exact=1
-&amp;amp;amp;amp;amp;gt; Bitmap Index Scan on datagin (cost=0.00..16.50 rows=1000 width=0) (actual time=0.092..0.092 rows=1 loops=1)
Index Cond: (data @&amp;amp;amp;amp;amp;gt; '{"publisher": "XlekfkLOtL"}'::jsonb)
Planning Time: 0.090 ms
Execution Time: 0.523 ms</code></pre>

<p style="text-align: justify; padding: 10px 0px;">The queries can be multi-level as well:</p>


<pre><code>demo=# select * from books where data @&amp;amp;amp;amp;amp;gt; '{"tags":{"nk455671":{"ik937456":"iv506075"}}}'::jsonb;
id | author | isbn | rating | data

---------+-----------------+------------+--------+------------------------------------------------------------------------------------------------------------------------------------------------------
------------------
1000005 | XEI7xShT8bPu6H7 | 2kD5XJDZUF | 0 | {"tags": {"nk455671": {"ik937456": "iv506075"}}, "braille": true, "keywords": ["abc", "kef", "keh"], "hardcover": false, "publisher": "zSfZIAjGGs", "
criticrating": 4}
(1 row)</code></pre>

<h4 style="padding-top: 10px;">GIN Index "pathops" Operator Class</h4>
<p style="text-align: justify;">GIN also supports a "pathops" option to reduce the size of the GIN index. When you use the pathops option, the only operator support is the "@&gt;" so you need to be careful with your queries. From the <a style="color: #2da964;" href="https://www.postgresql.org/docs/12/datatype-json.html#DATATYPE-JSONPATH" target="_blank">docs</a>:</p>
<p style="text-align: justify;">"The technical difference between a jsonb_ops and a jsonb_path_ops GIN index is that the former creates independent index items for each key and value in the data, while the latter creates index items only for each value in the data"</p>
<p style="text-align: justify; padding-bottom: 10px;">You can create a GIN pathops index as follows:</p>


<pre><code>CREATE INDEX dataginpathops ON books USING gin (data jsonb_path_ops);</code></pre>

<p style="text-align: justify; padding: 10px 0px;">On my small dataset of 1 million books, you can see that the pathops GIN index is smaller - you should test with your dataset to understand the savings:</p>


<pre><code>public | dataginpathops | index | sgpostgres | books | 67 MB |
public | datatagsgin | index | sgpostgres | books | 84 MB |</code></pre>

<p style="text-align: justify; padding: 10px 0px;">Let's rerun our query from before with the pathops index:</p>


<<pre>code>demo=# select * from books where data @&amp;amp;amp;amp;amp;gt; '{"tags":{"nk455671":{"ik937456":"iv506075"}}}'::jsonb;
id | author | isbn | rating | data

---------+-----------------+------------+--------+------------------------------------------------------------------------------------------------------------------------------------------------------
------------------
1000005 | XEI7xShT8bPu6H7 | 2kD5XJDZUF | 0 | {"tags": {"nk455671": {"ik937456": "iv506075"}}, "braille": true, "keywords": ["abc", "kef", "keh"], "hardcover": false, "publisher": "zSfZIAjGGs", "
criticrating": 4}
(1 row)

demo=# explain select * from books where data @&amp;amp;amp;amp;amp;gt; '{"tags":{"nk455671":{"ik937456":"iv506075"}}}'::jsonb;
QUERY PLAN
-----------------------------------------------------------------------------------------
Bitmap Heap Scan on books (cost=12.75..1005.25 rows=1000 width=158)
Recheck Cond: (data @&amp;amp;amp;amp;amp;gt; '{"tags": {"nk455671": {"ik937456": "iv506075"}}}'::jsonb)
-&amp;amp;amp;amp;amp;gt; Bitmap Index Scan on dataginpathops (cost=0.00..12.50 rows=1000 width=0)
Index Cond: (data @&amp;amp;amp;amp;amp;gt; '{"tags": {"nk455671": {"ik937456": "iv506075"}}}'::jsonb)
(4 rows)</code></pre>

<p style="text-align: justify; padding: 10px 0px;">However, as mentioned above, the "pathops" option does not support all of the scenarios that the default operator class supports. With a "pathops" GIN index, all these queries are not able to leverage the GIN index. To summarize, you have a smaller index but it supports a more limited use case.</p>


<pre><code>select * from books where data ? 'tags'; =&amp;amp;amp;amp;amp;gt; Sequential scan
select * from books where data @&amp;amp;amp;amp;amp;gt; '{"tags" :{}}'; =&amp;amp;amp;amp;amp;gt; Sequential scan
select * from books where data @&amp;amp;amp;amp;amp;gt; '{"tags" :{"k7888":{}}}' =&amp;amp;amp;amp;amp;gt; Sequential scan</code></pre>

<h3 style="padding-top: 10px;">B-Tree indexes</h3>
<p style="text-align: justify;">B-tree indexes are the most common index type in relational databases. However, if you index an entire JSONB column with a B-tree index, the only useful operators are "=", &lt;, &lt;=, &gt;, &gt;=. Essentially, this can only be used for whole object comparisons, which has a very limited use case.</p>
<p style="text-align: justify; padding-bottom: 10px;">A more common scenario is to use B-tree "expression indexes". For a primer, refer here - <a style="color: #2da964;" href="https://www.postgresql.org/docs/8.1/indexes-expressional.html">Indexes on Expressions</a>. B-tree expression indexes can support the common comparison operators '=', '&lt;', '&gt;', '&gt;=', '&lt;='. As you might recall, GIN indexes don't support these operators. Let's consider the case when we want to retrieve all books with a data-&gt;criticrating &gt; 4. So, you would build a query something like this:</p>


<pre><code>demo=# select * from books where data-&amp;amp;amp;amp;gt;'criticrating' &amp;amp;amp;amp;gt; 4;
ERROR: operator does not exist: jsonb &amp;amp;amp;amp;gt;= integer
LINE 1: select * from books where data-&amp;amp;amp;amp;gt;'criticrating'  &amp;amp;amp;amp;gt;= 4;
^
HINT: No operator matches the given name and argument types. You might need to add explicit type casts.</code></pre>

<p style="text-align: justify; padding: 10px 0px;">Well, that doesn't work since the '-&gt;' operator returns a JSONB type. So we need to use something like this:</p>


<pre><code>demo=# select * from books where (data-&amp;amp;amp;amp;gt;'criticrating')::int4 &amp;amp;amp;amp;gt; 4;</code></pre>

<p style="text-align: justify; padding: 10px 0px;">If you're using a version prior to PostgreSQL 11, it gets more ugly. You need to first query as text and then cast it to integer:</p>


<pre><code>demo=# select * from books where (data-&amp;amp;amp;amp;gt;'criticrating')::int4 &amp;amp;amp;amp;gt; 4;</code></pre>

<p style="text-align: justify; padding: 10px 0px;">For expression indexes, the index needs to be an exact match with the query expression. So, our index would look something like this:</p>


<pre><code>demo=# CREATE INDEX criticrating ON books USING BTREE (((data-&amp;amp;amp;amp;gt;'criticrating')::int4));
CREATE INDEX

demo=# explain analyze select * from books where (data-&amp;amp;amp;amp;gt;'criticrating')::int4 = 3;
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------
Index Scan using criticrating on books (cost=0.42..4626.93 rows=5000 width=158) (actual time=0.069..70.221 rows=199883 loops=1)
Index Cond: (((data -&amp;amp;amp;amp;gt; 'criticrating'::text))::integer = 3)
Planning Time: 0.103 ms
Execution Time: 79.019 ms
(4 rows)

demo=# explain analyze select * from books where (data-&amp;amp;amp;amp;gt;'criticrating')::int4 = 3;
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------
Index Scan using criticrating on books (cost=0.42..4626.93 rows=5000 width=158) (actual time=0.069..70.221 rows=199883 loops=1)
Index Cond: (((data -&amp;amp;amp;amp;gt; 'criticrating'::text))::integer = 3)
Planning Time: 0.103 ms
Execution Time: 79.019 ms
(4 rows)
</code></pre>
From above we can see that the BTREE index is being used as expected.

<h3 style="padding-top: 10px;">Hash Indexes</h3>
<p style="text-align: left;">If you are only interested in the "=" operator, then Hash indexes become interesting. For example, consider the case when we are looking for a particular tag on a book. The element to be indexed can be a top level element or deeply nested.</p>
<p style="text-align: left; padding-bottom: 10px;">E.g. tags-&gt;publisher = XlekfkLOtL</p>


<pre><code>CREATE INDEX publisherhash ON books USING HASH ((data-&amp;amp;amp;amp;gt;'publisher'));</code></pre>

<p style="text-align: justify; padding: 10px 0px;">Hash indexes also tend to be smaller in size than B-tree or GIN indexes. Of course, this ultimately depends on your data set.</p>


<pre><code>demo=# select * from books where data-&amp;amp;amp;amp;gt;'publisher' = 'XlekfkLOtL'
demo-# ;
id | author | isbn | rating | data
-----+-----------------+------------+--------+-------------------------------------------------------------------------------------
346 | uD3QOvHfJdxq2ez | KiAaIRu8QE | 1 | {"tags": {"nk88": {"ik37": "iv161"}}, "publisher": "XlekfkLOtL", "criticrating": 3}
(1 row)

demo=# explain analyze select * from books where data-&amp;amp;amp;amp;gt;'publisher' = 'XlekfkLOtL';
QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------
Index Scan using publisherhash on books (cost=0.00..2.02 rows=1 width=158) (actual time=0.016..0.017 rows=1 loops=1)
Index Cond: ((data -&amp;amp;amp;amp;gt; 'publisher'::text) = 'XlekfkLOtL'::text)
Planning Time: 0.080 ms
Execution Time: 0.035 ms
(4 rows)</code></pre>

<h3 style="padding-top: 10px;">Special Mention: GIN Trigram Indexes</h3>
<p style="text-align: justify; padding-bottom: 10px;">PostgreSQL supports string matching using trigram indexes. Trigram indexes work by breaking up text into trigrams. Trigrams are basically words broken up into sequences of 3 letters. More information can be found in the <a style="color: #2da964;" href="https://www.postgresql.org/docs/12/pgtrgm.html">documentation</a>. GIN indexes support the “gin_trgm_ops” class that can be used to index the data in JSONB. You can choose to use expression indexes to build the trigram index on a particular column.</p>


<pre><code>CREATE EXTENSION pg_trgm;
CREATE INDEX publisher ON books USING GIN ((data-&amp;amp;amp;amp;gt;'publisher') gin_trgm_ops);

demo=# select * from books where data-&amp;amp;amp;amp;gt;'publisher' LIKE '%I0UB%';
 id |     author      |    isbn    | rating |                                      data
----+-----------------+------------+--------+---------------------------------------------------------------------------------
  4 | KiEk3xjqvTpmZeS | EYqXO9Nwmm |      0 | {"tags": {"nk3": {"ik1": "iv1"}}, "publisher": "MI0UBqZJDt", "criticrating": 1}
(1 row)</code></pre>

<p style="text-align: justify; padding: 10px 0px;">As you can see in the query above, we can search for any arbitrary string occurring at any potion. Unlike the B-tree indexes, we are not restricted to left anchored expressions.</p>


<pre><code>demo=# explain analyze select * from books where data-&amp;amp;amp;amp;gt;'publisher' LIKE '%I0UB%';
                                                     QUERY PLAN
--------------------------------------------------------------------------------------------------------------------
 Bitmap Heap Scan on books  (cost=9.78..111.28 rows=100 width=158) (actual time=0.033..0.033 rows=1 loops=1)
   Recheck Cond: ((data -&amp;amp;amp;amp;amp;gt; 'publisher'::text) ~~ '%I0UB%'::text)
   Heap Blocks: exact=1
   -&amp;amp;amp;amp;gt;  Bitmap Index Scan on publisher  (cost=0.00..9.75 rows=100 width=0) (actual time=0.025..0.025 rows=1 loops=1)
         Index Cond: ((data -&amp;amp;amp;amp;amp;gt; 'publisher'::text) ~~ '%I0UB%'::text)
 Planning Time: 0.213 ms
 Execution Time: 0.058 ms
(7 rows)</code></pre>

<h3>Special Mention: GIN Array Indexes</h3>
<p style="text-align: left; padding-bottom: 10px;">JSONB has great built-in support for indexing arrays. Let's consider an example of indexing an array of strings using a GIN index in the case when our JSONB data contains a "keyword" element and we would like to find rows with particular keywords:</p>


<pre><code>{"tags": {"nk780341": {"ik397357": "iv632731"}}, "keywords": ["abc", "kef", "keh"], "publisher": "fqaJuAdjP5", "criticrating": 2}

CREATE INDEX keywords ON books USING GIN ((data-&amp;amp;amp;amp;gt;'keywords') jsonb_path_ops);

demo=# select * from books where data-&amp;amp;amp;amp;gt;'keywords' @&amp;amp;amp;amp;gt; '["abc", "keh"]'::jsonb;
   id    |     author      |    isbn    | rating |                                                               data
---------+-----------------+------------+--------+-----------------------------------------------------------------------------------------------------------------------------------
 1000003 | zEG406sLKQ2IU8O | viPdlu3DZm |      4 | {"tags": {"nk263020": {"ik203820": "iv817928"}}, "keywords": ["abc", "kef", "keh"], "publisher": "7NClevxuTM", "criticrating": 2}
 1000004 | GCe9NypHYKDH4rD | so6TQDYzZ3 |      4 | {"tags": {"nk780341": {"ik397357": "iv632731"}}, "keywords": ["abc", "kef", "keh"], "publisher": "fqaJuAdjP5", "criticrating": 2}
(2 rows)

demo=# explain analyze select * from books where data-&amp;amp;amp;amp;gt;'keywords' @&amp;amp;amp;amp;gt; '["abc", "keh"]'::jsonb;
                                                     QUERY PLAN
---------------------------------------------------------------------------------------------------------------------
 Bitmap Heap Scan on books  (cost=54.75..1049.75 rows=1000 width=158) (actual time=0.026..0.028 rows=2 loops=1)
   Recheck Cond: ((data -&amp;amp;amp;amp;gt; 'keywords'::text) @&amp;amp;amp;amp;gt; '["abc", "keh"]'::jsonb)
   Heap Blocks: exact=1
   -&amp;amp;amp;amp;gt;  Bitmap Index Scan on keywords  (cost=0.00..54.50 rows=1000 width=0) (actual time=0.014..0.014 rows=2 loops=1)
         Index Cond: ((data -&amp;amp;amp;amp;gt; 'keywords'::text) @&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; '["abc", "keh"]'::jsonb)
 Planning Time: 0.131 ms
 Execution Time: 0.063 ms
(7 rows)</code></pre>

<p style="text-align: justify; padding: 10px 0px;">The order of the items in the array on the right does not matter. For example, the following query would return the same result as the previous:</p>


<pre><code>demo=# explain analyze select * from books where data-&amp;amp;amp;amp;gt;'keywords' @&amp;amp;amp;amp;gt; '["keh","abc"]'::jsonb;</code></pre>

<p style="text-align: justify; padding: 10px 0px;">All elements in the right side array of the containment operator need to be present - basically like an "AND" operator. If you want "OR" behavior, you can construct it in the WHERE clause:</p>


<pre><code>demo=# explain analyze select * from books where (data-&amp;amp;amp;amp;gt;'keywords' @&amp;amp;amp;amp;gt; '["abc"]'::jsonb OR data-&amp;amp;amp;amp;gt;'keywords' @&amp;amp;amp;amp;gt; '["keh"]'::jsonb);</code></pre>

<p style="text-align: justify; padding-top: 10px;">More details on the behavior of the containment operators with arrays can be found in the <a style="color: #2da964;" href="https://www.postgresql.org/docs/12/datatype-json.html#JSON-CONTAINMENT" target="_blank">documentation</a>.</p>

<h2 style="padding-top: 15px;"><a id="7"></a>SQL/JSON &amp; JSONPath</h2>
<p style="text-align: justify;">SQL standard added support for JSON  in SQL - SQL/JSON Standard-2016. With the PostgreSQL 12/13 releases, PostgreSQL has one of the best implementations of the SQL/JSON standard. For more details refer to the <a style="color: #2da964;" href="https://obartunov.livejournal.com/200076.html" target="_blank">PostgreSQL 12 announcement</a>.</p>
<p style="text-align: justify; padding-bottom: 10px;">One of the core features of SQL/JSON is support for the JSONPath language to query JSONB data. JSONPath allows you to specify an expression (using a syntax similar to the property access notation in Javascript) to query your JSONB data. This makes it simple and intuitive, but is also very powerful to query your JSONB data. Think of  JSONPath as the logical equivalent of XPath for XML.</p>

<table width="100%">
<tbody>
<tr>
<td style="width: 10%; border: 1px solid #eee; padding: 10px; background: #f9f9f9;">.key</td>
<td style="width: 90%; border: 1px solid #eee; padding: 10px;">Returns an object member with the specified key.</td>
</tr>
<tr>
<td style="border: 1px solid #eee; padding: 10px; background: #f9f9f9;">[*]</td>
<td style="border: 1px solid #eee; padding: 10px;">Wildcard array element accessor that returns all array elements.</td>
</tr>
<tr>
<td style="border: 1px solid #eee; padding: 10px; background: #f9f9f9;">.*</td>
<td style="border: 1px solid #eee; padding: 10px;">Wildcard member accessor that returns the values of all members located at the top level of the current object.</td>
</tr>
<tr>
<td style="border: 1px solid #eee; padding: 10px; background: #f9f9f9;">.**</td>
<td style="border: 1px solid #eee; padding: 10px;">Recursive wildcard member accessor that processes all levels of the JSON hierarchy of the current object and returns all the member values, regardless of their nesting level.</td>
</tr>
</tbody>
</table>
<p style="text-align: justify; padding-top: 10px;"><i>Refer to <a style="color: #2da964;" href="https://www.postgresql.org/docs/12/datatype-json.html#DATATYPE-JSONPATH">JSONPath documentation </a>for the full list of operators. JSONPath also supports a variety of filter expressions.</i></p>

<h3 style="padding-top: 10px;">JSONPath Functions</h3>
<p style="text-align: justify; padding-bottom: 10px;">PostgreSQL 12 provides several functions to use JSONPath to query your JSONB data. From the docs:</p>

<ul style="text-align: justify;">
	<li style="padding-bottom: 5px;"><strong>jsonb_path_exists -</strong> Checks whether JSONB path returns any item for the specified <strong>JSON</strong> value.</li>
	<li style="padding-bottom: 5px;"><strong>jsonb_path_match -</strong> Returns the result of JSONB path predicate check for the specified JSONB value. Only the first item of the result is taken into account. If the result is not Boolean, then null is returned.</li>
	<li style="padding-bottom: 5px;"><strong>jsonb_path_query -</strong> Gets all JSONB items returned by JSONB path for the specified JSONB value. There are also a couple of other variants of this function that handle arrays of objects.</li>
</ul>
<p style="text-align: justify; padding-bottom: 10px;">Let's start with a simple query - finding books by publisher:</p>


<pre><code>demo=# select * from books where data @@ '$.publisher == "ktjKEZ1tvq"';
id | author | isbn | rating | data
---------+-----------------+------------+--------+----------------------------------------------------------------------------------------------------------------------------------
1000001 | 4RNsovI2haTgU7l | GwSoX67gLS | 2 | {"tags": {"nk542369": {"ik55240": "iv305393"}}, "keywords": ["abc", "def", "geh"], "publisher": "ktjKEZ1tvq", "criticrating": 0}
(1 row)

demo=# explain analyze select * from books where data @@ '$.publisher == "ktjKEZ1tvq"';
QUERY PLAN
--------------------------------------------------------------------------------------------------------------------
Bitmap Heap Scan on books (cost=21.75..1014.25 rows=1000 width=158) (actual time=0.123..0.124 rows=1 loops=1)
Recheck Cond: (data @@ '($."publisher" == "ktjKEZ1tvq")'::jsonpath)
Heap Blocks: exact=1
-&amp;amp;amp;amp;gt; Bitmap Index Scan on datagin (cost=0.00..21.50 rows=1000 width=0) (actual time=0.110..0.110 rows=1 loops=1)
Index Cond: (data @@ '($."publisher" == "ktjKEZ1tvq")'::jsonpath)
Planning Time: 0.137 ms
Execution Time: 0.194 ms
(7 rows)</code></pre>

<p style="text-align: justify; padding: 10px 0px;">You can rewrite this expression as a JSONPath filter:</p>


<pre><code>demo=# select * from books where jsonb_path_exists(data,'$.publisher ?(@ == "ktjKEZ1tvq")');</code></pre>

<p style="text-align: justify; padding: 10px 0px;">You can also use very complex query expressions. For example, let's select books where print style = hardcover and price = 100:</p>


<pre><code>select * from books where jsonb_path_exists(data, '$.prints[*] ?(@.style=="hc" &amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp; @.price == 100)');</code></pre>

<p style="text-align: justify; padding: 10px 0px;">However, index support for JSONPath is very limited at this point - this makes it dangerous to use JSONPath in the where clause. JSONPath support for indexes will be improved in subsequent releases.</p>


<pre><code>demo=# explain analyze select * from books where jsonb_path_exists(data,'$.publisher ?(@ == "ktjKEZ1tvq")');
QUERY PLAN
------------------------------------------------------------------------------------------------------------
Seq Scan on books (cost=0.00..36307.24 rows=333340 width=158) (actual time=0.019..480.268 rows=1 loops=1)
Filter: jsonb_path_exists(data, '$."publisher"?(@ == "ktjKEZ1tvq")'::jsonpath, '{}'::jsonb, false)
Rows Removed by Filter: 1000028
Planning Time: 0.095 ms
Execution Time: 480.348 ms
(5 rows)</code></pre>

<h3 style="padding-top: 10px;">Projecting Partial JSON</h3>
<p style="text-align: justify; padding-bottom: 10px;">Another great use case for JSONPath is projecting partial JSONB from the row that matches. Consider the following sample JSONB:</p>


<pre><code>demo=# select jsonb_pretty(data) from books where id = 1000029;
jsonb_pretty
-----------------------------------
{
 "tags": {
 "nk678947": {
      "ik159670": "iv32358
 }
 },
 "prints": [
     {
         "price": 100,
         "style": "hc"
     },
     {
        "price": 50,
        "style": "pb"
     }
 ],
 "braille": false,
 "keywords": [
     "abc",
     "kef",
     "keh"
 ],
 "hardcover": true,
 "publisher": "ppc3YXL8kK",
 "criticrating": 3
}</code></pre>

<p style="text-align: justify; padding: 10px 0px;">Select only the publisher field:</p>


<pre><code>demo=# select jsonb_path_query(data, '$.publisher') from books where id = 1000029;
jsonb_path_query
------------------
"ppc3YXL8kK"
(1 row)</code></pre>

<p style="text-align: justify; padding: 10px 0px;">Select the prints field (which is an array of objects):</p>


<pre><code>demo=# select jsonb_path_query(data, '$.prints') from books where id = 1000029;
jsonb_path_query
---------------------------------------------------------------
[{"price": 100, "style": "hc"}, {"price": 50, "style": "pb"}]
(1 row)</code></pre>

<p style="text-align: justify; padding: 10px 0px;">Select the first element in the array prints:</p>


<pre><code>demo=# select jsonb_path_query(data, '$.prints[0]') from books where id = 1000029;
jsonb_path_query
-------------------------------
{"price": 100, "style": "hc"}
(1 row)</code></pre>

<p style="text-align: justify; padding: 10px 0px;">Select the last element in the array prints:</p>


<pre><code>demo=# select jsonb_path_query(data, '$.prints[$.size()]') from books where id = 1000029;
jsonb_path_query
------------------------------
{"price": 50, "style": "pb"}
(1 row)</code></pre>

<p style="text-align: justify; padding: 10px 0px;">Select only the hardcover prints from the array:</p>


<pre><code>demo=# select jsonb_path_query(data, '$.prints[*] ?(@.style=="hc")') from books where id = 1000029;
       jsonb_path_query
-------------------------------
 {"price": 100, "style": "hc"}
(1 row)</code></pre>

<p style="text-align: justify; padding: 10px 0px;">We can also chain the filters:</p>


<pre><code>demo=# select jsonb_path_query(data, '$.prints[*] ?(@.style=="hc") ?(@.price ==100)') from books where id = 1000029;
jsonb_path_query
-------------------------------
{"price": 100, "style": "hc"}
(1 row)</code></pre>

<p style="text-align: justify; padding: 10px 0px 20px;">In summary, PostgreSQL provides a powerful and versatile platform to store and process JSON data. There are several gotcha's that you need to be aware of, but we are optimistic that it will be fixed in future releases.</p>

<table style="background: #def5fe; margin-top:40px;">
<tbody>
<tr style="padding: 30px;">
<th></th>
</tr>
<tr>
<td style="padding: 20px;">
<table style="background: #fff;">
<tbody>
<tr>
<td style="padding: 20px;" width="100%">
<h3 style="font-size: 30px; padding-bottom: 20px;">More tips for you</h3>
<h4>Which Is the Best PostgreSQL GUI?</h4>
<p style="padding-bottom: 10px;">PostgreSQL graphical user interface (GUI) tools help these open source database users to manage, manipulate, and visualize their data. In this post, we discuss the top 5 GUI tools for administering your PostgreSQL deployments. <a style="color: #2da964; text-decoration: underline;" href="https://scalegrid.io/blog/which-is-the-best-postgresql-gui-2019-comparison/">Learn more</a></p>


<hr />

<h4>Managing High Availability in PostgreSQL</h4>
<p style="padding-bottom: 10px;">Managing high availability in your PostgreSQL hosting is very important to ensuring your clusters maintain exceptional uptime and strong operational performance so your data is always available to your application. <a style="color: #2da964; text-decoration: underline;" href="https://scalegrid.io/blog/managing-high-availability-in-postgresql-part-1/">Learn more</a></p>


<hr />

<h4>PostgreSQL Connection Pooling: Part 1 – Pros & Cons</h4>
<p style="padding-bottom: 10px;">In modern apps, clients open a lot of connections. Developers are discouraged from holding a database connection while other operations take place. “Open a connection as late as possible, close as soon as possible”. <a style="color: #2da964; text-decoration: underline;" href="https://scalegrid.io/blog/postgresql-connection-pooling-part-1-pros-and-cons/">Learn more</a></p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>