forked from Fantomas42/django-blog-zinnia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch.py
144 lines (125 loc) · 4.54 KB
/
search.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
"""Search module with complex query parsing for Zinnia"""
from django.db.models import Q
from pyparsing import CaselessLiteral
from pyparsing import Combine
from pyparsing import OneOrMore
from pyparsing import Optional
from pyparsing import ParseResults
from pyparsing import StringEnd
from pyparsing import Word
from pyparsing import WordEnd
from pyparsing import alphas
from pyparsing import opAssoc
from pyparsing import operatorPrecedence
from pyparsing import printables
from pyparsing import quotedString
from pyparsing import removeQuotes
from zinnia.models.author import Author
from zinnia.models.entry import Entry
from zinnia.settings import SEARCH_FIELDS
from zinnia.settings import STOP_WORDS
def create_q(token):
"""
Creates the Q() object.
"""
meta = getattr(token, 'meta', None)
query = getattr(token, 'query', '')
wildcards = None
if isinstance(query, str): # Unicode -> Quoted string
search = query
else: # List -> No quoted string (possible wildcards)
if len(query) == 1:
search = query[0]
elif len(query) == 3:
wildcards = 'BOTH'
search = query[1]
elif len(query) == 2:
if query[0] == '*':
wildcards = 'START'
search = query[1]
else:
wildcards = 'END'
search = query[0]
# Ignore short term and stop words
if (len(search) < 3 and not search.isdigit()) or search in STOP_WORDS:
return Q()
if not meta:
q = Q()
for field in SEARCH_FIELDS:
q |= Q(**{'%s__icontains' % field: search})
return q
if meta == 'category':
if wildcards == 'BOTH':
return (Q(categories__title__icontains=search) |
Q(categories__slug__icontains=search))
elif wildcards == 'START':
return (Q(categories__title__iendswith=search) |
Q(categories__slug__iendswith=search))
elif wildcards == 'END':
return (Q(categories__title__istartswith=search) |
Q(categories__slug__istartswith=search))
else:
return (Q(categories__title__iexact=search) |
Q(categories__slug__iexact=search))
elif meta == 'author':
if wildcards == 'BOTH':
return Q(**{'authors__%s__icontains' % Author.USERNAME_FIELD:
search})
elif wildcards == 'START':
return Q(**{'authors__%s__iendswith' % Author.USERNAME_FIELD:
search})
elif wildcards == 'END':
return Q(**{'authors__%s__istartswith' % Author.USERNAME_FIELD:
search})
else:
return Q(**{'authors__%s__iexact' % Author.USERNAME_FIELD:
search})
elif meta == 'tag': # TODO: tags ignore wildcards
return Q(tags__icontains=search)
def union_q(token):
"""
Appends all the Q() objects.
"""
query = Q()
operation = 'and'
negation = False
for t in token:
if type(t) is ParseResults: # See tokens recursively
query &= union_q(t)
else:
if t in ('or', 'and'): # Set the new op and go to next token
operation = t
elif t == '-': # Next tokens needs to be negated
negation = True
else: # Append to query the token
if negation:
t = ~t
if operation == 'or':
query |= t
else:
query &= t
return query
NO_BRTS = printables.replace('(', '').replace(')', '')
SINGLE = Word(NO_BRTS.replace('*', ''))
WILDCARDS = Optional('*') + SINGLE + Optional('*') + WordEnd(wordChars=NO_BRTS)
QUOTED = quotedString.setParseAction(removeQuotes)
OPER_AND = CaselessLiteral('and')
OPER_OR = CaselessLiteral('or')
OPER_NOT = '-'
TERM = Combine(Optional(Word(alphas).setResultsName('meta') + ':') +
(QUOTED.setResultsName('query') |
WILDCARDS.setResultsName('query')))
TERM.setParseAction(create_q)
EXPRESSION = operatorPrecedence(TERM, [
(OPER_NOT, 1, opAssoc.RIGHT),
(OPER_OR, 2, opAssoc.LEFT),
(Optional(OPER_AND, default='and'), 2, opAssoc.LEFT)])
EXPRESSION.setParseAction(union_q)
QUERY = OneOrMore(EXPRESSION) + StringEnd()
QUERY.setParseAction(union_q)
def advanced_search(pattern):
"""
Parse the grammar of a pattern and build a queryset with it.
"""
query_parsed = QUERY.parseString(pattern)
return Entry.published.filter(query_parsed[0]).distinct()