Nested search without keys in jsonb in PostgreSql - sql

The question is about selection from JSON in PostgreSQL.
For example, application contains translation data in jsonb:
{
"en":{
"locale":"en",
"title":"Title",
"textShort":"Short text",
"textFull":"Full text"
}
"ru":{
"locale":"ru",
"title":"Заголовок",
"textShort":"Короткий текст",
"textFull":"Подробный текст"
}
}
This query works successfully:
select *
from content_records
where translations::json->'en'->>'title' like '%Title.';
But this query requires information about the locale, but the case is that we don't know anything about locales and search must be done for every locale, for example:
select *
from content_records
where translations::json->'any locale'->>'title' like '%Title.';
In MySQL it works as:
select *
from content_records
where LOWER(JSON_EXTRACT(translations, '$.*.title')) LIKE LOWER(:title);
There is the similar function in PostgreSQL:
json_extract_path, but it requires keywords and you can't miss the key as the symbol * does in MySQL.
The question is - how to do the selection of a nested JSON in this situation?

Unfortunately, in Postgres you have to "unnest" the keys first.
Something like this:
select t.*, cr.translations
from content_records cr
cross join lateral jsonb_object_keys(translations) as t(locale)
where lower(cr.translations -> t.locale ->> 'title') like '%title';
Note that if a title matches in more than one locale, you will get one row for each matching locale. If you don't want that, you can do the following:
select cr.*
from content_records cr
where exists (select *
from jsonb_object_keys(cr.translations) as t(locale)
where lower(cr.translations -> t.locale ->> 'title') like '%title')

Related

searching for a keyword in JSON having multiple fields

{
"TaskType": "kkkk",
"Status": "SUCCESS",
"jobID": "18056",
"DownloadFilePath": "https://abcd",
"accountId": "1234",
"customerId": "hhff"
}
This is sample data in message in notification table. I need to search for the keyword inside 3 or 4 fields out of 6 fields.
One way is to use multiple OR statements like:
SELECT message AS note
FROM notification
WHERE message::jsonb->'TaskType' LIKE '%1234%'
OR message::jsonb->'jobId' LIKE '%1234%'
OR message::jsonb->'Status' LIKE '%1234%';
The results are satisfactory, but is there a way to optimize the query in case I need to search in more fields.
you could just cast the message column to text and search inside the text:
SELECT message AS note
FROM notification
WHERE message::text like '%1234%'
You need to iterate through all key/value pairs:
select n.*
from notification n
where exists (select *
from jsonb_each_text(n.message) as m(key,value)
where key in ('TaskType', 'jobId', 'Status')
and value like '%1234%');
If you want to search in all values, just leave out the key in (..) part in the sub-select.
Searching in all values can be done using a JSON path operator in Postgres 12 or later:
select *
from notification
where message ## '$.* like_regex "1234"'
This assumes that messages is defined as jsonb - which it should be. If it's not, you need to cast it: message::jsonb

jpa postgres - query result difference with like on TEXT fields

I'm trying to make a query to search items structured as follows:
IssueCategory --* Issue (one to many)
using the following JPQL
select count(z) from IssueCategory z join z.issues x
where
lower(cast(function('lo_get', cast(x.diagnosis as integer)) as text)) like lower(concat('TEXT TO SEARCH', '%'))
where diagnosis is a Issue's String field with #Lob annotation, mapped as a text field in postgres:
CREATE TABLE issues (
...
diagnosis text,
...
)
this query produces the following query
select count(issuecateg0_.id) as col_0_0_
from issue_categories issuecateg0_
inner join issues issues1_ on issuecateg0_.id=issues1_.category_id
where lower(cast(lo_get(cast(issues1_.diagnosis as int4)) as text)) like lower(('TEXT TO SEARCH'||'%'))
Obviously in origin the "TEXT TO SEARCH" was passed as a parameter to the query.
The problem is: when I execute the JPQL query, it returns 0, but if I execute the generated query directly in postgres, I get 1.
Does anyone know of behaviours like this one?
I finally changed to the following conditions:
lower(function('encode', (function('lo_get', cast(x.diagnosis as integer))), 'escape') like lower(concat('TEXT TO SEARCH', '%'))

Querying for a specific value in a String stored in a database field

{"create_channel":"1","update_comm":"1","channels":"*"}
This is the database field which I want to query.
What would my query look like if I wanted to select all the records that have a "create_channel": "1" and a "update_comm": "1"
Additional question:
View the field below:
{"create_channel":"0","update_comm":"0","channels":[{"ch_id":"33","news":"1","parties":"1","questions ":"1","cam":"1","edit":"1","view_subs":"1","invite_subs":"1"},{"ch_id":"18","news":"1","parties":"1","questions ":"1","cam":"1","edit":"1","view_subs":"1","invite_subs":"1"}]}
How would I go about finding out all those that are subadmins in the News, parties, questions and Cams sections
You can use the ->> operator to return a member as a string:
select *
from YourTable
where YourColumn->>'create_channel' = '1' and
YourColumn->>'update_comm' = '1'
To find a user who has news, parties, questions and cam in channel 33, you can use the #> operator to check if the channels array contains those properties:
select *
from YourTable
where YourColumn->'channels' #> '[{
"ch_id":"33",
"news":"1",
"parties":"1",
"questions ":"1",
"cam":"1"
}]';

