11

I have a JSON field with one-dimensional array. In fact, in this field I have a list of some IDs, like this:

[347470, 162063, 17315, 346852, 174776, 295865, 7833, 136813]

In my queries I refer this field like this:

... AND JSON_CONTAINS(`users_actions`, 174776)=0 

My question is: should I create an index for this field, and if so - which exactly index should I use?

7
  • Do you mean like this? Commented Aug 19, 2020 at 0:10
  • It's worth noting that Postgres does a fantastic job of this on ARRAY,, HSTORE and JSON columns. MySQL not so much. Commented Aug 19, 2020 at 0:10
  • @tadman I don't think that's applicable Commented Aug 19, 2020 at 0:14
  • 1
    I don't think there's a way to index this in MySQL. You would be better off normalizing the schema. Commented Aug 19, 2020 at 0:19
  • 1
    @tadman: agree with Barmar, that technique works for JSON objects, not for arrays. Commented Aug 19, 2020 at 0:28

1 Answer 1

18

If you are running a very recent version of MySQL (8.0.17 or higher), you can use a Multi-valued index, which was designed exactly for that purpose:

A multi-valued index is a secondary index defined on a column that stores an array of values.

[...]

Multi-valued indexes are intended for indexing JSON arrays.

[...]

The optimizer uses a multi-valued index to fetch records when the following functions are specified in a WHERE clause: MEMBER OF(), JSON_CONTAINS(), JSON_OVERLAPS().

Assuming that your json array is stored in column myjs of table mytable, you can create the index like so:

CREATE INDEX myidx 
ON mytable ( (CAST(myjs AS UNSIGNED ARRAY)) );
Sign up to request clarification or add additional context in comments.

5 Comments

How do we index an array which contains objects ?
@SudhirN: this type of index supports scalar values only, hence so far we can't do that in MySQL: Cannot store an array or an object in a scalar key part of the index
so we cant have an index if its an array of objects
@SudhirN: no - as you can see in the fiddle that I linked in my comment.
I see... is that your tool, dbfiddle ? nice would love to see it evolve

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.