Debian Codegraph @

petl/io/whoosh.py

raw
1 # -*- coding: utf-8 -*-
2 from __future__ import absolute_import, print_function, division
3
4
5 import operator
6 from petl.compat import string_types, izip
7
8
9 from petl.errors import ArgumentError
10 from petl.util.base import Table, dicts
11
12
13 def fromtextindex(index_or_dirname, indexname=None, docnum_field=None):
14 """
15 Extract all documents from a Whoosh index. E.g.::
16
17 >>> import petl as etl
18 >>> import os
19 >>> # set up an index and load some documents via the Whoosh API
20 ... from whoosh.index import create_in
21 >>> from whoosh.fields import *
22 >>> schema = Schema(title=TEXT(stored=True), path=ID(stored=True),
23 ... content=TEXT)
24 >>> dirname = 'example.whoosh'
25 >>> if not os.path.exists(dirname):
26 ... os.mkdir(dirname)
27 ...
28 >>> index = create_in(dirname, schema)
29 >>> writer = index.writer()
30 >>> writer.add_document(title=u"First document", path=u"/a",
31 ... content=u"This is the first document we've added!")
32 >>> writer.add_document(title=u"Second document", path=u"/b",
33 ... content=u"The second one is even more interesting!")
34 >>> writer.commit()
35 >>> # extract documents as a table
36 ... table = etl.fromtextindex(dirname)
37 >>> table
38 +------+-------------------+
39 | path | title |
40 +======+===================+
41 | '/a' | 'First document' |
42 +------+-------------------+
43 | '/b' | 'Second document' |
44 +------+-------------------+
45
46 Keyword arguments:
47
48 index_or_dirname
49 Either an instance of `whoosh.index.Index` or a string containing the
50 directory path where the index is stored.
51 indexname
52 String containing the name of the index, if multiple indexes are stored
53 in the same directory.
54 docnum_field
55 If not None, an extra field will be added to the output table containing
56 the internal document number stored in the index. The name of the field
57 will be the value of this argument.
58
59 """
60
61 return TextIndexView(index_or_dirname, indexname=indexname,
62 docnum_field=docnum_field)
63
64
65 class TextIndexView(Table):
66
67 def __init__(self, index_or_dirname, indexname=None, docnum_field=None):
68 self.index_or_dirname = index_or_dirname
69 self.indexname = indexname
70 self.docnum_field = docnum_field
71
72 def __iter__(self):
73 return itertextindex(self.index_or_dirname, self.indexname,
74 self.docnum_field)
75
76
77 def itertextindex(index_or_dirname, indexname, docnum_field):
78 import whoosh.index
79
80 if isinstance(index_or_dirname, string_types):
81 dirname = index_or_dirname
82 index = whoosh.index.open_dir(dirname, indexname=indexname,
83 readonly=True)
84 needs_closing = True
85 elif isinstance(index_or_dirname, whoosh.index.Index):
86 index = index_or_dirname
87 needs_closing = False
88 else:
89 raise ArgumentError('expected string or index, found %r'
90 % index_or_dirname)
91
92 try:
93
94 if docnum_field is None:
95
96 # figure out the field names
97 hdr = tuple(index.schema.stored_names())
98 yield hdr
99
100 # yield all documents
101 astuple = operator.itemgetter(*index.schema.stored_names())
102 for _, stored_fields_dict in index.reader().iter_docs():
103 yield astuple(stored_fields_dict)
104
105 else:
106
107 # figure out the field names
108 hdr = (docnum_field,) + tuple(index.schema.stored_names())
109 yield hdr
110
111 # yield all documents
112 astuple = operator.itemgetter(*index.schema.stored_names())
113 for docnum, stored_fields_dict in index.reader().iter_docs():
114 yield (docnum,) + astuple(stored_fields_dict)
115
116 except:
117 raise
118
119 finally:
120 if needs_closing:
121 # close the index if we're the ones who opened it
122 index.close()
123
124
125 def totextindex(table, index_or_dirname, schema=None, indexname=None,
126 merge=False, optimize=False):
127 """
128 Load all rows from `table` into a Whoosh index. N.B., this will clear any
129 existing data in the index before loading. E.g.::
130
131 >>> import petl as etl
132 >>> import datetime
133 >>> import os
134 >>> # here is the table we want to load into an index
135 ... table = (('f0', 'f1', 'f2', 'f3', 'f4'),
136 ... ('AAA', 12, 4.3, True, datetime.datetime.now()),
137 ... ('BBB', 6, 3.4, False, datetime.datetime(1900, 1, 31)),
138 ... ('CCC', 42, 7.8, True, datetime.datetime(2100, 12, 25)))
139 >>> # define a schema for the index
140 ... from whoosh.fields import *
141 >>> schema = Schema(f0=TEXT(stored=True),
142 ... f1=NUMERIC(int, stored=True),
143 ... f2=NUMERIC(float, stored=True),
144 ... f3=BOOLEAN(stored=True),
145 ... f4=DATETIME(stored=True))
146 >>> # load index
147 ... dirname = 'example.whoosh'
148 >>> if not os.path.exists(dirname):
149 ... os.mkdir(dirname)
150 ...
151 >>> etl.totextindex(table, dirname, schema=schema)
152
153 Keyword arguments:
154
155 table
156 A table container with the data to be loaded.
157 index_or_dirname
158 Either an instance of `whoosh.index.Index` or a string containing the
159 directory path where the index is to be stored.
160 schema
161 Index schema to use if creating the index.
162 indexname
163 String containing the name of the index, if multiple indexes are stored
164 in the same directory.
165 merge
166 Merge small segments during commit?
167 optimize
168 Merge all segments together?
169
170 """
171 import whoosh.index
172 import whoosh.writing
173
174 # deal with polymorphic argument
175 if isinstance(index_or_dirname, string_types):
176 dirname = index_or_dirname
177 index = whoosh.index.create_in(dirname, schema,
178 indexname=indexname)
179 needs_closing = True
180 elif isinstance(index_or_dirname, whoosh.index.Index):
181 index = index_or_dirname
182 needs_closing = False
183 else:
184 raise ArgumentError('expected string or index, found %r'
185 % index_or_dirname)
186
187 writer = index.writer()
188 try:
189
190 for d in dicts(table):
191 writer.add_document(**d)
192 writer.commit(merge=merge, optimize=optimize,
193 mergetype=whoosh.writing.CLEAR)
194
195 except:
196 writer.cancel()
197 raise
198
199 finally:
200 if needs_closing:
201 index.close()
202
203
204 def appendtextindex(table, index_or_dirname, indexname=None, merge=True,
205 optimize=False):
206 """
207 Load all rows from `table` into a Whoosh index, adding them to any existing
208 data in the index.
209
210 Keyword arguments:
211
212 table
213 A table container with the data to be loaded.
214 index_or_dirname
215 Either an instance of `whoosh.index.Index` or a string containing the
216 directory path where the index is to be stored.
217 indexname
218 String containing the name of the index, if multiple indexes are stored
219 in the same directory.
220 merge
221 Merge small segments during commit?
222 optimize
223 Merge all segments together?
224
225 """
226 import whoosh.index
227
228 # deal with polymorphic argument
229 if isinstance(index_or_dirname, string_types):
230 dirname = index_or_dirname
231 index = whoosh.index.open_dir(dirname, indexname=indexname,
232 readonly=False)
233 needs_closing = True
234 elif isinstance(index_or_dirname, whoosh.index.Index):
235 index = index_or_dirname
236 needs_closing = False
237 else:
238 raise ArgumentError('expected string or index, found %r'
239 % index_or_dirname)
240
241 writer = index.writer()
242 try:
243
244 for d in dicts(table):
245 writer.add_document(**d)
246 writer.commit(merge=merge, optimize=optimize)
247
248 except Exception:
249 writer.cancel()
250 raise
251
252 finally:
253 if needs_closing:
254 index.close()
255
256
257 def searchtextindex(index_or_dirname, query, limit=10, indexname=None,
258 docnum_field=None, score_field=None, fieldboosts=None,
259 search_kwargs=None):
260 """
261 Search a Whoosh index using a query. E.g.::
262
263 >>> import petl as etl
264 >>> import os
265 >>> # set up an index and load some documents via the Whoosh API
266 ... from whoosh.index import create_in
267 >>> from whoosh.fields import *
268 >>> schema = Schema(title=TEXT(stored=True), path=ID(stored=True),
269 ... content=TEXT)
270 >>> dirname = 'example.whoosh'
271 >>> if not os.path.exists(dirname):
272 ... os.mkdir(dirname)
273 ...
274 >>> index = create_in('example.whoosh', schema)
275 >>> writer = index.writer()
276 >>> writer.add_document(title=u"Oranges", path=u"/a",
277 ... content=u"This is the first document we've added!")
278 >>> writer.add_document(title=u"Apples", path=u"/b",
279 ... content=u"The second document is even more "
280 ... u"interesting!")
281 >>> writer.commit()
282 >>> # demonstrate the use of searchtextindex()
283 ... table1 = etl.searchtextindex('example.whoosh', 'oranges')
284 >>> table1
285 +------+-----------+
286 | path | title |
287 +======+===========+
288 | '/a' | 'Oranges' |
289 +------+-----------+
290
291 >>> table2 = etl.searchtextindex('example.whoosh', 'doc*')
292 >>> table2
293 +------+-----------+
294 | path | title |
295 +======+===========+
296 | '/a' | 'Oranges' |
297 +------+-----------+
298 | '/b' | 'Apples' |
299 +------+-----------+
300
301 Keyword arguments:
302
303 index_or_dirname
304 Either an instance of `whoosh.index.Index` or a string containing the
305 directory path where the index is to be stored.
306 query
307 Either a string or an instance of `whoosh.query.Query`. If a string,
308 it will be parsed as a multi-field query, i.e., any terms not bound
309 to a specific field will match **any** field.
310 limit
311 Return at most `limit` results.
312 indexname
313 String containing the name of the index, if multiple indexes are stored
314 in the same directory.
315 docnum_field
316 If not None, an extra field will be added to the output table containing
317 the internal document number stored in the index. The name of the field
318 will be the value of this argument.
319 score_field
320 If not None, an extra field will be added to the output table containing
321 the score of the result. The name of the field will be the value of this
322 argument.
323 fieldboosts
324 An optional dictionary mapping field names to boosts.
325 search_kwargs
326 Any extra keyword arguments to be passed through to the Whoosh
327 `search()` method.
328
329 """
330
331 return SearchTextIndexView(index_or_dirname, query, limit=limit,
332 indexname=indexname, docnum_field=docnum_field,
333 score_field=score_field, fieldboosts=fieldboosts,
334 search_kwargs=search_kwargs)
335
336
337 def searchtextindexpage(index_or_dirname, query, pagenum, pagelen=10,
338 indexname=None, docnum_field=None, score_field=None,
339 fieldboosts=None, search_kwargs=None):
340 """
341 Search an index using a query, returning a result page.
342
343 Keyword arguments:
344
345 index_or_dirname
346 Either an instance of `whoosh.index.Index` or a string containing the
347 directory path where the index is to be stored.
348 query
349 Either a string or an instance of `whoosh.query.Query`. If a string,
350 it will be parsed as a multi-field query, i.e., any terms not bound
351 to a specific field will match **any** field.
352 pagenum
353 Number of the page to return (e.g., 1 = first page).
354 pagelen
355 Number of results per page.
356 indexname
357 String containing the name of the index, if multiple indexes are stored
358 in the same directory.
359 docnum_field
360 If not None, an extra field will be added to the output table containing
361 the internal document number stored in the index. The name of the field
362 will be the value of this argument.
363 score_field
364 If not None, an extra field will be added to the output table containing
365 the score of the result. The name of the field will be the value of this
366 argument.
367 fieldboosts
368 An optional dictionary mapping field names to boosts.
369 search_kwargs
370 Any extra keyword arguments to be passed through to the Whoosh
371 `search()` method.
372
373 """
374
375 return SearchTextIndexView(index_or_dirname, query, pagenum=pagenum,
376 pagelen=pagelen, indexname=indexname,
377 docnum_field=docnum_field,
378 score_field=score_field, fieldboosts=fieldboosts,
379 search_kwargs=search_kwargs)
380
381
382 class SearchTextIndexView(Table):
383
384 def __init__(self, index_or_dirname, query, limit=None, pagenum=None,
385 pagelen=None, indexname=None, docnum_field=None,
386 score_field=None, fieldboosts=None, search_kwargs=None):
387 self._index_or_dirname = index_or_dirname
388 self._query = query
389 self._limit = limit
390 self._pagenum = pagenum
391 self._pagelen = pagelen
392 self._indexname = indexname
393 self._docnum_field = docnum_field
394 self._score_field = score_field
395 self._fieldboosts = fieldboosts
396 self._search_kwargs = search_kwargs
397
398 def __iter__(self):
399 return itersearchindex(self._index_or_dirname, self._query,
400 self._limit, self._pagenum, self._pagelen,
401 self._indexname, self._docnum_field,
402 self._score_field, self._fieldboosts,
403 self._search_kwargs)
404
405
406 def itersearchindex(index_or_dirname, query, limit, pagenum, pagelen, indexname,
407 docnum_field, score_field, fieldboosts, search_kwargs):
408 import whoosh.index
409 import whoosh.query
410 import whoosh.qparser
411
412 if not search_kwargs:
413 search_kwargs = dict()
414
415 if isinstance(index_or_dirname, string_types):
416 dirname = index_or_dirname
417 index = whoosh.index.open_dir(dirname,
418 indexname=indexname,
419 readonly=True)
420 needs_closing = True
421 elif isinstance(index_or_dirname, whoosh.index.Index):
422 index = index_or_dirname
423 needs_closing = False
424 else:
425 raise ArgumentError('expected string or index, found %r'
426 % index_or_dirname)
427
428 try:
429
430 # figure out header
431 hdr = tuple()
432 if docnum_field is not None:
433 hdr += (docnum_field,)
434 if score_field is not None:
435 hdr += (score_field,)
436 stored_names = tuple(index.schema.stored_names())
437 hdr += stored_names
438 yield hdr
439
440 # parse the query
441 if isinstance(query, string_types):
442 # search all fields by default
443 parser = whoosh.qparser.MultifieldParser(
444 index.schema.names(),
445 index.schema,
446 fieldboosts=fieldboosts
447 )
448 query = parser.parse(query)
449 elif isinstance(query, whoosh.query.Query):
450 pass
451 else:
452 raise ArgumentError(
453 'expected string or whoosh.query.Query, found %r' % query
454 )
455
456 # make a function to turn docs into tuples
457 astuple = operator.itemgetter(*index.schema.stored_names())
458
459 with index.searcher() as searcher:
460 if limit is not None:
461 results = searcher.search(query, limit=limit,
462 **search_kwargs)
463 else:
464 results = searcher.search_page(query, pagenum,
465 pagelen=pagelen,
466 **search_kwargs)
467
468 if docnum_field is None and score_field is None:
469
470 for doc in results:
471 yield astuple(doc)
472
473 else:
474
475 for (docnum, score), doc in izip(results.items(), results):
476 row = tuple()
477 if docnum_field is not None:
478 row += (docnum,)
479 if score_field is not None:
480 row += (score,)
481 row += astuple(doc)
482 yield row
483
484 except:
485 raise
486
487 finally:
488 if needs_closing:
489 # close the index if we're the ones who opened it
490 index.close()
491
492
493 # TODO guess schema