Learning Django by Example(6): Search
Web January 4th, 2008
Search is one of the must-have functionalities in Gelman. Here is an SearchQuerySet based upon MySQL full text search extension. It is really cool and neat, but
- first, I don’t want to build my application against specific database extension, even though MySQL is universally picked up in the Web application.
- second, I still prefer more flexible and powerful search syntax other than what MySQL provides
- Last but not the least, I may still need Lucene or Xapian to index, search the PDF, CHM eBooks
So I home-brew the search using PLY, the Python Lex Yacc toolchain. You could check the code here, most of parser.py is just boilerplate, the interesting part is to build django.db.models.Q:
def p_expression_term(t):
‘expression : TERM’
t[0] = Q(**{‘title__icontains’:t[1]})
‘expression : TERM’
t[0] = Q(**{‘title__icontains’:t[1]})
The semantics is quite straightforward: AND(the default), OR operations are supported directly from Q; and only field title is searched. We may extend the syntax using author: like Google does later, so stay tune.
Would you find a search abstraction layer (in much the same way as you have DB abstraction layers) usfull? You would be able to integrate a fully featured search solution without locking yourself down to a specific implementation.
I did not, that is the reason I would like to build one for myself. The only issue so far is Q does not support NOT operation, so either I need to manipulate the QuerySet when parsing the query or just forget it.