I have a JSON field in mysql 8 that looks like this:
[{"key": "apples", "string_values": ["red"]}, {"key": "oranges", "string_values": ["orange"]}]
Is there a way to create an index on string values? I was hoping I could do something like this:
ALTER TABLE mytable ADD INDEX myindex(
(CAST(metadata->'$[*].string_values' AS UNSIGNED ARRAY))
);
However that returns the following error: Cannot store an array or an object in a scalar key part of the index
Fiddle for example: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=ae36a5169094ae67a290febf09f49f0c
EDIT:
I'm starting to think that the only way I can do this is with a generated column:
The following select will hit the index now.
ALTER TABLE mytable ADD string_values JSON AS (JSON_EXTRACT(metadata, '$[*].string_values[0]'));
ALTER TABLE mytable ADD INDEX idx_string_values(
(CAST(string_values->'$' AS CHAR(100) ARRAY))
);
SELECT * FROM mytable WHERE 'red' MEMBER OF(string_values->'$');