revamp search
authorJan Szejko <janek37@gmail.com>
Wed, 6 Dec 2017 10:33:30 +0000 (11:33 +0100)
committerJan Szejko <janek37@gmail.com>
Wed, 6 Dec 2017 10:33:30 +0000 (11:33 +0100)
doc/schema.xml
src/search/index.py
src/search/mock_search.py
src/search/views.py

index 17868e1..56172d3 100644 (file)
 <!--   <field name="published_date" type="tdate" stored="false" indexed="true"/>-->
    <field name="published_date" type="string" stored="true" indexed="true"/>
 
-   <field name="metadata" type="lowercase" stored="false" indexed="true"/>
+   <field name="epochs" type="lowercase" stored="false" indexed="false" multiValued="true" />
+   <field name="kinds" type="lowercase" stored="false" indexed="false" multiValued="true" />
+   <field name="genres" type="lowercase" stored="false" indexed="false" multiValued="true" />
+
+   <field name="metadata" type="text_pl" stored="false" indexed="true" multiValued="true" termPositions="true" termVectors="true" />
 
    <field name="themes" type="lowercase" stored="true" indexed="true" termVectors="true" termPositions="true" multiValued="true" />
    <field name="themes_pl" type="text_pl" stored="true" indexed="true" termVectors="true" termPositions="true" multiValued="true" />
   <copyField source="tag_name" dest="tag_name_pl"/>
   <copyField source="title" dest="title_orig"/>
 
+  <copyField source="translators" dest="metadata"/>
+  <copyField source="epochs" dest="metadata"/>
+  <copyField source="kinds" dest="metadata"/>
+  <copyField source="genres" dest="metadata"/>
+
 <!--
    <copyField source="cat" dest="text"/>
    <copyField source="name" dest="text"/>
index f9fb4b2..4f9a765 100644 (file)
@@ -240,7 +240,8 @@ class Index(SolrIndex):
             self.remove_book(book, remove_snippets=False)
 
         book_doc = self.create_book_doc(book)
-        meta_fields = self.extract_metadata(book, book_info, dc_only=['source_name', 'authors', 'translators', 'title'])
+        meta_fields = self.extract_metadata(book, book_info, dc_only=[
+            'source_name', 'authors', 'translators', 'title', 'epochs', 'kinds', 'genres'])
         # let's not index it - it's only used for extracting publish date
         if 'source_name' in meta_fields:
             del meta_fields['source_name']
@@ -257,8 +258,9 @@ class Index(SolrIndex):
             'published_date': meta_fields['published_date']
             }
 
-        if 'translators' in meta_fields:
-            book_fields['translators'] = meta_fields['translators']
+        for tag_name in ('translators', 'epochs', 'kinds', 'genres'):
+            if tag_name in meta_fields:
+                book_fields[tag_name] = meta_fields[tag_name]
 
         self.index_content(book, book_fields=book_fields)
 
@@ -726,71 +728,23 @@ class Search(SolrIndex):
 
         return q
 
-    def search_phrase(self, searched, field='text', book=False,
-                      filters=None,
-                      snippets=False):
-        if filters is None:
-            filters = []
-        if book:
-            filters.append(self.index.Q(is_book=True))
-
-        q = self.index.query(**{field: searched})
-        q = self.apply_filters(q, filters).field_limit(score=True, all_fields=True)
-        res = q.paginate(rows=100).execute()
-        return [SearchResult(found, how_found=u'search_phrase') for found in res]
-
-    def search_some(self, searched, fields, book=True,
-                    filters=None, snippets=True, query_terms=None):
-        assert isinstance(fields, list)
-        if filters is None:
-            filters = []
+    def search_words(self, words, fields, book=True):
+        filters = []
+        for word in words:
+            word_filter = None
+            for field in fields:
+                q = self.index.Q(**{field: word})
+                if word_filter is None:
+                    word_filter = q
+                else:
+                    word_filter |= q
+            filters.append(word_filter)
         if book:
-            filters.append(self.index.Q(is_book=True))
-
-        query = self.index.Q()
-
-        for fld in fields:
-            query = self.index.Q(query | self.make_term_query(searched, fld))
-
-        query = self.index.query(query)
+            query = self.index.query(is_book=True)
+        else:
+            query = self.index.query()
         query = self.apply_filters(query, filters).field_limit(score=True, all_fields=True)
