JSONB column query - sql

There is a JSONB column (some_strings) that has value like string array
---------------------
["string1","string2","string3"]
["string5"]
["string6","string7"]
-------etc-----------
Is there a way to make a query to get row where (some_strings) contain "string2" ?

This query will return records where string2 appears anywhere in the JSONB array:
SELECT *
FROM yourTable
WHERE some_strings ?& array['string2']
Documentation

Related

How to select by a word in a row from a column which has an array inside?

I have a column that contains an array of strings. I try to select the items which have a certain word in that column but I get this error:
function contains(character varying[], unknown) does not exist
This is my select query:
SELECT "schedule", COUNT("schedule") AS "count"
FROM "members" AS "member"
WHERE contains("member"."facility_id", 'DEMO')
GROUP BY "schedule";
If you want to test if an array of strings contains a specific element you need to use the contains operator which is #> but only works with arrays on both sides
WHERE member.facility_id #> array['DEMO']
To test for a single value, you can also use the any operator:
WHERE 'DEMO' = ANY(member.facility_id)

Postgresql query by json key condition

I've a table with JSON column and want to select rows where JSON key 'k' has value 'value'. Json may consist of several pairs of [K,V].
[
{"k":"esr:code","v":"800539"},
{"k":"lit","v":"yes"},
{"k":"name","v":"5 ΠΊΠΌ"},
{"k":"railway","v":"halt"},
{"k":"uic_ref","v":"2040757"}
]
I tried to use the next query, but it's wrong.
SELECT *
FROM public.node
where ((node.tags)::json->>'k' like 'name')
How I can fix it, if it's possible?)
Where node - table name, tags - json column.
You can use the JSONB contains operator #>
SELECT *
FROM public.node
where node.tags #> '[{"k","name"}]';
This will do an exact match against name. Your usage of like might indicate you are looking for a partial match - however as your like condition doesn't use a wildcard it's the same as =.
This assumes that tags is defined as jsonb (which it should be). If it's not you need to cast it: node.tags::jsonb

Postgres perform regex query on jsonb field

I have a column in my Postgres database that stores jsonb type values. Some of these values are raw strings (not a list or dictionary). I want to be able to perform a regex search on this column, such as
select * from database where jsonb_column::text ~ regex_expression.
The issue is that for values that are already strings, converting from jsonb to text adds additional escaped double quotes at the beginning and end of the value. I don't want these included in the regex query. I understand why Postgres does this, but if, say we assume all values stored in the jsonb field were jsonb strings, is there a work around? I know you can use ->> to get a value out of a jsonb dictionary, but can't figure out a solution for just jsonb strings on their own.
Once I figure out how to make this query in normal Postgres, I want to translate it into Peewee. However, any and all help with even just the initial query would be appreciated!
Just cast the json to text. Here is an example:
class Reg(Model):
key = CharField()
data = BinaryJSONField()
class Meta:
database = db
for i in range(10):
Reg.create(key='k%s' % i, data={'k%s' % i: 'v%s' % i})
# Find the row that contains the json string "k1": "v1".
expr = Reg.data.cast('text').regexp('"k1": "v1"')
query = Reg.select().where(expr)
for row in query:
print(row.key, row.data)
Prints
k1 {'k1': 'v1'}
To extract a plain string (string primitive without key name) from a JSON value (json or jsonb), you can extract the "empty path" like:
SELECT jsonb '"my string"' #>> '{}';
This also works for me (with jsonb but not with json), but it's more of a hack:
SELECT jsonb '"my string"' ->> 0
So:
SELECT * FROM tbl WHERE (jsonb_column #>> '{}') ~ 'my regex here';

Search strings in json array column

I have this PostgreSQL table:
id | something
1 | ["something1", "something2", "something3"]
2 | ["something1"]
3 | ["something2", "something4"]
I am using this query to get all the datas having the string something1 in the something column:
select * from my_table where (something)::jsonb ? 'something1'
How can i modify (or also there's a better way) this query to get all the datas that contains something1 OR something2?
You can use ?:
where something::jsonb ? 'something1'
To check for several possible values, use ?| against a text array:
where something::jsonb ?| array['something1', 'something2']
This checks if any value from the array exists in the jsonb array. If you want to check if all array elements exist in the jsonb payload, then use ?& instead.

postgres json array elements and null returns

I have a json column in a table in postgres that includes an array of objects e.g.
{"BlockData":[{"Name":"George","Age":"54","Height":"1.75"}, {"Name":"Mario","Age":"35","Height":"1.90"}]}
I am using a Select query and want to access the Name object and the value pair of the Name (George and Mario). What I am trying to to is the following:
select jsonb_array_elements(jsondoc_->'BlockData')->>'Name' from BlockData;
What I get in return is
"ERROR: cannot extract elements from a scalar
SQL state: 22023"
From what I could discover is that this issue occurs because at some rows the return is NULL. Can you please advise how can I overlap this issue?
did you try to Filter them?
t=# with t(jsondoc_) as (values('{"BlockData":[{"Name":"George","Age":"54","Height":"1.75"}, {"Name":"Mario","Age":"35","Height":"1.90"}]}'::jsonb),('{"BlockData":null}'))
select jsonb_array_elements(jsondoc_->'BlockData')->>'Name' from t
where jsondoc_->'BlockData' <> 'null';
?column?
----------
George
Mario
(2 rows)