Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL nested JSON column search and extract sub JSON

I have a MySQL table authors with columns id, name and published_books. In this, published_books is a JSON column. With sample data,

id | name  | published_books
-----------------------------------------------------------------------
1  | Tina  |  {
   |       |    "17e9bf8f": {
   |       |         "name": "Book 1",
   |       |         "tags": [
   |       |             "self Help",
   |       |             "Social"
   |       |         ],
   |       |         "language": "English",
   |       |         "release_date": "2017-05-01"
   |       |     },
   |       |      "8e8b2470": {
   |       |          "name": "Book 2",
   |       |          "tags": [
   |       |              "Inspirational"
   |       |          ],
   |       |          "language": "English",
   |       |          "release_date": "2017-05-01"
   |       |      }
   |       |   }
-----------------------------------------------------------------------
2  | John  |   {
   |       |     "8e8b2470": {
   |       |         "name": "Book 4",
   |       |         "tags": [
   |       |             "Social"
   |       |         ],
   |       |         "language": "Tamil",
   |       |         "release_date": "2017-05-01"
   |       |     }
   |       |   }
-----------------------------------------------------------------------
3  | Keith |   {
   |       |      "17e9bf8f": {
   |       |          "name": "Book 5",
   |       |          "tags": [
   |       |              "Comedy"
   |       |          ],
   |       |          "language": "French",
   |       |          "release_date": "2017-05-01"
   |       |      },
   |       |      "8e8b2470": {
   |       |          "name": "Book 6",
   |       |          "tags": [
   |       |              "Social",
   |       |              "Life"
   |       |          ],
   |       |          "language": "English",
   |       |          "release_date": "2017-05-01"
   |       |      }
   |       |   }
-----------------------------------------------------------------------

As you see, the published_books column has nested JSON data (one level). JSON will have dynamic UUIDs as the keys and its values will be book details as a JSON.

I want to search for books with certain conditions and extract those books JSON data alone to return as the result.

The query that I've written,

select JSON_EXTRACT(published_books, '$.*') from authors 
   where JSON_CONTAINS(published_books->'$.*.language', '"English"')     
   and JSON_CONTAINS(published_books->'$.*.tags', '["Social"]');

This query performs the search and returns the entire published_books JSON. But I wanted just those books JSON alone.

The expected result,

result
--------
"17e9bf8f": {
    "name": "Book 1",
    "tags": [
        "self Help",
        "Social"
    ],
    "language": "English",
    "release_date": "2017-05-01"
}
-----------
"8e8b2470": {
    "name": "Book 6",
    "tags": [
        "Social",
        "Life"
    ],
    "language": "English",
    "release_date": "2017-05-01"
}
like image 562
Kanmaniselvan Avatar asked Nov 30 '17 05:11

Kanmaniselvan


People also ask

How can I get specific data from JSON in SQL?

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).

Does MySQL support Jsonb?

MySQL supports a native JSON data type defined by RFC 7159 that enables efficient access to data in JSON (JavaScript Object Notation) documents. The JSON data type provides these advantages over storing JSON-format strings in a string column: Automatic validation of JSON documents stored in JSON columns.


1 Answers

There is no JSON function yet that filters elements of a document or array with "WHERE"-like logic.

But this is a task that some people using JSON data may want to do, so the solution MySQL has provided is to use the JSON_TABLE() function to transform the JSON document into a format as if you had stored your data in a normal table. Then you can use a standard SQL WHERE clause to the fields returned.

You can't use this function in MySQL 5.7, but if you upgrade to MySQL 8.0 you can do this.

select authors.id, authors.name, books.* from authors,
  json_table(published_books, '$.*' 
  columns(
    bookid for ordinality,
    name text path '$.name',
    tags json path '$.tags',
    language text path '$.language',
    release_date date path '$.release_date')
  ) as books
where books.language = 'English'
  and json_search(tags, 'one', 'Social') is not null;

+----+-------+--------+--------+-------------------------+----------+--------------+
| id | name  | bookid | name   | tags                    | language | release_date |
+----+-------+--------+--------+-------------------------+----------+--------------+
|  1 | Tina  |      1 | Book 1 | ["self Help", "Social"] | English  | 2017-05-01   |
|  3 | Keith |      2 | Book 6 | ["Social", "Life"]      | English  | 2017-05-01   |
+----+-------+--------+--------+-------------------------+----------+--------------+

Note that nested JSON arrays are still difficult to work with, even with JSON_TABLE(). In this example, I exposed the tags as a JSON array, and then use JSON_SEARCH() to find the tag you wanted.

I agree with Rick James — you might as well store the data in normalized tables and columns. You think that using JSON will save you some work, but it's won't. It might make it more convenient to store the data as a single JSON document instead of multiple rows across several tables, but you just have to unravel the JSON again before you can query it the way you want.

Furthermore, if you store data in JSON, you will have to solve this sort of JSON_TABLE() expression every time you want to query the data. That's going to make a lot more work for you on an ongoing basis than if you had stored the data normally.

Frankly, I have yet to see a question on Stack Overflow about using JSON with MySQL that wouldn't lead to the conclusion that storing data in relational tables is a better idea than using JSON, if the structure of the data doesn't need to vary.

like image 66
Bill Karwin Avatar answered Sep 17 '22 17:09

Bill Karwin