From 9a1a22980d3650e6e232bc4423ec74bfc6d0e7be Mon Sep 17 00:00:00 2001 From: Tom Lane Date: Thu, 29 Oct 2015 18:54:35 -0400 Subject: [PATCH] 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 --- doc/src/sgml/json.sgml | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/doc/src/sgml/json.sgml b/doc/src/sgml/json.sgml index 118fb35e25..3cf78d6394 100644 --- a/doc/src/sgml/json.sgml +++ b/doc/src/sgml/json.sgml @@ -349,6 +349,34 @@ SELECT '"foo"'::jsonb ? 'foo'; need to be searched linearly. + + + Because JSON containment is nested, an appropriate query can skip + explicit selection of sub-objects. As an example, suppose that we have + a doc column containing objects at the top level, with + most objects containing tags fields that contain arrays of + sub-objects. This query finds entries in which sub-objects containing + both "term":"paris" and "term":"food" appear, + while ignoring any such keys outside the tags array: + +SELECT doc->'site_name' FROM websites + WHERE doc @> '{"tags":[{"term":"paris"}, {"term":"food"}]}'; + + One could accomplish the same thing with, say, + +SELECT doc->'site_name' FROM websites + WHERE doc->'tags' @> '[{"term":"paris"}, {"term":"food"}]'; + + but that approach is less flexible, and often less efficient as well. + + + + On the other hand, the JSON existence operator is not nested: it will + only look for the specified key or array element at top level of the + JSON value. + + + The various containment and existence operators, along with all other JSON operators and functions are documented