简体   繁体   中英

PostgreSQL 9.6 jsonb query using like on arrays

i need to query a jsonb table field with the normal like functions.

This is my json field

  "campi":[ 
    { 
      "label":"testLabel",
      "valore":[ 
        "testValore",
        "testValore2"
      ],
      "idCampo":"testID",
      "idCampoTP":"testCampoID",
      "proprieta":[ 
        { 
          "label":"testLabel",
          "idProprieta":"testProp"
        }
      ],
      "idTipoCampo":"idTipoCampoID"
    },
    { 
      "label":"testLabel2",
      "valore":[ 
        "testValore3",
        "testValore4"
      ],
      "idCampo":"testID2",
      "idCampoTP":"testCampoID2",
      "proprieta":[ 
        { 
          "label":"testLabel2",
          "idProprieta":"testProp2"
        }
      ],
      "idTipoCampo":"idTipoCampoID2"
    }
  ]
}

Is even possibile make a query like this?

SELECT customfield from procedura WHERE customfield->'campi' @> '[{"label":"testLabel3"}]'

But with testLabel3 with like wildcards: testLabel%

Another question, is even possibile make a query for get the object(s) "campi" with a "valore" of "testValore"?

My dream query was:

SELECT customfield from procedura WHERE customfield->'campi' @> '[{"label":"testLabel%"}]'

With % as wildcard

EDIT:

I faund a way to make some simple query:

SELECT customfield FROM procedura, jsonb_array_elements(procedura.customfield #> '{campi}') obj
WHERE  obj->>'idCampoTP' LIKE 'testCampoID3%' group by procedura.id;

but i cant figure how to search in valore field sub-array

EDIT:

I found this way, but to me seem a crap solution

SELECT customfield FROM procedura, jsonb_array_elements(procedura.customfield #> '{campi}') obj
WHERE  obj->>'valore' LIKE '%stValore5%' group by procedura.id;

Yes it works:)

For filtering of type 'testValore' as you have already mentioned in you question

data->'campi' @> '[{"label":"testLabel3"}]';

For extracting id with valore of type 'testValore'

data->'campi' @> '[{"valore": ["testValore"]}]';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM