title: Postgresql querying double nested json
body: <p>I am using postgres 9.4. I have a JSON type column called &quot;data&quot; in &quot;list&quot; table and the data stored in it is in the format</p>
  <pre><code>{
      &quot;pages&quot;:[
           {
               &quot;pageName&quot; : &quot;test&quot;,
               &quot;components&quot; : [
                    {
                        &quot;name&quot; : &quot;comp1&quot;,
                        &quot;type&quot; : &quot;text&quot;,
                        &quot;value&quot; : &quot;val1&quot;
                    },
                    {
                        &quot;name&quot; : &quot;comp2&quot;,
                        &quot;type&quot; : &quot;grade&quot;,
                        &quot;value&quot; : 7
                    }
               ]
           }
      ]
  }
  </code></pre>
  <p>I need to query all component values for all lists that have component of type &quot;grade&quot;.
  I currently use this query:</p>
  <pre><code>select avg((comp-&gt;&gt;'value')::int)
  from list,
    jsonb_array_elements(data-&gt;'pages') as page ,
    jsonb_array_elements(page-&gt;'components') as comp
  where comp @&gt; '{&quot;type&quot;:&quot;grade&quot;}' and (comp-&gt;&gt;'value') IS NOT NULL;
  </code></pre>
  <p>The problem is i think this is a very inefficient, and as far as i can see from explain, it does not use any index which i set on the data column as using GIN(data jsonb_path_ops);</p>
  <p>Is there a more efficient way to query double nested objects?</p>