1 # -*- coding: utf-8 -*-
3 from django.conf import settings
4 from lucene import SimpleFSDirectory, IndexWriter, CheckIndex, \
5 File, Field, Integer, \
6 NumericField, Version, Document, JavaError, IndexSearcher, \
7 QueryParser, PerFieldAnalyzerWrapper, \
8 SimpleAnalyzer, PolishAnalyzer, ArrayList, \
9 KeywordAnalyzer, NumericRangeQuery, NumericRangeFilter, BooleanQuery, \
10 BlockJoinQuery, BlockJoinCollector, Filter, TermsFilter, ChainedFilter, \
11 HashSet, BooleanClause, Term, CharTermAttribute, \
12 PhraseQuery, MultiPhraseQuery, StringReader, TermQuery, \
13 FuzzyQuery, FuzzyTermEnum, PrefixTermEnum, Sort, Integer, \
14 SimpleHTMLFormatter, Highlighter, QueryScorer, TokenSources, TextFragment, \
15 BooleanFilter, TermsFilter, FilterClause, QueryWrapperFilter, \
16 initVM, CLASSPATH, JArray, JavaError
20 JVM = initVM(CLASSPATH)
26 from librarian import dcparser
27 from librarian.parser import WLDocument
28 import catalogue.models
29 from multiprocessing.pool import ThreadPool
30 from threading import current_thread
35 class WLAnalyzer(PerFieldAnalyzerWrapper):
37 polish = PolishAnalyzer(Version.LUCENE_34)
38 # polish_gap.setPositionIncrementGap(999)
40 simple = SimpleAnalyzer(Version.LUCENE_34)
41 # simple_gap.setPositionIncrementGap(999)
43 keyword = KeywordAnalyzer(Version.LUCENE_34)
45 # not sure if needed: there's NOT_ANALYZED meaning basically the same
47 PerFieldAnalyzerWrapper.__init__(self, polish)
49 self.addAnalyzer("tags", simple)
50 self.addAnalyzer("technical_editors", simple)
51 self.addAnalyzer("editors", simple)
52 self.addAnalyzer("url", keyword)
53 self.addAnalyzer("source_url", keyword)
54 self.addAnalyzer("source_name", simple)
55 self.addAnalyzer("publisher", simple)
56 self.addAnalyzer("author", simple)
57 self.addAnalyzer("is_book", keyword)
59 self.addAnalyzer("themes", simple)
60 self.addAnalyzer("themes_pl", polish)
62 self.addAnalyzer("tag_name", simple)
63 self.addAnalyzer("tag_name_pl", polish)
65 self.addAnalyzer("KEYWORD", keyword)
66 self.addAnalyzer("SIMPLE", simple)
67 self.addAnalyzer("POLISH", polish)
70 class IndexStore(object):
73 self.store = SimpleFSDirectory(File(settings.SEARCH_INDEX))
75 def make_index_dir(self):
77 os.makedirs(settings.SEARCH_INDEX)
78 except OSError as exc:
79 if exc.errno == errno.EEXIST:
84 class IndexChecker(IndexStore):
86 IndexStore.__init__(self)
89 checker = CheckIndex(self.store)
90 status = checker.checkIndex()
94 class Snippets(object):
95 SNIPPET_DIR = "snippets"
97 def __init__(self, book_id):
99 os.makedirs(os.path.join(settings.SEARCH_INDEX, self.SNIPPET_DIR))
100 except OSError as exc:
101 if exc.errno == errno.EEXIST:
104 self.book_id = book_id
107 def open(self, mode='r'):
110 self.file = open(os.path.join(settings.SEARCH_INDEX, self.SNIPPET_DIR, str(self.book_id)), mode)
114 def add(self, snippet):
115 txt = snippet.encode('utf-8')
118 pos = (self.position, l)
123 self.file.seek(pos[0], 0)
124 txt = self.file.read(pos[1]).decode('utf-8')
131 class Index(IndexStore):
132 def __init__(self, analyzer=None):
133 IndexStore.__init__(self)
136 analyzer = WLAnalyzer()
137 self.analyzer = analyzer
139 def open(self, analyzer=None):
141 raise Exception("Index is already opened")
142 self.index = IndexWriter(self.store, self.analyzer,\
143 IndexWriter.MaxFieldLength.LIMITED)
147 self.index.optimize()
151 self.index.optimize()
152 except JavaError, je:
153 print "Error during optimize phase, check index: %s" % je
158 def index_tags(self):
159 q = NumericRangeQuery.newIntRange("tag_id", 0, Integer.MAX_VALUE, True, True)
160 self.index.deleteDocuments(q)
162 for tag in catalogue.models.Tag.objects.all():
164 doc.add(NumericField("tag_id", Field.Store.YES, True).setIntValue(tag.id))
165 doc.add(Field("tag_name", tag.name, Field.Store.NO, Field.Index.ANALYZED))
166 doc.add(Field("tag_name_pl", tag.name, Field.Store.NO, Field.Index.ANALYZED))
167 doc.add(Field("tag_category", tag.category, Field.Store.NO, Field.Index.NOT_ANALYZED))
168 self.index.addDocument(doc)
170 def remove_book(self, book):
171 q = NumericRangeQuery.newIntRange("book_id", book.id, book.id, True, True)
172 self.index.deleteDocuments(q)
174 def index_book(self, book, overwrite=True):
176 self.remove_book(book)
178 book_doc = self.create_book_doc(book)
179 meta_fields = self.extract_metadata(book)
180 for f in meta_fields.values():
181 if isinstance(f, list) or isinstance(f, tuple):
187 self.index.addDocument(book_doc)
190 self.index_content(book, book_fields=[meta_fields['title'], meta_fields['author']])
195 'dramat_wierszowany_l',
196 'dramat_wierszowany_lp',
197 'dramat_wspolczesny', 'liryka_l', 'liryka_lp',
201 skip_header_tags = ['autor_utworu', 'nazwa_utworu', 'dzielo_nadrzedne']
203 def create_book_doc(self, book):
205 Create a lucene document connected to the book
208 doc.add(NumericField("book_id", Field.Store.YES, True).setIntValue(book.id))
209 if book.parent is not None:
210 doc.add(NumericField("parent_id", Field.Store.YES, True).setIntValue(book.parent.id))
213 def extract_metadata(self, book):
215 book_info = dcparser.parse(book.xml_file)
217 print("extract metadata for book %s id=%d, thread%d" % (book.slug, book.id, current_thread().ident))
219 fields['slug'] = Field("slug", book.slug, Field.Store.NO, Field.Index.ANALYZED_NO_NORMS)
220 fields['tags'] = self.add_gaps([Field("tags", t.name, Field.Store.NO, Field.Index.ANALYZED) for t in book.tags], 'tags')
221 fields['is_book'] = Field("is_book", 'true', Field.Store.NO, Field.Index.NOT_ANALYZED)
224 for field in dcparser.BookInfo.FIELDS:
225 if hasattr(book_info, field.name):
226 if not getattr(book_info, field.name):
228 # since no type information is available, we use validator
229 type_indicator = field.validator
230 if type_indicator == dcparser.as_unicode:
231 s = getattr(book_info, field.name)
235 fields[field.name] = Field(field.name, s, Field.Store.NO, Field.Index.ANALYZED)
236 except JavaError as je:
237 raise Exception("failed to add field: %s = '%s', %s(%s)" % (field.name, s, je.message, je.args))
238 elif type_indicator == dcparser.as_person:
239 p = getattr(book_info, field.name)
240 if isinstance(p, dcparser.Person):
243 persons = ', '.join(map(unicode, p))
244 fields[field.name] = Field(field.name, persons, Field.Store.NO, Field.Index.ANALYZED)
245 elif type_indicator == dcparser.as_date:
246 dt = getattr(book_info, field.name)
247 fields[field.name] = Field(field.name, "%04d%02d%02d" %\
248 (dt.year, dt.month, dt.day), Field.Store.NO, Field.Index.NOT_ANALYZED)
251 def get_master(self, root):
252 for master in root.iter():
253 if master.tag in self.master_tags:
256 def add_gaps(self, fields, fieldname):
259 yield Field(fieldname, ' ', Field.Store.NO, Field.Index.NOT_ANALYZED)
260 return reduce(lambda a, b: a + b, zip(fields, gap()))[0:-1]
262 def index_content(self, book, book_fields=[]):
263 wld = WLDocument.from_file(book.xml_file.path)
264 root = wld.edoc.getroot()
266 master = self.get_master(root)
272 for child in list(node):
273 for b, e in walker(child):
278 def fix_format(text):
279 return re.sub("/$", "", text, flags=re.M)
281 def add_part(snippets, **fields):
282 doc = self.create_book_doc(book)
283 for f in book_fields:
286 doc.add(NumericField('header_index', Field.Store.YES, True).setIntValue(fields["header_index"]))
287 doc.add(NumericField("header_span", Field.Store.YES, True)\
288 .setIntValue('header_span' in fields and fields['header_span'] or 1))
289 doc.add(Field('header_type', fields["header_type"], Field.Store.YES, Field.Index.NOT_ANALYZED))
291 doc.add(Field('content', fields["content"], Field.Store.NO, Field.Index.ANALYZED, \
292 Field.TermVector.WITH_POSITIONS_OFFSETS))
294 snip_pos = snippets.add(fields["content"])
295 doc.add(NumericField("snippets_position", Field.Store.YES, True).setIntValue(snip_pos[0]))
296 doc.add(NumericField("snippets_length", Field.Store.YES, True).setIntValue(snip_pos[1]))
298 if 'fragment_anchor' in fields:
299 doc.add(Field("fragment_anchor", fields['fragment_anchor'],
300 Field.Store.YES, Field.Index.NOT_ANALYZED))
302 if 'themes' in fields:
303 themes, themes_pl = zip(*[
304 (Field("themes", theme, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS),
305 Field("themes_pl", theme, Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS))
306 for theme in fields['themes']])
308 themes = self.add_gaps(themes, 'themes')
309 themes_pl = self.add_gaps(themes_pl, 'themes_pl')
319 if isinstance(s, unicode):
320 return s.encode('utf-8')
326 snippets = Snippets(book.id).open('w')
328 for header, position in zip(list(master), range(len(master))):
330 if header.tag in self.skip_header_tags:
333 content = u' '.join([t for t in header.itertext()])
334 content = fix_format(content)
336 doc = add_part(snippets, header_index=position, header_type=header.tag, content=content)
338 self.index.addDocument(doc)
340 for start, end in walker(header):
341 if start is not None and start.tag == 'begin':
342 fid = start.attrib['id'][1:]
343 fragments[fid] = {'content': [], 'themes': [], 'start_section': position, 'start_header': header.tag}
344 fragments[fid]['content'].append(start.tail)
345 elif start is not None and start.tag == 'motyw':
346 fid = start.attrib['id'][1:]
347 if start.text is not None:
348 fragments[fid]['themes'] += map(str.strip, map(give_me_utf8, start.text.split(',')))
349 fragments[fid]['content'].append(start.tail)
350 elif start is not None and start.tag == 'end':
351 fid = start.attrib['id'][1:]
352 if fid not in fragments:
353 continue # a broken <end> node, skip it
354 frag = fragments[fid]
355 if frag['themes'] == []:
356 continue # empty themes list.
360 return u' '.join(map(
361 lambda x: x == None and u'(none)' or unicode(x),
364 doc = add_part(snippets,
365 header_type=frag['start_header'],
366 header_index=frag['start_section'],
367 header_span=position - frag['start_section'] + 1,
369 content=u' '.join(filter(lambda s: s is not None, frag['content'])),
370 themes=frag['themes'])
372 self.index.addDocument(doc)
373 elif start is not None:
374 for frag in fragments.values():
375 frag['content'].append(start.text)
376 elif end is not None:
377 for frag in fragments.values():
378 frag['content'].append(end.tail)
387 def __exit__(self, type, value, tb):
391 def log_exception_wrapper(f):
396 print("Error in indexing thread: %s" % e)
397 traceback.print_exc()
402 class ReusableIndex(Index):
404 Works like index, but does not close/optimize Lucene index
405 until program exit (uses atexit hook).
406 This is usefull for importbooks command.
408 if you cannot rely on atexit, use ReusableIndex.close_reusable() yourself.
414 def open(self, analyzer=None, threads=4):
415 if ReusableIndex.index is not None:
416 self.index = ReusableIndex.index
418 print("opening index")
419 ReusableIndex.pool = ThreadPool(threads, initializer=lambda: JVM.attachCurrentThread() )
420 ReusableIndex.pool_jobs = []
421 Index.open(self, analyzer)
422 ReusableIndex.index = self.index
423 atexit.register(ReusableIndex.close_reusable)
425 def index_book(self, *args, **kw):
426 job = ReusableIndex.pool.apply_async(log_exception_wrapper(Index.index_book), (self,) + args, kw)
427 ReusableIndex.pool_jobs.append(job)
430 def close_reusable():
431 if ReusableIndex.index is not None:
432 print("wait for indexing to finish")
433 for job in ReusableIndex.pool_jobs:
435 sys.stdout.write('.')
438 ReusableIndex.pool.close()
440 ReusableIndex.index.optimize()
441 ReusableIndex.index.close()
442 ReusableIndex.index = None
448 class Search(IndexStore):
449 def __init__(self, default_field="content"):
450 IndexStore.__init__(self)
451 self.analyzer = WLAnalyzer() #PolishAnalyzer(Version.LUCENE_34)
452 ## self.analyzer = WLAnalyzer()
453 self.searcher = IndexSearcher(self.store, True)
454 self.parser = QueryParser(Version.LUCENE_34, default_field,
457 self.parent_filter = TermsFilter()
458 self.parent_filter.addTerm(Term("is_book", "true"))
460 def query(self, query):
461 return self.parser.parse(query)
463 def wrapjoins(self, query, fields=[]):
465 This functions modifies the query in a recursive way,
466 so Term and Phrase Queries contained, which match
467 provided fields are wrapped in a BlockJoinQuery,
468 and so delegated to children documents.
470 if BooleanQuery.instance_(query):
471 qs = BooleanQuery.cast_(query)
473 clause = BooleanClause.cast_(clause)
474 clause.setQuery(self.wrapjoins(clause.getQuery(), fields))
478 query.extractTerms(termset)
481 if t.field() not in fields:
483 return BlockJoinQuery(query, self.parent_filter,
484 BlockJoinQuery.ScoreMode.Total)
486 def simple_search(self, query, max_results=50):
487 """Returns (books, total_hits)
490 tops = self.searcher.search(self.query(query), max_results)
492 for found in tops.scoreDocs:
493 doc = self.searcher.doc(found.doc)
494 bks.append(catalogue.models.Book.objects.get(id=doc.get("book_id")))
495 return (bks, tops.totalHits)
497 def search(self, query, max_results=50):
498 query = self.query(query)
499 query = self.wrapjoins(query, ["content", "themes"])
501 tops = self.searcher.search(query, max_results)
503 for found in tops.scoreDocs:
504 doc = self.searcher.doc(found.doc)
505 bks.append(catalogue.models.Book.objects.get(id=doc.get("book_id")))
506 return (bks, tops.totalHits)
508 def bsearch(self, query, max_results=50):
509 q = self.query(query)
510 bjq = BlockJoinQuery(q, self.parent_filter, BlockJoinQuery.ScoreMode.Avg)
512 tops = self.searcher.search(bjq, max_results)
514 for found in tops.scoreDocs:
515 doc = self.searcher.doc(found.doc)
516 bks.append(catalogue.models.Book.objects.get(id=doc.get("book_id")))
517 return (bks, tops.totalHits)
519 # TokenStream tokenStream = analyzer.tokenStream(fieldName, reader);
520 # OffsetAttribute offsetAttribute = tokenStream.getAttribute(OffsetAttribute.class);
521 # CharTermAttribute charTermAttribute = tokenStream.getAttribute(CharTermAttribute.class);
523 # while (tokenStream.incrementToken()) {
524 # int startOffset = offsetAttribute.startOffset();
525 # int endOffset = offsetAttribute.endOffset();
526 # String term = charTermAttribute.toString();
530 class SearchResult(object):
531 def __init__(self, searcher, scoreDocs, score=None, how_found=None, snippets=None):
537 self.score = scoreDocs.score
541 stored = searcher.doc(scoreDocs.doc)
542 self.book_id = int(stored.get("book_id"))
544 header_type = stored.get("header_type")
548 sec = (header_type, int(stored.get("header_index")))
549 header_span = stored.get('header_span')
550 header_span = header_span is not None and int(header_span) or 1
552 fragment = stored.get("fragment_anchor")
554 hit = (sec + (header_span,), fragment, scoreDocs.score, {'how_found': how_found, 'snippets': snippets})
556 self.hits.append(hit)
558 def merge(self, other):
559 if self.book_id != other.book_id:
560 raise ValueError("this search result is or book %d; tried to merge with %d" % (self.book_id, other.book_id))
561 self.hits += other.hits
562 if other.score > self.score:
563 self.score = other.score
567 return catalogue.models.Book.objects.get(id=self.book_id)
569 book = property(get_book)
571 def process_hits(self):
572 frags = filter(lambda r: r[1] is not None, self.hits)
573 sect = filter(lambda r: r[1] is None, self.hits)
574 sect = filter(lambda s: 0 == len(filter(
575 lambda f: s[0][1] >= f[0][1] and s[0][1] < f[0][1] + f[0][2],
582 'header_index': s[0][1]
588 frag = catalogue.models.Fragment.objects.get(anchor=f[1])
591 'themes': frag.tags.filter(category='theme')
596 hits.sort(lambda a, b: cmp(a['score'], b['score']), reverse=True)
598 print("--- %s" % hits)
602 def __unicode__(self):
603 return u'SearchResult(book_id=%d, score=%d)' % (self.book_id, self.score)
606 def aggregate(*result_lists):
608 for rl in result_lists:
610 if r.book_id in books:
611 books[r.book_id].merge(r)
612 #print(u"already have one with score %f, and this one has score %f" % (books[book.id][0], found.score))
615 return books.values()
617 def __cmp__(self, other):
618 return cmp(self.score, other.score)
622 def __init__(self, search):
628 def book(self, book):
631 def tags(self, tags):
633 if t.category in ['author', 'title', 'epoch', 'genre', 'kind']:
634 lst = self.book_tags.get(t.category, [])
636 self.book_tags[t.category] = lst
637 if t.category in ['theme']:
638 self.part_tags.append(t)
640 def tag_filter(self, tags, field='tags'):
644 toks = self.search.get_tokens(tag.name, field=field)
645 tag_phrase = PhraseQuery()
647 tag_phrase.add(Term(field, tok))
648 q.add(BooleanClause(tag_phrase, BooleanClause.Occur.MUST))
650 return QueryWrapperFilter(q)
652 def book_filter(self):
653 tags = reduce(lambda a, b: a + b, self.book_tags.values(), [])
655 return self.tag_filter(tags)
659 def part_filter(self):
662 fs.append(self.tag_filter(self.part_tags, field='themes'))
663 if self._book is not None:
664 fs.append(NumericRangeFilter.newIntRange('book_id', self._book.id, self._book.id, True, True))
665 return MultiSearch.chain_filters(fs)
667 def should_search_for_book(self):
668 return self._book is None
670 def just_search_in(self, all):
671 """Holds logic to figure out which indexes should be search, when we have some hinst already"""
674 if field == 'author' and 'author' in self.book_tags:
676 if field == 'title' and self._book is not None:
678 if (field == 'themes' or field == 'themes_pl') and self.part_tags:
684 class MultiSearch(Search):
685 """Class capable of IMDb-like searching"""
686 def get_tokens(self, searched, field='content'):
687 """returns tokens analyzed by a proper (for a field) analyzer
688 argument can be: StringReader, string/unicode, or tokens. In the last case
689 they will just be returned (so we can reuse tokens, if we don't change the analyzer)
691 if isinstance(searched, str) or isinstance(searched, unicode):
692 searched = StringReader(searched)
693 elif isinstance(searched, list):
697 tokens = self.analyzer.reusableTokenStream(field, searched)
699 while tokens.incrementToken():
700 cta = tokens.getAttribute(CharTermAttribute.class_)
701 toks.append(cta.toString())
704 def fuzziness(self, fuzzy):
707 if isinstance(fuzzy, float) and fuzzy > 0.0 and fuzzy <= 1.0:
712 def make_phrase(self, tokens, field='content', slop=2, fuzzy=False):
714 phrase = MultiPhraseQuery()
716 term = Term(field, t)
717 fuzzterm = FuzzyTermEnum(self.searcher.getIndexReader(), term, self.fuzziness(fuzzy))
721 # print("fuzz %s" % unicode(fuzzterm.term()).encode('utf-8'))
725 if not fuzzterm.next(): break
727 phrase.add(JArray('object')(fuzzterms, Term))
731 phrase = PhraseQuery()
734 term = Term(field, t)
738 def make_term_query(self, tokens, field='content', modal=BooleanClause.Occur.SHOULD, fuzzy=False):
741 term = Term(field, t)
743 term = FuzzyQuery(term, self.fuzziness(fuzzy))
745 term = TermQuery(term)
746 q.add(BooleanClause(term, modal))
749 def content_query(self, query):
750 return BlockJoinQuery(query, self.parent_filter,
751 BlockJoinQuery.ScoreMode.Total)
753 def search_perfect_book(self, searched, max_results=20, fuzzy=False, hint=None):
754 fields_to_search = ['author', 'title']
757 if not hint.should_search_for_book():
759 fields_to_search = hint.just_search_in(fields_to_search)
760 only_in = hint.book_filter()
762 qrys = [self.make_phrase(self.get_tokens(searched, field=fld), field=fld, fuzzy=fuzzy) for fld in fields_to_search]
766 top = self.searcher.search(q,
767 self.chain_filters([only_in, self.term_filter(Term('is_book', 'true'))]),
769 for found in top.scoreDocs:
770 books.append(SearchResult(self.searcher, found))
773 def search_perfect_parts(self, searched, max_results=20, fuzzy=False, hint=None):
774 qrys = [self.make_phrase(self.get_tokens(searched), field=fld, fuzzy=fuzzy) for fld in ['content']]
778 flt = hint.part_filter()
782 top = self.searcher.search(q,
783 self.chain_filters([self.term_filter(Term('is_book', 'true'), inverse=True),
787 for found in top.scoreDocs:
788 books.append(SearchResult(self.searcher, found, snippets=self.get_snippets(found, q)))
792 def search_everywhere(self, searched, max_results=20, fuzzy=False, hint=None):
797 only_in = hint.part_filter()
799 # content only query : themes x content
802 tokens = self.get_tokens(searched)
803 if hint is None or hint.just_search_in(['themes_pl']) != []:
804 q.add(BooleanClause(self.make_term_query(tokens, field='themes_pl',
805 fuzzy=fuzzy), BooleanClause.Occur.MUST))
807 q.add(BooleanClause(self.make_term_query(tokens, field='content',
808 fuzzy=fuzzy), BooleanClause.Occur.SHOULD))
810 topDocs = self.searcher.search(q, only_in, max_results)
811 for found in topDocs.scoreDocs:
812 books.append(SearchResult(self.searcher, found))
814 # query themes/content x author/title/tags
816 in_meta = BooleanQuery()
817 in_content = BooleanQuery()
819 for fld in ['themes', 'content', 'tags', 'author', 'title']:
820 in_content.add(BooleanClause(self.make_term_query(tokens, field=fld, fuzzy=False), BooleanClause.Occur.SHOULD))
822 topDocs = self.searcher.search(q, only_in, max_results)
823 for found in topDocs.scoreDocs:
824 books.append(SearchResult(self.searcher, found))
829 def multisearch(self, query, max_results=50):
832 - (phrase) OR -> content
835 - (keywords) -> author
840 # queryreader = StringReader(query)
841 # tokens = self.get_tokens(queryreader)
843 # top_level = BooleanQuery()
844 # Should = BooleanClause.Occur.SHOULD
846 # phrase_level = BooleanQuery()
847 # phrase_level.setBoost(1.3)
849 # p_content = self.make_phrase(tokens, joined=True)
850 # p_title = self.make_phrase(tokens, 'title')
851 # p_author = self.make_phrase(tokens, 'author')
853 # phrase_level.add(BooleanClause(p_content, Should))
854 # phrase_level.add(BooleanClause(p_title, Should))
855 # phrase_level.add(BooleanClause(p_author, Should))
857 # kw_level = BooleanQuery()
859 # kw_level.add(self.make_term_query(tokens, 'author'), Should)
860 # j_themes = self.make_term_query(tokens, 'themes', joined=True)
861 # kw_level.add(j_themes, Should)
862 # kw_level.add(self.make_term_query(tokens, 'tags'), Should)
863 # j_con = self.make_term_query(tokens, joined=True)
864 # kw_level.add(j_con, Should)
866 # top_level.add(BooleanClause(phrase_level, Should))
867 # top_level.add(BooleanClause(kw_level, Should))
871 def book_search(self, query, filter=None, max_results=50, collector=None):
872 tops = self.searcher.search(query, filter, max_results)
873 #tops = self.searcher.search(p_content, max_results)
876 for found in tops.scoreDocs:
877 doc = self.searcher.doc(found.doc)
878 b = catalogue.models.Book.objects.get(id=doc.get("book_id"))
880 print "%s (%d) -> %f" % (b, b.id, found.score)
883 def get_snippets(self, scoreDoc, query, field='content'):
884 htmlFormatter = SimpleHTMLFormatter()
885 highlighter = Highlighter(htmlFormatter, QueryScorer(query))
887 stored = self.searcher.doc(scoreDoc.doc)
890 snippets = Snippets(stored.get('book_id')).open()
892 text = snippets.get((int(stored.get('snippets_position')),
893 int(stored.get('snippets_length'))))
897 tokenStream = TokenSources.getAnyTokenStream(self.searcher.getIndexReader(), scoreDoc.doc, field, self.analyzer)
898 # highlighter.getBestTextFragments(tokenStream, text, False, 10)
899 # import pdb; pdb.set_trace()
900 snip = highlighter.getBestFragments(tokenStream, text, 3, "...")
905 def enum_to_array(enum):
907 Converts a lucene TermEnum to array of Terms, suitable for
916 if not enum.next(): break
919 return JArray('object')(terms, Term)
921 def search_tags(self, query, filter=None, max_results=40):
922 tops = self.searcher.search(query, filter, max_results)
925 for found in tops.scoreDocs:
926 doc = self.searcher.doc(found.doc)
927 tag = catalogue.models.Tag.objects.get(id=doc.get("tag_id"))
929 print "%s (%d) -> %f" % (tag, tag.id, found.score)
933 def create_prefix_phrase(self, toks, field):
934 q = MultiPhraseQuery()
935 for i in range(len(toks)):
936 t = Term(field, toks[i])
937 if i == len(toks) - 1:
938 pterms = MultiSearch.enum_to_array(PrefixTermEnum(self.searcher.getIndexReader(), t))
948 def term_filter(term, inverse=False):
949 only_term = TermsFilter()
950 only_term.addTerm(term)
953 neg = BooleanFilter()
954 neg.add(FilterClause(only_term, BooleanClause.Occur.MUST_NOT))
959 def hint_tags(self, string, max_results=50):
960 toks = self.get_tokens(string, field='SIMPLE')
963 for field in ['tag_name', 'tag_name_pl']:
964 q = self.create_prefix_phrase(toks, field)
965 top.add(BooleanClause(q, BooleanClause.Occur.SHOULD))
967 no_book_cat = self.term_filter(Term("tag_category", "book"), inverse=True)
969 return self.search_tags(top, no_book_cat, max_results=max_results)
971 def hint_books(self, string, max_results=50):
972 toks = self.get_tokens(string, field='SIMPLE')
974 q = self.create_prefix_phrase(toks, 'title')
976 return self.book_search(q, self.term_filter(Term("is_book", "true")), max_results=max_results)
979 def chain_filters(filters, op=ChainedFilter.AND):
980 filters = filter(lambda x: x is not None, filters)
983 chf = ChainedFilter(JArray('object')(filters, Filter), op)
986 def filtered_categories(self, tags):
989 cats[t.category] = True