-        res = query.execute()
-        return [SearchResult(found, how_found='search_some', query_terms=query_terms) for found in res]
-
-    def search_everywhere(self, searched, query_terms=None):
-        """
-        Tries to use search terms to match different fields of book (or its parts).
-        E.g. one word can be an author survey, another be a part of the title, and the rest
-        are some words from third chapter.
-        """
-        books = []
-        # content only query : themes x content
-        q = self.make_term_query(searched, 'text')
-        q_themes = self.make_term_query(searched, 'themes_pl')
-
-        query = self.index.query(q).query(q_themes).field_limit(score=True, all_fields=True)
-        res = query.execute()
-
-        for found in res:
-            books.append(SearchResult(found, how_found='search_everywhere_themesXcontent', query_terms=query_terms))
-
-        # query themes/content x author/title/tags
-        in_content = self.index.Q()
-        in_meta = self.index.Q()
-
-        for fld in ['themes_pl', 'text']:
-            in_content |= self.make_term_query(searched, field=fld)
-
-        for fld in ['tags', 'authors', 'title']:
-            in_meta |= self.make_term_query(searched, field=fld)
-
-        q = in_content & in_meta
-        res = self.index.query(q).field_limit(score=True, all_fields=True).execute()
-
-        for found in res:
-            books.append(SearchResult(found, how_found='search_everywhere', query_terms=query_terms))
-
-        return books
+        return [SearchResult(found, how_found='search_words') for found in query]
 
     def get_snippets(self, searchresult, query, field='text', num=1):
         """
index b1c8162..3bd7b93 100644 (file)
@@ -21,12 +21,10 @@ class Search(Mock):
     index = MockIndex()
 
     @staticmethod
-    def _find_some_books(snippets=False, query_terms=None, max_results=20):
+    def _find_some_books(query_terms=None, max_results=20):
         from .index import SearchResult
 
         qs = Book.objects.order_by('?')
-        if snippets:
-            qs = qs.exclude(fragments=None)
         results = []
         for book in qs[:randint(1, max_results)]:
             doc = {
@@ -34,33 +32,13 @@ class Search(Mock):
                 'book_id': book.pk,
                 'published_date': randint(1000, 1920),
                 }
-            if snippets:
-                fragment = book.fragments.order_by('?')[0]
-                doc.update({
-                    'header_type': choice(['strofa', 'akap']),
-                    'header_index': randint(100, 200),
-                    'header_span': randint(100, 200),
-                    'fragment_anchor': fragment.anchor,
-                    'snippets_position': randint(100, 200),
-                    'snippets_length': randint(100, 200),
-                    'snippets_revision': randint(1, 100),
-                    'themes_pl': fragment.tags.filter(category='theme'),
-                })
             res = SearchResult(doc, how_found='mock', query_terms=query_terms)
-            if snippets:
-                res.snippets = [fragment.short_text]
             results.append(res)
         return results
 
-    def search_phrase(self, searched, field='text', book=False, filters=None, snippets=False):
-        return self._find_some_books(snippets)
-
-    def search_some(self, searched, fields, book=True, filters=None, snippets=True, query_terms=None):
-        return self._find_some_books(snippets, query_terms)
-
     # WTF
     def search_books(self, query, filters=None, max_results=10):
-        return self._find_some_books(snippets, max_results=max_results)
+        return self._find_some_books(max_results=max_results)
 
     def search_everywhere(self, searched, query_terms=None):
         return []
index 14da6f6..8b055a4 100644 (file)
@@ -146,40 +146,34 @@ def main(request):
             'catalogue/search_too_long.html', {'prefix': query}, context_instance=RequestContext(request))
 
     query = remove_query_syntax_chars(query)
-    
-    search = Search()
 
-    theme_terms = search.index.analyze(text=query, field="themes_pl") \
-        + search.index.analyze(text=query, field="themes")
+    words = query.split()
+    if len(words) > 10:
+        query = ' '.join(words[:10])
+
+    search = Search()
 
     # change hints
     tags = search.hint_tags(query, pdcounter=True, prefix=False)
     tags = split_tags(tags)
 
-    author_results = search.search_phrase(query, 'authors', book=True)
-    translator_results = search.search_phrase(query, 'translators', book=True)
+    author_results = search.search_words(words, ['authors'])
 
-    title_results = search.search_phrase(query, 'title', book=True)
+    title_results = search.search_words(words, ['title'])
 
-    # Boost main author/title results with mixed search, and save some of its results for end of list.
-    # boost author, title results
-    author_title_mixed = search.search_some(query, ['authors', 'translators', 'title', 'tags'], query_terms=theme_terms)
+    author_title_mixed = search.search_words(words, ['authors', 'title', 'metadata'])
     author_title_rest = []
 
     for b in author_title_mixed:
-        also_in_mixed = filter(lambda ba: ba.book_id == b.book_id, author_results + translator_results + title_results)
+        also_in_mixed = filter(lambda ba: ba.book_id == b.book_id, author_results + title_results)
         for b2 in also_in_mixed:
             b2.boost *= 1.1
-        if also_in_mixed is []:
+        if not also_in_mixed:
             author_title_rest.append(b)
 
-    # Do a phrase search but a term search as well - this can give us better snippets then search_everywhere,
-    # Because the query is using only one field.
-    text_phrase = SearchResult.aggregate(
-        search.search_phrase(query, 'text', snippets=True, book=False),
-        search.search_some(query, ['text'], snippets=True, book=False, query_terms=theme_terms))
+    text_phrase = SearchResult.aggregate(search.search_words(words, ['text'], book=False))
 
-    everywhere = search.search_everywhere(query, query_terms=theme_terms)
+    everywhere = search.search_words(words, ['metadata', 'text', 'themes_pl'], book=False)
 
     def already_found(results):
         def f(e):
@@ -190,17 +184,15 @@ def main(request):
                     return True
             return False
         return f
-    f = already_found(author_results + translator_results + title_results + text_phrase)
+    f = already_found(author_results + title_results + text_phrase)
     everywhere = filter(lambda x: not f(x), everywhere)
 
-    author_results = SearchResult.aggregate(author_results)
-    translator_results = SearchResult.aggregate(translator_results)
+    author_results = SearchResult.aggregate(author_results, author_title_rest)
     title_results = SearchResult.aggregate(title_results)
 
     everywhere = SearchResult.aggregate(everywhere, author_title_rest)
 
     for field, res in [('authors', author_results),
-                       ('translators', translator_results),
                        ('title', title_results),
                        ('text', text_phrase),
                        ('text', everywhere)]:
@@ -217,24 +209,15 @@ def main(request):
             return False
 
     author_results = filter(ensure_exists, author_results)
-    translator_results = filter(ensure_exists, translator_results)
     title_results = filter(ensure_exists, title_results)
     text_phrase = filter(ensure_exists, text_phrase)
     everywhere = filter(ensure_exists, everywhere)
 
     # ensure books do exists & sort them
-    for res in (author_results, translator_results, title_results, text_phrase, everywhere):
+    for res in (author_results, title_results, text_phrase):
         res.sort(reverse=True)
 
-    # We don't want to redirect to book text, but rather display result page even with one result.
-    # if len(results) == 1:
-    #     fragment_hits = filter(lambda h: 'fragment' in h, results[0].hits)
-    #     if len(fragment_hits) == 1:
-    #         #anchor = fragment_hits[0]['fragment']
-    #         #frag = Fragment.objects.get(anchor=anchor)
-    #         return HttpResponseRedirect(fragment_hits[0]['fragment'].get_absolute_url())
-    #     return HttpResponseRedirect(results[0].book.get_absolute_url())
-    if not (author_results or translator_results or title_results or text_phrase or everywhere):
+    if not (author_results or title_results or text_phrase or everywhere):
         form = PublishingSuggestForm(initial={"books": query + ", "})
         return render_to_response(
             'catalogue/search_no_hits.html',
@@ -253,7 +236,6 @@ def main(request):
             'prefix': query,
             'results': {
                 'author': author_results,
-                'translator': translator_results,
                 'title': title_results,
                 'content': text_phrase,
                 'other': everywhere