2 from sunburnt import sunburnt
6 from sunburnt import search
10 class TermVectorOptions(search.Options):
11 def __init__(self, schema, original=None):
15 self.positions = False
17 self.fields = copy.copy(original.fields)
18 self.positions = copy.copy(original.positions)
20 def update(self, positions=False, fields=None):
23 if isinstance(fields, basestring):
25 self.schema.check_fields(fields, {"stored": True})
26 self.fields.update(fields)
27 self.positions = positions
31 if self.positions or self.fields:
34 opts['tv.positions'] = 'true'
36 opts['tv.fl'] = ','.join(sorted(self.fields))
40 class CustomSolrConnection(sunburnt.SolrConnection):
41 def __init__(self, *args, **kw):
42 super(CustomSolrConnection, self).__init__(*args, **kw)
43 self.analysis_url = self.url + "analysis/field/"
45 def analyze(self, params):
46 qs = urllib.urlencode(params)
47 url = "%s?%s" % (self.analysis_url, qs)
48 if len(url) > self.max_length_get_url:
49 warnings.warn("Long query URL encountered - POSTing instead of "
50 "GETting. This query will not be cached at the HTTP layer")
51 url = self.analysis_url
55 headers={"Content-Type": "application/x-www-form-urlencoded"},
58 kwargs = dict(method="GET")
59 r, c = self.request(url, **kwargs)
61 raise sunburnt.SolrError(r, c)
65 # monkey patching sunburnt SolrSearch
66 search.SolrSearch.option_modules += ('term_vectorer',)
69 def __term_vector(self, positions=False, fields=None):
70 newself = self.clone()
71 newself.term_vectorer.update(positions, fields)
73 setattr(search.SolrSearch, 'term_vector', __term_vector)
76 def __patched__init_common_modules(self):
77 __original__init_common_modules(self)
78 self.term_vectorer = TermVectorOptions(self.schema)
79 __original__init_common_modules = search.SolrSearch._init_common_modules
80 setattr(search.SolrSearch, '_init_common_modules', __patched__init_common_modules)
83 class CustomSolrInterface(sunburnt.SolrInterface):
84 # just copied from parent and SolrConnection -> CustomSolrConnection
85 def __init__(self, url, schemadoc=None, http_connection=None, mode='', retry_timeout=-1, max_length_get_url=sunburnt.MAX_LENGTH_GET_URL):
86 self.conn = CustomSolrConnection(url, http_connection, retry_timeout, max_length_get_url)
87 self.schemadoc = schemadoc
89 self.writeable = False
94 def _analyze(self, **kwargs):
96 raise TypeError("This Solr instance is only for writing")
98 'analysis_showmatch': True
100 if 'field' in kwargs: args['analysis_fieldname'] = kwargs['field']
101 if 'text' in kwargs: args['analysis_fieldvalue'] = kwargs['text']
102 if 'q' in kwargs: args['q'] = kwargs['q']
103 if 'query' in kwargs: args['q'] = kwargs['q']
105 params = map(lambda (k, v): (k.replace('_', '.'), v), sunburnt.params_from_dict(**args))
107 content = self.conn.analyze(params)
108 doc = etree.fromstring(content)
111 def highlight(self, **kwargs):
112 doc = self._analyze(**kwargs)
113 analyzed = doc.xpath("//lst[@name='index']/arr[last()]/lst[bool/@name='match']")
116 start = int(wrd.xpath("int[@name='start']")[0].text)
117 end = int(wrd.xpath("int[@name='end']")[0].text)
118 matches.add((start, end))
121 return self.substring(kwargs['text'], matches,
122 margins=kwargs.get('margins', 30),
123 mark=kwargs.get('mark', ("<b>", "</b>")))
127 def analyze(self, **kwargs):
128 doc = self._analyze(**kwargs)
129 terms = doc.xpath("//lst[@name='index']/arr[last()]/lst/str[1]")
130 terms = map(lambda n: unicode(n.text), terms)
133 def substring(self, text, matches, margins=30, mark=("<b>", "</b>")):
137 matches_margins = map(lambda (s, e):
139 (max(0, s - margins), min(totlen, e + margins))),
141 (start, end) = matches_margins[0][1]
143 for (m, (s, e)) in matches_margins[1:]:
144 if end < s or start > e:
146 start = min(start, s)
150 snip = text[start:end]
151 matches.sort(lambda a, b: cmp(b[0], a[0]))
153 for (s, e) in matches:
155 snip = snip[:e + off] + mark[1] + snip[e + off:]
156 snip = snip[:s + off] + mark[0] + snip[s + off:]
157 # maybe break on word boundaries