Robert Brax
Robert Brax

Reputation: 7318

Indexing Django ArrayField or not?

Using Django 1.8 on a Postgres 9.6. One of my model has an ArrayField:

packages = ArrayField( models.CharField( max_length = 200 ), blank = True )

First question is should I add index to it ? Documentation says

At present using db_index will create a btree index. This does not offer particularly significant help to querying. A more useful index is a GIN index, which you should create using a RunSQL operation.

But it's not clear what I should do with that.

If yes, second question, is where to place "db_index = True" ? Like so?:

packages = ArrayField( models.CharField( db_index = True, max_length = 200 ), blank = True )

Upvotes: 7

Views: 3275

Answers (1)

e4c5
e4c5

Reputation: 53734

That's what the django docs say. This is what the postgresql docs say

Arrays are not sets; searching for specific array elements can be a sign of database misdesign. Consider using a separate table with a row for each item that would be an array element. This will be easier to search, and is likely to scale better for a large number of elements.

should I add index to it ? That means you are thinking of searching the array field. Postgresql advises you not to. In fact, you shouldn't really ever store arrays or CSV in a single column. What you should do is to normalize your tables.

If yes, second question, is where to place "db_index = True" ? irreverent because of above.

Upvotes: 10

Related Questions