SQL Server can not find word

When I search for the Dünyas word with a LIKE operator I can see the results but when I search Dünyası word with LIKE operator, it returns no results. Problem is not ı or ü letters I tried with i and u letters as well.
This query:
select * from DbDivx where NameTurkish like '%Dünyas%' =>
returns:
Boksörün Dünyası
Geleceğin Dünyası
Su Dünyası
However:
select * from DbDivx where NameTurkish like '%Dünyası%' =>
returns nothing.
Can you help me please?
http://sqlfiddle.com/#!6/8c359/1
create table test (someName nvarchar(300))
insert into test (someName)
select N'Boksörün Dünyası'
union all select N'Geleceğin Dünyası'
union all select N'Su Dünyası'
select * from test where someName like N'%Dünyası%'
Not having any issues with the above fiddle. Note that when i inserted data without the N in front of it, the like query did not return results.
hopefully this helps!

Postgres SELECT * FROM Table where array has element

I am using Postgres 9.3.2 to make a database of contacts.
Example: If i have a row in my table that looks something like this.
{
firstName : "First name"
lastName : "Last name"
emails : ["email#one.com", "email#two.com", "email#three.com]
}
PS: firstName, lastName and emails are columns in my db and the value associated is the value for that column for that specific row.
I want to be able to query the db so that if i query for the email "email#four.com" the result is nothing but if i query for "email#two.com" the result will be the above row entry.
I dont think the query
"Select * from contactTable where emails="email#two.com""
will work. instead i want to do something like
"Select * from contactTable where emails contains "email#two.com""
any ideas on how to do this?
"Select * from contactTable where emails contains "email#two.com""
I think you want:
"Select * from contactTable where thejsonfield -> emails
Example setup, after fixing up your totally broken json:
CREATE TABLE contacts AS SELECT '{
"firstName" : "First name",
"lastName" : "Last name",
"emails" : ["email#one.com", "email#two.com", "email#three.com"]
}'::json AS myjsonfield;
The following will work in PostgreSQL 9.4, but unfortunately does not in 9.3 due to the oversight of the missing json_array_elements_text function:
select *
from contacts,
lateral json_array_elements_text(myjsonfield -> 'emails') email
where email = 'email#two.com';
For 9.3, you have to use a clumsier method to scan the json array for matching values:
select *
from contacts,
lateral json_array_length(myjsonfield -> 'emails') numemails,
lateral generate_series(0, numemails) n
WHERE json_array_element_text(myjsonfield -> 'emails', n) = 'email#two.com';
You can't use the simple IN or = ANY constructs because (at this point) PostgreSQL doesn't understand that you might have a json array, so it'll fail with:
regress=> SELECT * FROM contacts WHERE 'email#two.com' = ANY (myjsonfield->'emails');
ERROR: op ANY/ALL (array) requires array on right side
LINE 1: SELECT * FROM contacts WHERE 'email#two.com' = ANY (myjsonfi...
^
as it expects a PostgreSQL array, not a json array, and there's no convenient builtin to turn a json array into a PostgreSQL array yet.
Postgres has support for parsing JSON. Here is documentation: http://www.postgresql.org/docs/9.3/static/functions-json.html. I can't give you more detailed answer since you didn't provide exact data and schema, but it's easy to find the right function in documentation.