简体   繁体   中英

Is the MySQL JSON data type bad for performance for data retrieval?

Let's say I have a MySQL JSON data type called custom_properties for a media table:

在此处输入图片说明

An example of the json data stored in the custom_properties column could be:

{
 "company_id": 1, 
 "uploaded_by": "Name", 
 "document_type": "Policy", 
 "policy_signed_date": "04/04/2018"
}

In my PHP Laravel app I would do something like this:

$media = Media::where('custom_properties->company_id', Auth::user()->company_id)->orderBy('created_at', 'DESC')->get();

This would fetch all media items belonging to company 1.

My question is that lets say we have 1 million media records, would this be a bad way to fetch records in terms of performance? Can anyone shed some light on how MySQL indexes JSON data types? Is the performance significantly better if we joined separate tables and index the columns instead? I'd like to know what the actual performance difference would be.

From the MySQL official docs :

JSON documents stored in JSON columns are converted to an internal format that permits quick read access to document elements. When the server later must read a JSON value stored in this binary format, the value need not be parsed from a text representation. The binary format is structured to enable the server to look up subobjects or nested values directly by key or array index without reading all values before or after them in the document.

When they say "quick read access" they mean "better than if you stored JSON in a TEXT column."

It's still bad performance compared to an indexed lookup.

Using JSON_EXTRACT() or the -> operator is the same as searching on any other expression in MySQL, in that it causes the query to do a table-scan.

If you want better performance, you must create an index on the field you search for. That requires defining a generated column before you can make an index.

See https://mysqlserverteam.com/indexing-json-documents-via-virtual-columns/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM