GinIndex is a class in the django.contrib.postgres.indexes module that creates a generalized inverted index for PostgreSQL. This index is specifically designed to handle complex data types like arrays, JSONB, hstore, and full-text search.
The package library for this module is Django's official PostgreSQL Backend.
Code Example:
To use GinIndex in Django, you need to import it from django.contrib.postgres.indexes and add it to your model's Meta.indexes attribute.
from django.contrib.postgres.indexes import GinIndex from django.db import models
class MyModel(models.Model): name = models.CharField(max_length=100) tags = models.JSONField()
class Meta: indexes = [GinIndex(fields=['tags'])]
In this example, we have a model with a JSONField called "tags". We add GinIndex to the model's Meta.indexes attribute to create an inverted index for the "tags" field.
Another example could be using GinIndex for a Full Text Search field. Here, we would create the index on the TextSearchVector field rather than the actual text field.
from django.contrib.postgres.indexes import GinIndex, GinTrgmIndex from django.contrib.postgres.search import SearchVector, SearchVectorField from django.db import models
class Book(models.Model): title = models.CharField(max_length=255) author = models.CharField(max_length=255) summary = models.TextField() search_vector = SearchVectorField(null=True)
class Meta: indexes = [ GinIndex(fields=['search_vector'], name='book_idx'), GinTrgmIndex(fields=['title'], name='book_title_idx'), ]
In this example, we have a model with a TextSearchVector field called "search_vector". We add GinIndex to the model's Meta.indexes attribute, along with GinTrgmIndex (a trigram index for fuzzy text search) for the "title" field.
Overall, GinIndex is a useful tool in the Django toolkit for handling complex data types and optimizing search performance.
Python GinIndex - 34 examples found. These are the top rated real world Python examples of django.contrib.postgres.indexes.GinIndex extracted from open source projects. You can rate examples to help us improve the quality of examples.