Django postgres full text search
- Unlike relational databases, full-text search is not standardized.
- There are several open-source options like ElasticSearch, Solr, and Xapian.
- For general uses
- We can stick with the full-text search capabilities that many relational (like Postgres, MySQL, SQLite)
- And non-relational databases (like MongoDB and CouchDB) offer.
Basic Search
- In Django you’ll typically start by performing search queries with
contains
oricontains
for exact matches. - The
Q
object can be used as well to addAND
(&) orOR
(|) logical operators. - Limitations
- Only exact match is shown –> similar words excluded
- Stop word(article) all has same weight
- complex lookups not possible
from django.db.models import Q
ProductDetail.objects.filter(Q(name__icontains=query))
Quote.objects.filter(Q(name__icontains=query) | Q(quote__icontains=query))
- Eg:
- query = pony
- then ponies != pony
The search lookup(Single Field Search)
- To use the search lookup,
django.contrib.postgres
must be in your INSTALLED_APPS. - Used for Single Field Search
- Advantage
- It takes similar words into account
- ponies, pony
- It takes similar words into account
INSTALLED_APPS += ['django.contrib.postgres']
ProductDetail.objects.filter(name__search=query)
SearchVector
- To search against multiple fields and on related models, you can use the SearchVector
Entry.objects.annotate(search=SearchVector('body_text') + SearchVector('blog__tagline')).filter(search=query)
Quote.objects.annotate(search=SearchVector("name", "quote")).filter(search=query)
SearchQuery
SearchQuery translates the terms the user provides into a search query object that the database compares to a search vector. By default, all the words the user provides are passed through the stemming algorithms, and then it looks for matches for all of the resulting terms.
[Read More]