0

I am writing a small search engine for my page in django.

my query code:

sterm = request.GET.get('searchterm')
books = Book.objects.filter(title__iregex=r"\y{0}\y".format(sterm))

One issue with this code is, if I search for "python test", it is giving me only books which have "python test" in their title. But I also need books which have only "python" or "test" in their title. I know, I can use Q. But i am in need for some efficient lookup, i am thinking about this logic:

sterms = sterm.split()
if len(sterms) == 1:
   books = Book.objects.filter(title__iregex=r"\y{0}\y".format(sterm))
else: 
   for each in sterms:
      ## how can I gather here all Q's?
   #then this?
   books = Book.objects.filter("gathered Q's with |")

how can I gather Q filters and then pass it to query? am I ok with this logic or is there more efficient and cooler way of doing this?

doniyor
  • 36,596
  • 57
  • 175
  • 260

1 Answers1

1

You can see how to make a dynamic OR'd together query at How to dynamically compose an OR query filter in Django?.

Do you need to do it this way, though? Case-insensitive regex queries are quite slow.

Are you using PostgreSQL for your data store? If so, you could investigate the full-text indexing capabilities. That would give you a much faster way to perform these kinds of searchers.

Community
  • 1
  • 1
Joel Burton
  • 1,466
  • 9
  • 11
  • yeah i am using postgresql. thanks for guidance, i think i will take this full text indexing thanks – doniyor Mar 19 '14 at 07:38