How to compare JSON-like text in MySQL 5.6? - mysql

DBMS: MySQL 5.6
I have a table tbl of which column json stores JSON-like text, the type of column is text. The column json looks like
{"id": "123", "name": "foo", "age": "20"}
I tried to select rows with the condition json.id = '123'. The query select * from tbl where json like '%"id": "123"%' failed.
I found MySQL 5.6 not supporting Json functions. So how to use Json in the WHERE clause?
Append
The schema that storing a JSON in a single column is definitely not so reasonable. But I cannot modify the schema since the business has run for a while. The version of MySQL is out of same concern. So I think a workaround is needed.

use LOCATE
Select * from tbl where
LOCATE('"id": "123"','{"id": "123", "name": "foo", "age": "20"}') >0

Try this, common_schema is used for json parsing,
SELECT json
FROM tbl
WHERE common_schema.extract_json_value(json ,'id')
LIKE "123%"

select * from tbl where json like '%\"id\": \"123\"%'
try this. I have escaped " character.

Related

Complex regex in mysql json

I have sort of cache column in mysql table column. Lets call it cacheCol It is structured as json.
cacheCol example
{
"23": {
"variationOption": "23",
"productCode": "322992-015",
"price": "150",
"qnt": ""
},
"25": {
"variationOption": "25",
"productCode": "322992-015",
"price": "150",
"qnt": "0"
},
"26": {
"variationOption": "26",
"productCode": "322992-015",
"price": "150",
"qnt": "7"
}
}
I want to select myslq row if specific json part qnt is > 0. In this example part with key 26 is only one to match.
I have worked out regex to check those values:
https://www.regextester.com/?fam=109762
But when i run my query
SELECT * FROM "tbl" WHERE ("cacheCol" REGEXP ('(?<=\"26":\{)[^\{]*"qnt":"[1-9]\d*"(?=.*\})'))
Error shows up:
Got error 'repetition-operator operand invalid' from regexp
Here is sqlfiddle to play around: http://www.sqlfiddle.com/#!9/30335a/1
(Updated sqlfiddle to cover more variations in DB)
Is there any way to work around my regex to be compatible with mysql.
Found some info about mysql 5.7 having json data type maybe where is way to get my desired result avoiding regex?
For Schema like this :
CREATE TABLE IF NOT EXISTS `tbl` (
`id` int(6) unsigned NOT NULL,
`cacheCol` TEXT NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `tbl` (`id`, `cacheCol`) VALUES
('1', '{"23":{"variationOption":"23","productCode":"322992-015","price":"150","qnt":""}}'),
('2', '{"25":{"variationOption":"25","productCode":"322992-015","price":"150","qnt":"0"}}'),
('3', '{"26":{"variationOption":"26","productCode":"322992-015","price":"150","qnt":"7"}}');
Use the following query :
SELECT *
FROM `tbl`
where cacheCol REGEXP '.?"qnt":"[1-9]\d*"';
Since the field is always going to be JSON format it is enough to search for the substring alone.
You can play around here
Also it is good idea to explore JSON datatype in Mysql if you would have many updates and reads to this object, if only for simple querying, then you can treat it as string and work with REGEX itself.
Hope it helps
You can use JSON functions like JSON_SEARCH() to find a value that is an exact match, but not a inequality match.
In MySQL 8.0, you can use the JSON_TABLE() function if your JSON were structured as an array, but not with the JSON as you have structured it as an object.
Really, if you need to use inequality expressions to search for specific fields within your data, you should not use JSON at all. You should store the data in normal rows and columns.
The more I see people misusing JSON in complex ways in MySQL, the more I am convinced it was a bad idea for MySQL to implement a JSON data type.
My rule for JSON in MySQL is: references to a JSON column anywhere but the SELECT-list are a code smell. You should use normal columns instead of JSON.
MySQL REGEXP does not support lookaheads, but you can try to achieve the same logic using something like this:
SELECT * FROM "tbl" WHERE ("cacheCol" REGEXP ('(\{[\"\:,\-a-zA-Z0-9]+\"qnt\"\:\"[1-9][0-9]*\"\})'))
Hope it helps.

Get Everything before and after a character/pattern in a string

I have a column from which i want to extract everything before and after a string. I have the following entry:
[{"model": "test.question", "pk": 123456789, "fields": {"status": "graded"}}]
[{"model": "test.question", "pk": 123456789, "fields": {"status": "answered"}}]
I want to extract the substring after "status": {" and before }}]
SQL's LIKE keyword will let you use % as a wildcard. The rest is just straight text matching. So, you should be able to use something like
WHERE columnName LIKE 'status":{"%}}]
(replace columnName with your column, of course).
However, if you have structured data in a table, you might want to reconsider your options. MySQL has a JSON data type (see https://dev.mysql.com/doc/refman/5.7/en/json.html) which may let you query more directly and correctly - for example, the approach I've described above will break if somehow a status exists that includes the string }}].
If you want the substring itself, MySQL has a substring function, detailed at MySQL has a SUBSTRING function, detailed at https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_substring , which you would use in your SELECT clause, probably using LOCATE to get the index to use in the substring. Without seeing your current SQL, it's tough to describe how that would have to be put together.

PostgreSQL json search

I'am thinking about storing some data in postgres jsonb data type. There would be a structure like
{"name": "Jhon Smith", "emails": ["smith#test.com", "agent#matrix.net"],
"phones": ["123456789", "987654321"]}.
I know, that i can search this structure like
where contact->'emails' #> '"smith#test.com"'::jsonb;
But what I need is to search my data with some LIKE operator, so
where contact->'emails' <SOME_JSON_LIKE_OPERATOR> "smith"';
I can't find if psql have something similar, maybe it does not. So, maybe I can convert contact->'emails' field to Text ('["smith#test.com", "agent#matrix.net"]') and then use simple LIKE.. How would you have solved this problem?
You can expand the json array into a recordset of text and search that in whatever manner you like:
where exists (
select 1 from json_array_elements_text(contact->'emails')
where
value like "%smith%"
)

Querying JSON Strings in AWS Redshift

I have a field varchar(65000) column in my AWS Redshift database which is used to store JSON strings. The JSON key/value pairs change frequently and I need to be able to run a daily report to retrieve all key/value data from the column.
For example:
create table test.json(json varchar(65000));
insert into test.json
select '{"animal_id": 1, "name": "harry", "animal_type": "cat", "age": 2, "location": "oakland"}' union
select '{"animal_id": 2, "name": "louie","animal_type": "dog", "age": 4}' union
select '{"animal_id": 3, "gender": "female"}' union
select '{"animal_id": 4, "size": "large"}' ;
With the above data I can write the below query to get the attributes I know are there however if a new attribute is added tomorrow, my report query will not pick up that new key/value pair. Is there any way to do a SELECT * type query on this table?
SELECT
json_extract_path_text(JSON,'animal_id') animal_id,
json_extract_path_text(JSON,'name') name,
json_extract_path_text(JSON,'animal_type') animal_type,
json_extract_path_text(JSON,'location') location,
json_extract_path_text(JSON,'age') age,
json_extract_path_text(JSON,'gender') gender,
json_extract_path_text(JSON,'size') size
FROM test.json
ORDER BY animal_id;
It is not possible to do what you want using your current schema with plain SQL.
If you can have application logic when creating your SQL query, you could dynamically create the SELECT statement.
Option A
Load the whole JSON in your app, parse it and obtain the required information this way.
Option B
When storing values in your database, parse the JSON object and add the discovered keys to another table. When querying your Redshift cluster, load this list of values and generate the appropriate SQL statement using this information.
Here's hoping these workarounds can be applied to your situation.

Querying a MySQL table with a JSON field and accessing JSON attributes

With MySQL 5.7 new features involving JSON has emerged. Among these features is the ability to query the fields in the JSON object as it is stored in the database.
My object looks like this.
{
"color": [
{"WHITE" :{ "size": [
{"S": [{"Price" : "31"},
{"discountPrice" : "13" }]}
]}},
{"BLACK" :{ "size": [
{"S": "69"},
{"M": "31"},
{"L": "55.666"}
]}}
]}
I want to query this as if it was regular tabular data, to this end I tried the following query to no avail.
select json_extract(Sku, '$.color[0]') from CRAWL.DAILYDATA;
I want to explode this into a format that looks more like a traditional RDBMS.
Any ideas?
In order to get data out of a json object as values, you need to get all the way down to the values. For instance, if you wanted to pull all of the values like they are regular RDBMS columns:
select json_extract(Sku, '$.color[0].WHITE.size[0].S[0].price') as price,
json_extract(Sku, '$.color[0].WHITE.size[0].S[0].discountPrice') as discountPrice
from CRAWL.DAILYDATA;
Of course, you need to know exactly what you're looking for in the object. This is the price of having a schema-less object like json. In principle, you could define a mysql function that would use combinations of
json_contains_path
and
json_extract
to make sure the path you are looking for exists, and otherwise it returns null. Personally though, if you want the RDBMS quality, why not just force it into a form where you can put the values directly into mysql tables? This is, of course, why RDBMS's exist. If you can't put it into such a form, you're going to be stuck with searching your json as above.