Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

241
Visualizações
Matching one or more keywords with Django's Postgres full-text searching

If I search on a website with multiple keywords (and no quotes) -- such as for red car -- my expectation is that items containing "red car" exactly should be first, followed by items containing both keywords (but non-sequentially), followed by items containing one of the keywords. (I believe this is the default behavior in Lucene-like systems, but it's been a while since I've used them, so can't say for sure.)

My hope was that the Postgres full-text searching would automatically do this, but my early tests show this is not the case:

## ASSUME: items in database: <blue car>, <green car>, <red truck>

keywords = "red car"
items = ForSaleItem.objects.filter(name__search=keywords)

## RESULT: items is empty/None, whereas it should have each of 
##         the items since one keyword matches.

The hack I'm seeing is to using Django's disjunction operator, but I'm hoping there is something less-hacky. I'm also pretty sure this hack wouldn't put exact matches at the top of the list. Here's the hack:

from django.db.models import Q
keyword_query = Q()
for keyword in keywords.split(' '):
    keyword_query.add(Q(name__search=keyword), Q.OR)
items = ForSaleItem.objects.filter(keyword_query)

Is there some settings/API that I'm missing (or something implementable on the postgres side) that gets the functionality I'm expecting?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Thanks to @Dharshan for pointing me in the right direction. As he or she noted, the disjunction of SearchQuery objects will allow matching of either keyword. Additionally, to have items that contain both keywords at the top of the list -- as described in the Django full text search docs -- the SearchRank class can be used as follows:

vector = SearchVector('name')
query = SearchQuery('red') | SearchQuery('car')
items = ForSaleItem.objects.annotate(rank=SearchRank(vector, query)).order_by('-rank')
about 4 years ago · Santiago Trujillo Relatório

0

items = ForSaleItem.objects.filter(name__contains=keywords)
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda