PostgreSQL json search - json

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%"
)

Related

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.

Couchbase N1QL Json Array String Wild Card Search

Is is possible to wild card search JSON String Array in a way similar to %Mr.% in N1QL . I know that exact value could be queried like 'Jon' in names where names is the JSON array
{
"use" : "official"
"names" : ["Jon", "Snow", "Smith", "Mr. Smith"]
}
But I want to search like %Mr.% in names in N1QL . Is it possible ? I have tried but it failed to do so , I have also tried Regex functions but seems like it only works for key value pair not for Array Searching.
Try this.
WHERE ANY name IN names SATISFIES name LIKE '%Mr.%' END;
Also see
https://dzone.com/articles/a-couchbase-index-technique-for-like-predicates-wi
https://dzone.com/articles/more-than-like-efficient-json-search-with-couchbas
https://dzone.com/articles/split-and-conquer-efficient-string-search-with-n1q

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.

How to compare JSON-like text in MySQL 5.6?

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.

MySQL increment value in a text field

Say I have a text field with JSON data like this:
{
"id": {
"name": "value",
"votes": 0
}
}
Is there a way to write a query which would find id and then would increment votes value?
I know i could just retrieve the JSON data update what I need and reinsert updated version, but i wonder is there a way to do this without running two queries?
UPDATE `sometable`
SET `somefield` = JSON_REPLACE(`somefield`, '$.id.votes', JSON_EXTRACT(`somefield` , '$.id.votes')+1)
WHERE ...
Edit
As of MySQL 5.7.8, MySQL supports a native JSON data type that enables efficient access to data in JSON documents.
JSON_EXTRACT will allow you to access a particular JSON element in a JSON field, while JSON_REPLACE will allow you to update it.
To specify the JSON element you wish to access, use a string with the format
'$.[top element].[sub element].[...]'
So in your case, to access id.votes, use the string '$.id.votes'.
The SQL code above demonstrates putting all this together to increment the value of a JSON field by 1.
I think for a task like this you're stuck using a plain old SELECT followed by an UPDATE (after you parse the JSON, increment the value you want, and then serialize the JSON back).
You should wrap these operations in a single transaction, and if you're using InnoDB then you might also consider using SELECT ... FOR UPDATE : http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html
This is sort of a tangent, but I thought I'd also mention that this is the type of operation that a NoSQL database like MongoDB is quite good at.