Introduction to Multi-Valued Indexes
Starting from MySQL 8.0.17, InnoDB supports the creation of multi-valued indexes (Multi-Valued Indexes) , this index is a secondary index defined on the column of the JSON storage value array. There can be multiple index records for a single data record. The specific syntax definition for this type of index:
CAST(expression AS type ARRAY), for example, CAST(data->'$.zipcode' AS UNSIGNED ARRAY). Like ordinary indexes, they can also be viewed in EXPLAIN.
Create a multi-valued index
Like other indexes, a multi-valued index can be added when creating a table, or created through ALTER TABLE or CREATE INDEX.
JSON Object Field Index
Syntax
ALTER TABLE customers ADD INDEX idx_mv_custinfo_list( ( CAST( custinfo -> '$.key' AS UNSIGNED array ) ) );
Note: There are two layers of single brackets outside the CAST syntax! , if you write one less, an error will be reported!
Test Case
PS: The cases in the article refer to the cases in the official documents and are just for testing, so the naming and other aspects are not very standardized. They must be strict in the actual development process. Follow the development specifications of the company team and don’t be lazy!
DROP TABLE IF EXISTS `customers`; /*建表语句*/ CREATE TABLE customers ( id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, modified DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, custinfo JSON NOT NULL ); /*插入写测试数据*/ INSERT INTO customers VALUES ( NULL, NOW(), '{"key":94582,"value":"asdf"}' ), ( NULL, NOW(), '{"key":94568,"value":"gjgasdasdf"}' ), ( NULL, NOW(), '{"key":94477,"value":"ghasdfsdf"}' ), ( NULL, NOW(), '{"key":94536,"value":"hagsdfgdf"}' ), ( NULL, NOW(), '{"key":94507,"value":"wasfgjdf"}' ); /*添加多值索引*/ ALTER TABLE customers ADD INDEX idx_mv_custinfo_list( ( CAST( custinfo -> '$.key' AS UNSIGNED array)) ); /*测试 MEMBER OF 语法*/ SELECT * FROM customers WHERE 94507 MEMBER OF ( custinfo -> '$.key' ); /*测试 JSON_CONTAINS 语法*/ SELECT * FROM customers WHERE JSON_CONTAINS( custinfo -> '$.key', CAST( '[94582]' AS JSON )); /*测试 JSON_OVERLAPS 语法*/ SELECT * FROM customers WHERE JSON_OVERLAPS ( custinfo -> '$.key', CAST( '[94477]' AS JSON ));
Check the execution plan and find that the index can be used:
If you need to create a multi-value index for the character type, it must be the utf8mb4 character set And the sorting rule is utf8mb4_0900_as_cs, otherwise an error will be reported. This version does not support it:
If you want to create a multi-value index for a binary binary string, the sorting rule must be binary, otherwise an error will be reported and it is not supported.
After modifying the sorting rules, the index can be added successfully:
JSON array object index
Syntax
ALTER TABLE customers ADD INDEX idx_mv_custinfo_list( ( CAST( custinfo -> '$[*].key' AS UNSIGNED array ) ) );
Note: There are two layers of single brackets outside the CAST syntax! If you write one less, an error will be reported!
Test case
DROP TABLE IF EXISTS `customers`; /*建表语句*/ CREATE TABLE customers ( id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, modified DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, custinfo JSON NOT NULL ); /*插入写测试数据*/ INSERT INTO customers VALUES ( NULL, NOW(), '[{"key":94582},{"key":94536}]'), ( NULL, NOW(), '[{"key":94568},{"key":94507},{"key":94582}]'), ( NULL, NOW(), '[{"key":94477},{"key":94507}]'), ( NULL, NOW(), '[{"key":94536}]'), ( NULL, NOW(), '[{"key":94507},{"key":94582}]'); /*添加多值索引*/ ALTER TABLE customers ADD INDEX idx_mv_custinfo_list( ( CAST( custinfo -> '$[*].key' AS UNSIGNED array)) ); /*测试 MEMBER OF 语法*/ SELECT * FROM customers WHERE 94507 MEMBER OF ( custinfo -> '$[*].key' ); /*测试 JSON_CONTAINS 语法*/ SELECT * FROM customers WHERE JSON_CONTAINS( custinfo -> '$[*].key', CAST( '[94582, 94507]' AS JSON )); /*测试 JSON_OVERLAPS 语法*/ SELECT * FROM customers WHERE JSON_OVERLAPS ( custinfo -> '$[*].key', CAST( '[94477, 94582]' AS JSON ));
View the execution plan and find that the index can be used:
Created in the combined index Multi-value index
Syntax
The syntax is similar to that of ordinary combined indexes. It also follows the leftmost matching principle:
ALTER TABLE customers ADD INDEX idx_age_custinfo$list_modified ( age, (CAST( custinfo -> '$[*].key' AS UNSIGNED ARRAY )), modified );
Note: You need to use parentheses outside the CAST syntax here. stand up!
Test case
DROP TABLE IF EXISTS `customers`; /*建表语句*/ CREATE TABLE customers ( id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, age tinyint(4) not null, modified DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, custinfo JSON NOT NULL ); /*插入写测试数据*/ INSERT INTO customers VALUES ( NULL, 21, NOW(), '[{"key":94582},{"key":94536}]'), ( NULL, 22, NOW(), '[{"key":94568},{"key":94507},{"key":94582}]'), ( NULL, 23, NOW(), '[{"key":94477},{"key":94507}]'), ( NULL, 24, NOW(), '[{"key":94536}]'), ( NULL, 25, NOW(), '[{"key":94507},{"key":94582}]'); /*添加多值索引*/ alter table customers DROP INDEX idx_age_custinfo$list_modified ; ALTER TABLE customers ADD INDEX idx_age_custinfo$list_modified ( age, (CAST( custinfo -> '$[*].key' AS UNSIGNED ARRAY )),modified ); ALTER TABLE customers ADD INDEX idx_age_custinfo$list_modified ((CAST( custinfo -> '$[*].key' AS UNSIGNED ARRAY )), age,modified ); ALTER TABLE customers ADD INDEX idx_age_custinfo$list_modified ( age,modified, (CAST( custinfo -> '$[*].key' AS UNSIGNED ARRAY )) ); /*测试 MEMBER OF 语法*/ SELECT * FROM customers WHERE 94536 MEMBER OF ( custinfo -> '$[*].key' ) and modified = '2021-08-05 10:36:34' and age = 21;
View the execution plan and find that the index can be used:
Limitations of multi-valued indexes
A multi-valued index is only allowed to contain the value of one attribute
This index currently only supports three Syntax
Currently, only three syntaxes: MEMBER OF, JSON_CONTAINS(), and JSON_OVERLAB() can use multi-value indexes.
The index value must be converted into an array
This index does not support table association
Cannot be combined with prefix index
Does not support online creation of multi-value indexes
Multi-valued indexes have clear requirements for character set type fields
This is just one of the small scenes. There are many similar scenes. The user can change it to anything, and the label can also be changed to any other attribute. As long as the thing has multiple attribute values, there is a many-to-many relationship. Then if there is no need for this attribute to be associated with other tables), you can use multi-valued indexes! Multi-valued indexes do not support table association, so it is not appropriate if you need to use this field for table association.
The above is the detailed content of How to create an index for JSON fields in MySQL. For more information, please follow other related articles on the PHP Chinese website!

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1
Easy-to-use and free code editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
