Why index on json field not working? Django, large database
I have a model in django that has a json field that holds the nutritional values of a meal.
from django.db import models
class Meal(models.Model):
name = models.CharField(max_length=200)
portions_count = models.IntegerField()
attributes = models.JSONField()
I have a million meal records and would like to search based on attributes (gte, lte). Example atrributes field:
{"cep": 21.71, "eng": 23.37, "fep": 40.91, "pep": 27.29}
Example view:
class MealView(View):
def get(self, request, *args, **kwargs):
meals = Meal.objects.filter(attributes__eng__gte=12, attributes__cep__gte=12)[:50]
return render(request, 'meals.html', {
'meals': meals
})
...and more advanced queries (attributes, portions count and name together).
Queries can take a few seconds and if the database is overloaded, it takes longer.
We tried:
GinIndex(fields=['attributes']),
or
Index(fields=['attributes'])
But indexes was not used. (checked in postgres via sql query, pg_stat_all_indexes table and explain select)
I know that it would definitely be better if the attributes were not in JSON. Ultimately we will try to change it, but at the moment we are looking for a JSON solution.