I currently have a MySQL table that contains a column to store category ids. These ids are stored in a JSON string. I am looking for the most efficient method to query these JSON string for a specific id.
For example:
Table: posts
Field: cats
Here are some example values for the JSON string in the cats column:
[111, 123, 456]
[123, 345, 999]
[555, 777, 888]
Let's say I want to query for all rows that contain the id: "123" within the JSON string. I know I can accomplish this using a series of LIKE comparisons but I'm sure there is a more efficient way to query the JSON strings. Any other ideas would be much appreciated.
Thanks!
MySQL provides two operators ( -> and ->> ) to extract data from JSON columns. ->> will get the string value while -> will fetch value without quotes. As you can see ->> returns output as quoted strings, while -> returns values as they are. You can also use these operators in WHERE clause as shown below.
To query JSON data, you can use standard T-SQL. If you must create a query or report on JSON data, you can easily convert JSON data to rows and columns by calling the OPENJSON rowset function. For more information, see Convert JSON Data to Rows and Columns with OPENJSON (SQL Server).
In MySQL, the only way to index a JSON path expression is to add a virtual column that mirrors the path expression in question and build an index on the virtual column. As you can see, the title column is mapped to the $. title path expression on the properties JSON column.
cats must contains: {"ids": [2,4,6,7]}
WHERE JSON_CONTAINS(posts.cats->"$.ids", '[2]');
There is a strong discussion of storing JSON values (Storing Data in MySQL as JSON) but you could use native mysql functions for this:
Mysql official doc: https://dev.mysql.com/doc/refman/5.7/en/json-functions.html
In the
Functions That Search JSON Values
there is :
mysql> SET @j = '{"a": 1, "b": 2, "c": {"d": 4}}';
mysql> SET @j2 = '1';
mysql> SELECT JSON_CONTAINS(@j, @j2, '$.a');
or with REGEX something like:
SELECT * FROM posts where cats REGEXP '"id":"[[:<:]]123[[:>:]]"';
or with:
extract_json_value( json_text TEXT CHARSET utf8 xpath TEXT CHARSET utf8 ) RETURNS TEXT CHARSET utf8
Here a good post to deal with JSON on mysql: http://rpbouman.blogspot.com.es/2015/11/mysql-few-observations-on-json-type.html
Hope it helps!
WHERE JSON_CONTAINS(cats, ID_TO_SEARCH) = 1
Should work. MySQL 5.7 supports JSON types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With