1 # -*- coding: utf-8 -*-
3 from django.conf import settings
8 from librarian import dcparser
9 from librarian.parser import WLDocument
10 from lxml import etree
11 import catalogue.models
12 from pdcounter.models import Author as PDCounterAuthor, BookStub as PDCounterBook
13 from itertools import chain
16 log = logging.getLogger('search')
21 log = logging.getLogger('search')
23 class SolrIndex(object):
24 def __init__(self, mode=None):
25 self.index = custom.CustomSolrInterface(settings.SOLR, mode=mode)
28 class Snippets(object):
30 This class manages snippet files for indexed object (book)
31 the snippets are concatenated together, and their positions and
32 lengths are kept in lucene index fields.
34 SNIPPET_DIR = "snippets"
36 def __init__(self, book_id, revision=None):
38 os.makedirs(os.path.join(settings.SEARCH_INDEX, self.SNIPPET_DIR))
39 except OSError as exc:
40 if exc.errno == errno.EEXIST:
43 self.book_id = book_id
44 self.revision = revision
49 if self.revision: fn = "%d.%d" % (self.book_id, self.revision)
50 else: fn = "%d" % self.book_id
52 return os.path.join(settings.SEARCH_INDEX, self.SNIPPET_DIR, fn)
54 def open(self, mode='r'):
56 Open the snippet file. Call .close() afterwards.
62 if os.path.exists(self.path):
65 if not os.path.exists(self.path):
69 self.file = open(self.path, mode)
73 def add(self, snippet):
75 Append a snippet (unicode) to the snippet file.
76 Return a (position, length) tuple
78 txt = snippet.encode('utf-8')
81 pos = (self.position, l)
87 Given a tuple of (position, length) return an unicode
88 of the snippet stored there.
90 self.file.seek(pos[0], 0)
91 txt = self.file.read(pos[1]).decode('utf-8')
95 """Close snippet file"""
110 class Index(SolrIndex):
112 Class indexing books.
115 super(Index, self).__init__(mode='rw')
117 def delete_query(self, *queries):
119 index.delete(queries=...) doesn't work, so let's reimplement it
120 using deletion of list of uids.
124 if isinstance(q, sunburnt.search.LuceneQuery):
125 q = self.index.query(q)
126 q.field_limiter.update(['uid'])
130 ids = q.paginate(start=st, rows=rows).execute()
136 # print "Will delete %s" % ','.join([x for x in uids])
138 self.index.delete(uids)
143 def index_tags(self, *tags, **kw):
145 Re-index global tag list.
146 Removes all tags from index, then index them again.
147 Indexed fields include: id, name (with and without polish stems), category
149 log.debug("Indexing tags")
150 remove_only = kw.get('remove_only', False)
151 # first, remove tags from index.
155 q_id = self.index.Q(tag_id=tag.id)
157 if isinstance(tag, PDCounterAuthor):
158 q_cat = self.index.Q(tag_category='pd_author')
159 elif isinstance(tag, PDCounterBook):
160 q_cat = self.index.Q(tag_category='pd_book')
162 q_cat = self.index.Q(tag_category=tag.category)
164 q_id_cat = self.index.Q(q_id & q_cat)
165 tag_qs.append(q_id_cat)
166 self.delete_query(tag_qs)
168 q = self.index.Q(tag_id__any=True)
172 # then add them [all or just one passed]
174 tags = chain(catalogue.models.Tag.objects.exclude(category='set'), \
175 PDCounterAuthor.objects.all(), \
176 PDCounterBook.objects.all())
179 if isinstance(tag, PDCounterAuthor):
181 "tag_id": int(tag.id),
182 "tag_name": tag.name,
183 "tag_name_pl": tag.name,
184 "tag_category": 'pd_author',
185 "is_pdcounter": True,
186 "uid": "tag%d_pd_a" % tag.id
188 elif isinstance(tag, PDCounterBook):
190 "tag_id": int(tag.id),
191 "tag_name": tag.title,
192 "tag_name_pl": tag.title,
193 "tag_category": 'pd_book',
194 "is_pdcounter": True,
195 "uid": "tag%d_pd_b" % tag.id
199 "tag_id": int(tag.id),
200 "tag_name": tag.name,
201 "tag_name_pl": tag.name,
202 "tag_category": tag.category,
203 "is_pdcounter": False,
204 "uid": "tag%d" % tag.id
208 def create_book_doc(self, book):
210 Create a lucene document referring book id.
213 'book_id': int(book.id),
215 if book.parent is not None:
216 doc["parent_id"] = int(book.parent.id)
219 def remove_book(self, book_or_id, remove_snippets=True):
220 """Removes a book from search index.
221 book - Book instance."""
222 if isinstance(book_or_id, catalogue.models.Book):
223 book_id = book_or_id.id
227 self.delete_query(self.index.Q(book_id=book_id))
230 snippets = Snippets(book_id)
233 def index_book(self, book, book_info=None, overwrite=True):
236 Creates a lucene document for extracted metadata
237 and calls self.index_content() to index the contents of the book.
240 # we don't remove snippets, since they might be still needed by
241 # threads using not reopened index
242 self.remove_book(book, remove_snippets=False)
244 book_doc = self.create_book_doc(book)
245 meta_fields = self.extract_metadata(book, book_info, dc_only=['source_name', 'authors', 'translators', 'title'])
246 # let's not index it - it's only used for extracting publish date
247 if 'source_name' in meta_fields:
248 del meta_fields['source_name']
250 for n, f in meta_fields.items():
253 book_doc['uid'] = "book%s" % book_doc['book_id']
254 self.index.add(book_doc)
257 'title': meta_fields['title'],
258 'authors': meta_fields['authors'],
259 'published_date': meta_fields['published_date']
262 if 'translators' in meta_fields:
263 book_fields['translators'] = meta_fields['translators']
265 self.index_content(book, book_fields=book_fields)
270 'dramat_wierszowany_l',
271 'dramat_wierszowany_lp',
272 'dramat_wspolczesny', 'liryka_l', 'liryka_lp',
276 ignore_content_tags = [
278 'zastepnik_tekstu', 'sekcja_asterysk', 'separator_linia', 'zastepnik_wersu',
280 'naglowek_aktu', 'naglowek_sceny', 'naglowek_czesc',
283 footnote_tags = ['pa', 'pt', 'pr', 'pe']
285 skip_header_tags = ['autor_utworu', 'nazwa_utworu', 'dzielo_nadrzedne', '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}RDF']
287 published_date_re = re.compile("([0-9]+)[\]. ]*$")
289 def extract_metadata(self, book, book_info=None, dc_only=None):
291 Extract metadata from book and returns a map of fields keyed by fieldname
295 if book_info is None:
296 book_info = dcparser.parse(open(book.xml_file.path))
298 fields['slug'] = book.slug
299 fields['tags'] = [t.name for t in book.tags]
300 fields['is_book'] = True
303 for field in dcparser.BookInfo.FIELDS:
304 if dc_only and field.name not in dc_only:
306 if hasattr(book_info, field.name):
307 if not getattr(book_info, field.name):
309 # since no type information is available, we use validator
310 type_indicator = field.validator
311 if type_indicator == dcparser.as_unicode:
312 s = getattr(book_info, field.name)
315 fields[field.name] = s
316 elif type_indicator == dcparser.as_person:
317 p = getattr(book_info, field.name)
318 if isinstance(p, dcparser.Person):
321 persons = ', '.join(map(unicode, p))
322 fields[field.name] = persons
323 elif type_indicator == dcparser.as_date:
324 dt = getattr(book_info, field.name)
325 fields[field.name] = dt
329 if hasattr(book_info, 'source_name') and book_info.source_name:
330 match = self.published_date_re.search(book_info.source_name)
331 if match is not None:
332 pd = str(match.groups()[0])
334 fields["published_date"] = pd
338 # def add_gaps(self, fields, fieldname):
340 # Interposes a list of fields with gap-fields, which are indexed spaces and returns it.
341 # This allows for doing phrase queries which do not overlap the gaps (when slop is 0).
345 # yield Field(fieldname, ' ', Field.Store.NO, Field.Index.NOT_ANALYZED)
346 # return reduce(lambda a, b: a + b, zip(fields, gap()))[0:-1]
348 def get_master(self, root):
350 Returns the first master tag from an etree.
352 for master in root.iter():
353 if master.tag in self.master_tags:
356 def index_content(self, book, book_fields={}):
358 Walks the book XML and extract content from it.
359 Adds parts for each header tag and for each fragment.
361 wld = WLDocument.from_file(book.xml_file.path, parse_dublincore=False)
362 root = wld.edoc.getroot()
364 master = self.get_master(root)
368 def walker(node, ignore_tags=[]):
370 if node.tag not in ignore_tags:
371 yield node, None, None
372 if node.text is not None:
373 yield None, node.text, None
374 for child in list(node):
375 for b, t, e in walker(child):
377 yield None, None, node
379 if node.tail is not None:
380 yield None, node.tail, None
383 def fix_format(text):
384 # separator = [u" ", u"\t", u".", u";", u","]
385 if isinstance(text, list):
386 # need to join it first
387 text = filter(lambda s: s is not None, content)
388 text = u' '.join(text)
389 # for i in range(len(text)):
391 # if text[i][0] not in separator\
392 # and text[i - 1][-1] not in separator:
393 # text.insert(i, u" ")
395 return re.sub("(?m)/$", "", text)
397 def add_part(snippets, **fields):
398 doc = self.create_book_doc(book)
399 for n, v in book_fields.items():
402 doc['header_index'] = fields["header_index"]
403 doc['header_span'] = 'header_span' in fields and fields['header_span'] or 1
404 doc['header_type'] = fields['header_type']
406 doc['text'] = fields['text']
409 snip_pos = snippets.add(fields["text"])
411 doc['snippets_position'] = snip_pos[0]
412 doc['snippets_length'] = snip_pos[1]
413 if snippets.revision:
414 doc["snippets_revision"] = snippets.revision
416 if 'fragment_anchor' in fields:
417 doc["fragment_anchor"] = fields['fragment_anchor']
419 if 'themes' in fields:
420 doc['themes'] = fields['themes']
421 doc['uid'] = "part%s%s%s" % (doc['header_index'],
423 doc.get('fragment_anchor', ''))
427 if isinstance(s, unicode):
428 return s.encode('utf-8')
433 snippets = Snippets(book.id).open('w')
435 for header, position in zip(list(master), range(len(master))):
437 if header.tag in self.skip_header_tags:
439 if header.tag is etree.Comment:
446 def all_content(text):
447 for frag in fragments.values():
448 frag['text'].append(text)
450 handle_text = [all_content]
452 for start, text, end in walker(header, ignore_tags=self.ignore_content_tags):
454 if start is not None and start.tag in self.footnote_tags:
457 def collect_footnote(t):
460 handle_text.append(collect_footnote)
461 elif end is not None and footnote is not [] and end.tag in self.footnote_tags:
463 doc = add_part(snippets, header_index=position, header_type=header.tag,
464 text=u''.join(footnote),
467 #print "@ footnote text: %s" % footnote
470 # handle fragments and themes.
471 if start is not None and start.tag == 'begin':
472 fid = start.attrib['id'][1:]
473 fragments[fid] = {'text': [], 'themes': [], 'start_section': position, 'start_header': header.tag}
475 # themes for this fragment
476 elif start is not None and start.tag == 'motyw':
477 fid = start.attrib['id'][1:]
478 handle_text.append(None)
479 if start.text is not None:
480 fragments[fid]['themes'] += map(unicode.strip, map(unicode, (start.text.split(','))))
481 elif end is not None and end.tag == 'motyw':
484 elif start is not None and start.tag == 'end':
485 fid = start.attrib['id'][1:]
486 if fid not in fragments:
487 continue # a broken <end> node, skip it
488 frag = fragments[fid]
489 if frag['themes'] == []:
490 continue # empty themes list.
493 doc = add_part(snippets,
494 header_type=frag['start_header'],
495 header_index=frag['start_section'],
496 header_span=position - frag['start_section'] + 1,
498 text=fix_format(frag['text']),
499 themes=frag['themes'])
500 #print '@ FRAG %s' % frag['content']
505 if text is not None and handle_text is not []:
506 hdl = handle_text[-1]
510 # in the end, add a section text.
511 doc = add_part(snippets, header_index=position,
512 header_type=header.tag, text=fix_format(content))
513 #print '@ CONTENT: %s' % fix_format(content)
521 class SearchResult(object):
522 def __init__(self, doc, how_found=None, query=None, query_terms=None):
523 # self.search = search
526 self._processed_hits = None # processed hits
528 self.query_terms = query_terms
531 self._score = doc['score']
535 self.book_id = int(doc["book_id"])
538 self.published_date = int(doc.get("published_date"))
540 self.published_date = 0
543 header_type = doc.get("header_type", None)
544 # we have a content hit in some header of fragment
545 if header_type is not None:
546 sec = (header_type, int(doc["header_index"]))
547 header_span = doc['header_span']
548 header_span = header_span is not None and int(header_span) or 1
549 fragment = doc.get("fragment_anchor", None)
550 snippets_pos = (doc['snippets_position'], doc['snippets_length'])
551 snippets_rev = doc['snippets_revision']
553 hit = (sec + (header_span,), fragment, self._score, {
554 'how_found': how_found,
555 'snippets_pos': snippets_pos,
556 'snippets_revision': snippets_rev,
557 'themes': doc.get('themes', []),
558 'themes_pl': doc.get('themes_pl', [])
561 self._hits.append(hit)
563 def __unicode__(self):
564 return u"<SR id=%d %d(%d) hits score=%f %d snippets" % \
565 (self.book_id, len(self._hits), self._processed_hits and len(self._processed_hits) or -1, self._score, len(self.snippets))
568 return unicode(self).encode('utf-8')
572 return self._score * self.boost
574 def merge(self, other):
575 if self.book_id != other.book_id:
576 raise ValueError("this search result is or book %d; tried to merge with %d" % (self.book_id, other.book_id))
577 self._hits += other._hits
578 if other.score > self.score:
579 self._score = other._score
583 if hasattr(self, '_book'):
585 self._book = catalogue.models.Book.objects.get(id=self.book_id)
588 book = property(get_book)
599 if self._processed_hits is not None:
600 return self._processed_hits
602 # to sections and fragments
603 frags = filter(lambda r: r[self.FRAGMENT] is not None, self._hits)
605 sect = filter(lambda r: r[self.FRAGMENT] is None, self._hits)
607 # sections not covered by fragments
608 sect = filter(lambda s: 0 == len(filter(
609 lambda f: s[self.POSITION][self.POSITION_INDEX] >= f[self.POSITION][self.POSITION_INDEX]
610 and s[self.POSITION][self.POSITION_INDEX] < f[self.POSITION][self.POSITION_INDEX] + f[self.POSITION][self.POSITION_SPAN],
615 def remove_duplicates(lst, keyfn, compare):
620 if compare(els[eif], e) >= 1:
625 # remove fragments with duplicated fid's and duplicated snippets
626 frags = remove_duplicates(frags, lambda f: f[self.FRAGMENT], lambda a, b: cmp(a[self.SCORE], b[self.SCORE]))
627 # frags = remove_duplicates(frags, lambda f: f[OTHER]['snippet_pos'] and f[OTHER]['snippet_pos'] or f[FRAGMENT],
628 # lambda a, b: cmp(a[SCORE], b[SCORE]))
630 # remove duplicate sections
634 si = s[self.POSITION][self.POSITION_INDEX]
637 if sections[si]['score'] >= s[self.SCORE]:
640 m = {'score': s[self.SCORE],
641 'section_number': s[self.POSITION][self.POSITION_INDEX] + 1,
643 m.update(s[self.OTHER])
646 hits = sections.values()
650 frag = catalogue.models.Fragment.objects.get(anchor=f[self.FRAGMENT], book__id=self.book_id)
651 except catalogue.models.Fragment.DoesNotExist:
654 # Figure out if we were searching for a token matching some word in theme name.
655 themes = frag.tags.filter(category='theme')
657 if self.query_terms is not None:
658 for i in range(0, len(f[self.OTHER]['themes'])):
659 tms = f[self.OTHER]['themes'][i].split(r' +') + f[self.OTHER]['themes_pl'][i].split(' ')
660 tms = map(unicode.lower, tms)
661 for qt in self.query_terms:
663 themes_hit.add(f[self.OTHER]['themes'][i])
666 def theme_by_name(n):
667 th = filter(lambda t: t.name == n, themes)
672 themes_hit = filter(lambda a: a is not None, map(theme_by_name, themes_hit))
674 m = {'score': f[self.SCORE],
676 'section_number': f[self.POSITION][self.POSITION_INDEX] + 1,
678 'themes_hit': themes_hit
680 m.update(f[self.OTHER])
683 hits.sort(lambda a, b: cmp(a['score'], b['score']), reverse=True)
685 self._processed_hits = hits
690 def aggregate(*result_lists):
692 for rl in result_lists:
694 if r.book_id in books:
695 books[r.book_id].merge(r)
698 return books.values()
700 def __cmp__(self, other):
701 c = cmp(self.score, other.score)
703 # this is inverted, because earlier date is better
704 return cmp(other.published_date, self.published_date)
709 return len(self.hits)
711 def snippet_pos(self, idx=0):
712 return self.hits[idx]['snippets_pos']
714 def snippet_revision(self, idx=0):
716 return self.hits[idx]['snippets_revision']
721 class Search(SolrIndex):
725 def __init__(self, default_field="text"):
726 super(Search, self).__init__(mode='r')
728 # def get_tokens(self, searched, field='text', cached=None):
729 # """returns tokens analyzed by a proper (for a field) analyzer
730 # argument can be: StringReader, string/unicode, or tokens. In the last case
731 # they will just be returned (so we can reuse tokens, if we don't change the analyzer)
733 # if cached is not None and field in cached:
734 # return cached[field]
736 # if isinstance(searched, str) or isinstance(searched, unicode):
737 # searched = StringReader(searched)
738 # elif isinstance(searched, list):
742 # tokens = self.analyzer.reusableTokenStream(field, searched)
744 # while tokens.incrementToken():
745 # cta = tokens.getAttribute(CharTermAttribute.class_)
746 # toks.append(cta.toString())
748 # if cached is not None:
749 # cached[field] = toks
754 # def fuzziness(fuzzy):
755 # """Helper method to sanitize fuzziness"""
758 # if isinstance(fuzzy, float) and fuzzy > 0.0 and fuzzy <= 1.0:
763 # def make_phrase(self, tokens, field='text', slop=2, fuzzy=False):
765 # Return a PhraseQuery with a series of tokens.
768 # phrase = MultiPhraseQuery()
770 # term = Term(field, t)
771 # fuzzterm = FuzzyTermEnum(self.searcher.getIndexReader(), term, self.fuzziness(fuzzy))
775 # ft = fuzzterm.term()
777 # fuzzterms.append(ft)
778 # if not fuzzterm.next(): break
780 # phrase.add(JArray('object')(fuzzterms, Term))
784 # phrase = PhraseQuery()
785 # phrase.setSlop(slop)
787 # term = Term(field, t)
791 def make_term_query(self, query, field='text', modal=operator.or_):
793 Returns term queries joined by boolean query.
794 modal - applies to boolean query
795 fuzzy - should the query by fuzzy.
797 if query is None: query = ''
799 q = reduce(modal, map(lambda s: self.index.Q(**{field: s}),
800 query.split(r" ")), q)
804 def search_phrase(self, searched, field='text', book=False,
807 if filters is None: filters = []
808 if book: filters.append(self.index.Q(is_book=True))
810 q = self.index.query(**{field: searched})
811 q = self.apply_filters(q, filters).field_limit(score=True, all_fields=True)
813 return [SearchResult(found, how_found=u'search_phrase') for found in res]
815 def search_some(self, searched, fields, book=True,
816 filters=None, snippets=True, query_terms=None):
817 assert isinstance(fields, list)
818 if filters is None: filters = []
819 if book: filters.append(self.index.Q(is_book=True))
821 query = self.index.Q()
824 query = self.index.Q(query | self.make_term_query(searched, fld))
826 query = self.index.query(query)
827 query = self.apply_filters(query, filters).field_limit(score=True, all_fields=True)
828 res = query.execute()
829 return [SearchResult(found, how_found='search_some', query_terms=query_terms) for found in res]
831 # def search_perfect_book(self, searched, max_results=20, fuzzy=False, hint=None):
833 # Search for perfect book matches. Just see if the query matches with some author or title,
834 # taking hints into account.
836 # fields_to_search = ['authors', 'title']
839 # if not hint.should_search_for_book():
841 # fields_to_search = hint.just_search_in(fields_to_search)
842 # only_in = hint.book_filter()
844 # qrys = [self.make_phrase(self.get_tokens(searched, field=fld), field=fld, fuzzy=fuzzy) for fld in fields_to_search]
848 # top = self.searcher.search(q,
849 # self.chain_filters([only_in, self.term_filter(Term('is_book', 'true'))]),
851 # for found in top.scoreDocs:
852 # books.append(SearchResult(self, found, how_found="search_perfect_book"))
855 # def search_book(self, searched, max_results=20, fuzzy=False, hint=None):
856 # fields_to_search = ['tags', 'authors', 'title']
860 # if not hint.should_search_for_book():
862 # fields_to_search = hint.just_search_in(fields_to_search)
863 # only_in = hint.book_filter()
865 # tokens = self.get_tokens(searched, field='SIMPLE')
869 # for fld in fields_to_search:
870 # q.add(BooleanClause(self.make_term_query(tokens, field=fld,
871 # fuzzy=fuzzy), BooleanClause.Occur.SHOULD))
874 # top = self.searcher.search(q,
875 # self.chain_filters([only_in, self.term_filter(Term('is_book', 'true'))]),
877 # for found in top.scoreDocs:
878 # books.append(SearchResult(self, found, how_found="search_book"))
882 # def search_perfect_parts(self, searched, max_results=20, fuzzy=False, hint=None):
884 # Search for book parts which contains a phrase perfectly matching (with a slop of 2, default for make_phrase())
885 # some part/fragment of the book.
887 # qrys = [self.make_phrase(self.get_tokens(searched), field=fld, fuzzy=fuzzy) for fld in ['text']]
891 # flt = hint.part_filter()
895 # top = self.searcher.search(q,
896 # self.chain_filters([self.term_filter(Term('is_book', 'true'), inverse=True),
899 # for found in top.scoreDocs:
900 # books.append(SearchResult(self, found, snippets=self.get_snippets(found, q), how_found='search_perfect_parts'))
904 def search_everywhere(self, searched, query_terms=None):
906 Tries to use search terms to match different fields of book (or its parts).
907 E.g. one word can be an author survey, another be a part of the title, and the rest
908 are some words from third chapter.
911 # content only query : themes x content
912 q = self.make_term_query(searched, 'text')
913 q_themes = self.make_term_query(searched, 'themes_pl')
915 query = self.index.query(q).query(q_themes).field_limit(score=True, all_fields=True)
916 res = query.execute()
919 books.append(SearchResult(found, how_found='search_everywhere_themesXcontent', query_terms=query_terms))
921 # query themes/content x author/title/tags
922 in_content = self.index.Q()
923 in_meta = self.index.Q()
925 for fld in ['themes_pl', 'text']:
926 in_content |= self.make_term_query(searched, field=fld)
928 for fld in ['tags', 'authors', 'title']:
929 in_meta |= self.make_term_query(searched, field=fld)
931 q = in_content & in_meta
932 res = self.index.query(q).field_limit(score=True, all_fields=True).execute()
935 books.append(SearchResult(found, how_found='search_everywhere', query_terms=query_terms))
939 def get_snippets(self, searchresult, query, field='text', num=1):
941 Returns a snippet for found scoreDoc.
943 maxnum = len(searchresult)
944 if num is None or num < 0 or num > maxnum:
946 book_id = searchresult.book_id
947 revision = searchresult.snippet_revision()
948 snippets = Snippets(book_id, revision=revision)
949 snips = [None] * maxnum
953 while idx < maxnum and num > 0:
954 position, length = searchresult.snippet_pos(idx)
955 if position is None or length is None:
957 text = snippets.get((int(position),
959 snip = self.index.highlight(text=text, field=field, q=query)
966 log.error("Cannot open snippet file for book id = %d [rev=%d], %s" % (book_id, revision, e))
971 # remove verse end markers..
972 snips = map(lambda s: s and s.replace("/\n", "\n"), snips)
974 searchresult.snippets = snips
978 def hint_tags(self, query, pdcounter=True, prefix=True):
980 Return auto-complete hints for tags
984 query = query.strip()
985 for field in ['tag_name', 'tag_name_pl']:
987 q |= self.index.Q(**{field: query + "*"})
989 q |= self.make_term_query(query, field=field)
990 qu = self.index.query(q).exclude(tag_category="book")
992 return self.search_tags(qu, pdcounter=pdcounter)
994 def search_tags(self, query, filters=None, pdcounter=False):
996 Search for Tag objects using query.
998 if not filters: filters = []
1000 filters.append(~self.index.Q(is_pdcounter=True))
1001 res = self.apply_filters(query, filters).execute()
1005 is_pdcounter = doc.get('is_pdcounter', False)
1006 category = doc.get('tag_category')
1008 if is_pdcounter == True:
1009 if category == 'pd_author':
1010 tag = PDCounterAuthor.objects.get(id=doc.get('tag_id'))
1011 elif category == 'pd_book':
1012 tag = PDCounterBook.objects.get(id=doc.get('tag_id'))
1013 tag.category = 'pd_book' # make it look more lik a tag.
1015 print "Warning. cannot get pdcounter tag_id=%d from db; cat=%s" % (int(doc.get('tag_id')), category)
1017 tag = catalogue.models.Tag.objects.get(id=doc.get("tag_id"))
1018 # don't add the pdcounter tag if same tag already exists
1022 except catalogue.models.Tag.DoesNotExist: pass
1023 except PDCounterAuthor.DoesNotExist: pass
1024 except PDCounterBook.DoesNotExist: pass
1026 log.debug('search_tags: %s' % tags)
1030 def hint_books(self, query, prefix=True):
1032 Returns auto-complete hints for book titles
1033 Because we do not index 'pseudo' title-tags.
1037 query = query.strip()
1039 q |= self.index.Q(title=query + "*")
1041 q |= self.make_term_query(query, field='title')
1042 qu = self.index.query(q)
1043 only_books = self.index.Q(is_book=True)
1044 return self.search_books(qu, [only_books])
1046 def search_books(self, query, filters=None, max_results=10):
1048 Searches for Book objects using query
1051 res = self.apply_filters(query, filters).field_limit(['book_id'])
1054 bks.append(catalogue.models.Book.objects.get(id=r['book_id']))
1055 except catalogue.models.Book.DoesNotExist: pass
1058 # def make_prefix_phrase(self, toks, field):
1059 # q = MultiPhraseQuery()
1060 # for i in range(len(toks)):
1061 # t = Term(field, toks[i])
1062 # if i == len(toks) - 1:
1063 # pterms = Search.enum_to_array(PrefixTermEnum(self.searcher.getIndexReader(), t))
1073 # def term_filter(term, inverse=False):
1074 # only_term = TermsFilter()
1075 # only_term.addTerm(term)
1078 # neg = BooleanFilter()
1079 # neg.add(FilterClause(only_term, BooleanClause.Occur.MUST_NOT))
1087 def apply_filters(query, filters):
1089 Apply filters to a query
1091 if filters is None: filters = []
1092 filters = filter(lambda x: x is not None, filters)
1094 query = query.query(f)
1097 # def filtered_categories(self, tags):
1099 # Return a list of tag categories, present in tags list.
1103 # cats[t.category] = True
1104 # return cats.keys()