Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support cast array function to creating multi-valued index #981

Open
elonzh opened this issue Jan 11, 2023 · 1 comment
Open

Support cast array function to creating multi-valued index #981

elonzh opened this issue Jan 11, 2023 · 1 comment

Comments

@elonzh
Copy link

elonzh commented Jan 11, 2023

Description

As of MySQL 8.0.17, InnoDB supports multi-valued indexes. A multi-valued index is a secondary index defined on a column that stores an array of values.

https://dev.mysql.com/doc/refman/8.0/en/create-index.html#create-index-multi-valued

To create a multi-valued index, we need cast a json path to array type and django.db.models.functions.comparison.Cast doesn't support this feature(obviously django should not support this).

As a workround, we can subclass the Cast function like this:

class CastArray(functions.Cast):
    template = "%(function)s(%(expressions)s AS %(db_type)s ARRAY) "

Assume we have model Journal and it has issns as JSONField(default=list) type, we can define a multi-valued index like this:

>> i = models.Index(CastArray("issns", models.CharField(max_length=15)), name="multi-value-index")
>> i.create_sql(Journal, e)
<Statement 'CREATE INDEX `multi-value-index` ON `scholardata_journal` ((CAST(`issns` AS char(15) ARRAY) ))'>
>> i.remove_sql(Journal, e)
<Statement 'DROP INDEX `multi-value-index` ON `scholardata_journal`'>

I can make a PR if this feature request is accepted.

@adamchainz
Copy link
Owner

Adding a CastArray database function sounds like a good idea 👍

Please make sure your PR includes docs, a release note, and tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants