1

Now I use SQL script like SELECT * FROM user WHERE JSON_CONTAINS(users, '[1]');But it will scan full table, it's inefficient. So I want to create the index on users column.

For example, I have a column named users, data looked like [1,2,3,4]. Please tell me how to set index on JSON array type(Generate virtual column). I had read the document on MySQL website, they all talked about to indexing in JSON object type by using JSON_EXTRACT() function.

1
  • A generated column will not help you here. You will need to normalize your table in order to run lookups efficiently. Commented Dec 2, 2017 at 11:03

2 Answers 2

2

It's now possible with MySQL 8+

Here is an example:

CREATE TABLE customers (
    id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    modified DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    custinfo JSON
    );

ALTER TABLE customers ADD INDEX comp(id, modified, 
    (CAST(custinfo->'$.zipcode' AS UNSIGNED ARRAY)) );

Use it this way:

SELECT * FROM customers 
    ->     WHERE JSON_CONTAINS(custinfo->'$.zipcode', CAST('[94507,94582]' AS JSON));

More info: https://dev.mysql.com/doc/refman/8.0/en/create-index.html

Sign up to request clarification or add additional context in comments.

Comments

1

You cannot, not at least the way you intend. At The JSON Data Type we can read:

JSON columns, like columns of other binary types, are not indexed directly; instead, you can create an index on a generated column that extracts a scalar value from the JSON column. See Indexing a Generated Column to Provide a JSON Column Index, for a detailed example.

So with the restriction comes the workaround ;-)

3 Comments

I also thought of it, maybe I should another way.
There's nothing wrong in having a generated column for this purpose, it should work just fine.
If your are indexing the many elements in a JSON array you will want to use a multi-valued index see dev.mysql.com/doc/refman/8.0/en/… and elephantdolphin.blogspot.com/2019/08/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.