Correct xpath when reading JSON out of MYSQL DB using common_schema.extract_json - mysql

I am creating a query to re-use periodically to pull data out of a MySQL database (not for use in production code) and want to display values from a JSON object as columns. I installed common_schema and have been using the extract_json function but I can't find the correct xpath to use to get the field I want, I always get null. The query I am using currently is below:
SELECT common_schema.extract_json_value(stores.info,'/Region') as "Sales Region" FROM stores
An example of the JSON object stored in stores.info is below:
{"Town":"HDM","Post Code":"003408","Region":"FGH","OutletCode":"AB43G","CustomerCode":"15134158"}
What xpath do I need to access, for example Region. If the path is correct why is it returning NULL?

Related

MYSQL Json query

I have a JSON array of objects in a MySQL table that I am trying to see if there is a way to query and just pull the data. For example.
JSON Array Object
email_address_dump
[{"value":"a123#yahoo.com","type":"personal"},{"value":"all123#hotmail.com","type":"personal"},{"value":"car_sq5#indeedemail.com","type":"personal"}]
is there a way to query out just the email address? so that the results can be something like this?
a123#yahoo.com, all123#hotmail.com, car_sq5#indeedemail.com
I am not trying to search within the column, I know that with JSON Obtains you can use a where clause, this is more of a JSON Extract.
I was able to solve this by using JSON Extract from MySQL.
json_extract(c.email_address_dump, ''$[*].value') as EmailAddressArray,

Extract certain members of JSON array in MySQL

I have a table in MySQL where each row contains JSON returned from another system. The JSON will look something like:
[{"userId": "Dave"},{"userId": "Mary", "errorCode" : "DB Fail"}, {"userId": "Lorenza", "errorCode": "Web Error"}]
and I'm only interested in the members of the array containing an error code. In the future, these will be parsed into seperate rows of their own table, but in the meantime does MySql offer a way to extract only these with an errorCode?
I can use JSON_EXTRACT to extract the errorCodes only
JSON_EXTRACT(jsonData, '$[*].errorCode') AS errorCodes
but I really want the rest of the member (userId in the example above)
You could use the JSON_CONTAINS function to find the records with errorCode and then then use JSON_EXTRACT on those records. Put the JSON_CONTAINS in the where clause
I don't think you could do this with a single query without known boundaries of the number of elements, but you could use a stored procedure to run a loop.
e.g. each iteration runs LOCATE to find the position of "errorCode", and uses that location to run SUBSTR and/or SUBSTRING_INDEX to get the userid value and append it to another variable. The looped variable would just be the offset used in the LOCATE query.

CodeIgniter - use MySQL 5.7 JSON_CONTAINS function

So, I have a list of "whitelisted" countries (eg. ['PT', 'US', 'UK', 'ES']) on a column of a table, and I want to check if the user's country (eg. 'US') is whitelisted, in order to show the user the row's content.
I searched and the best and easiest way I found was to compile the whitelisted list into a JSON array, make the column JSON type and use the JSON_CONTAINS function present on MySQL 5.7+
However, I can't figure out how to implement that with CI's database library.
How can I use CI's DB lib to use MySQL's functions? Would there be a better way to achieve this instead of JSON array?
You can use
$this->db->where("(JSON_CONTAINS(field,'[\"US\"]')) > ",0);
The codeigniter where clause required an operator. If we provide an operator codeigniter will ignore IS NULL

Dynamic field name query using N1QL

I'm having a use case here which I can't seem to solve. Basically, I need to create a webservice where users may query the couchbase cluster "dynamically". Indeed, i'm storing metadata of different files, and the "creation" of this metadata is up to the user : I don't have specific fields in my Java POJO, i'm inserting a MAP which gets inserted as a nested object in couchbase.
Now the query I need is pretty simple on paper and looks something like this :
#Query("#{#n1ql.selectEntity} WHERE #{#n1ql.filter} AND $1 = $2")
List<FileMetadata> findListMetadata(String pKey, String pValue);
But it doesn't seem to work, $1 doesn't seem to ever get replaced by the pKey variable.
I'm using CouchBase 4.5 with the Spring Data connector.
Any ideas on how to solve that use case ?
You need to dynamically generate the query string, so that pKey is inserted into the query string and pValue is passed as a parameter (as you are doing).

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.