Skip to content

Commit 626f9be

Browse files
committed
Docs: add example clarifying use of nested JSON containment.
Show how this can be used in practice to make queries simpler and more flexible. Also, draw an explicit contrast to the existence operator, which doesn't work that way. Peter Geoghegan and Tom Lane
1 parent 589017e commit 626f9be

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

doc/src/sgml/json.sgml

+28
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,34 @@ SELECT '"foo"'::jsonb ? 'foo';
346346
need to be searched linearly.
347347
</para>
348348

349+
<tip>
350+
<para>
351+
Because JSON containment is nested, an appropriate query can skip
352+
explicit selection of sub-objects. As an example, suppose that we have
353+
a <structfield>doc</> column containing objects at the top level, with
354+
most objects containing <literal>tags</> fields that contain arrays of
355+
sub-objects. This query finds entries in which sub-objects containing
356+
both <literal>"term":"paris"</> and <literal>"term":"food"</> appear,
357+
while ignoring any such keys outside the <literal>tags</> array:
358+
<programlisting>
359+
SELECT doc-&gt;'site_name' FROM websites
360+
WHERE doc @&gt; '{"tags":[{"term":"paris"}, {"term":"food"}]}';
361+
</programlisting>
362+
One could accomplish the same thing with, say,
363+
<programlisting>
364+
SELECT doc-&gt;'site_name' FROM websites
365+
WHERE doc-&gt;'tags' @&gt; '[{"term":"paris"}, {"term":"food"}]';
366+
</programlisting>
367+
but that approach is less flexible, and often less efficient as well.
368+
</para>
369+
370+
<para>
371+
On the other hand, the JSON existence operator is not nested: it will
372+
only look for the specified key or array element at top level of the
373+
JSON value.
374+
</para>
375+
</tip>
376+
349377
<para>
350378
The various containment and existence operators, along with all other
351379
JSON operators and functions are documented

0 commit comments

Comments
 (0)