Skip to content
This repository
  • 5 commits
  • 3 files changed
  • 0 comments
  • 1 contributor
26  r2/r2/controllers/api.py
@@ -59,7 +59,7 @@
59 59
 from r2.lib.filters import safemarkdown
60 60
 from r2.lib.scraper import str_to_image
61 61
 from r2.controllers.api_docs import api_doc, api_section
62  
-from r2.lib.cloudsearch import basic_query
  62
+from r2.lib.search import SearchQuery
63 63
 
64 64
 import csv
65 65
 from collections import defaultdict
@@ -2785,7 +2785,7 @@ def POST_disable_otp(self, form, jquery):
2785 2785
         c.user._commit()
2786 2786
         form.redirect("/prefs/otp")
2787 2787
 
2788  
-    @json_validate(query=VPrintable("query", max_length=50))
  2788
+    @json_validate(query=VLength("query", max_length=50))
2789 2789
     @api_doc(api_section.subreddits, extensions=["json"])
2790 2790
     def GET_subreddits_by_topic(self, responder, query):
2791 2791
         if not g.CLOUDSEARCH_SEARCH_API:
@@ -2796,25 +2796,17 @@ def GET_subreddits_by_topic(self, responder, query):
2796 2796
 
2797 2797
         exclude = Subreddit.default_subreddits()
2798 2798
 
2799  
-        q = basic_query(query,
2800  
-                        facets={"reddit":{"sort":"-sum(text_relevance)", "count":20}},
2801  
-                        record_stats=True)
2802  
-        if not q["facets"]:
2803  
-            return []
2804  
-
2805  
-        sr_facets = [f["value"] for f in q["facets"]["reddit"]["constraints"]]
2806  
-        srs = Subreddit._by_name(sr_facets)
  2799
+        faceting = {"reddit":{"sort":"-sum(text_relevance)", "count":20}}
  2800
+        results = SearchQuery(query, sort="relevance", faceting=faceting).run()
2807 2801
 
2808  
-        results = []
2809  
-        for sr_name in sr_facets:
2810  
-            sr = srs.get(sr_name)
  2802
+        sr_results = []
  2803
+        for sr, count in results.subreddit_facets:
2811 2804
             if (sr._id in exclude or (sr.over_18 and not c.over18)
2812  
-                  or not sr.can_view(c.user)
2813 2805
                   or sr.type == "archived"):
2814 2806
                 continue
2815 2807
 
2816  
-            results.append({
2817  
-                "name": sr_name,
  2808
+            sr_results.append({
  2809
+                "name": sr.name,
2818 2810
             })
2819 2811
 
2820  
-        return results
  2812
+        return sr_results
47  r2/r2/lib/cloudsearch.py
@@ -496,11 +496,18 @@ def subreddit_facets(self):
496 496
         if not self._subreddits and 'reddit' in self._facets:
497 497
             sr_facets = [(sr['value'], sr['count']) for sr in
498 498
                          self._facets['reddit']]
499  
-            srs_by_name = Subreddit._by_name([sr[0] for sr in sr_facets])
500  
-            self._subreddits = [sr for sr in sr_facets
501  
-                                if sr[0] in srs_by_name and
502  
-                                srs_by_name[sr[0]].can_view(c.user)]
503  
-        
  499
+
  500
+            # look up subreddits
  501
+            srs_by_name = Subreddit._by_name([name for name, count
  502
+                                              in sr_facets])
  503
+
  504
+            sr_facets = [(srs_by_name[name], count) for name, count
  505
+                         in sr_facets if name in srs_by_name]
  506
+
  507
+            # filter by can_view
  508
+            self._subreddits = [(sr, count) for sr, count in sr_facets
  509
+                                if sr.can_view(c.user)]
  510
+
504 511
         return self._subreddits
505 512
 
506 513
 
@@ -509,12 +516,14 @@ def subreddit_facets(self):
509 516
                        'CS-IncorrectFieldTypeInMatchExpression',
510 517
                        'CS-InvalidMatchSetExpression',)
511 518
 DEFAULT_FACETS = {"reddit": {"count":20}}
512  
-def basic_query(query=None, bq=None, facets=DEFAULT_FACETS, size=1000,
  519
+def basic_query(query=None, bq=None, faceting=None, size=1000,
513 520
                 start=0, rank="-relevance", return_fields=None, record_stats=False,
514 521
                 search_api=None):
515 522
     if search_api is None:
516 523
         search_api = g.CLOUDSEARCH_SEARCH_API
517  
-    path = _encode_query(query, bq, facets, size, start, rank, return_fields)
  524
+    if faceting is None:
  525
+        faceting = DEFAULT_FACETS
  526
+    path = _encode_query(query, bq, faceting, size, start, rank, return_fields)
518 527
     timer = None
519 528
     if record_stats:
520 529
         timer = g.stats.get_timer("cloudsearch_timer")
@@ -557,7 +566,7 @@ def basic_query(query=None, bq=None, facets=DEFAULT_FACETS, size=1000,
557 566
 
558 567
 
559 568
 basic_subreddit = functools.partial(basic_query,
560  
-                                    facets=None,
  569
+                                    faceting=None,
561 570
                                     size=10, start=0,
562 571
                                     rank="-activity",
563 572
                                     return_fields=['title', 'reddit',
@@ -566,7 +575,7 @@ def basic_query(query=None, bq=None, facets=DEFAULT_FACETS, size=1000,
566 575
                                     search_api=g.CLOUDSEARCH_SUBREDDIT_SEARCH_API)
567 576
 
568 577
 
569  
-def _encode_query(query, bq, facets, size, start, rank, return_fields):
  578
+def _encode_query(query, bq, faceting, size, start, rank, return_fields):
570 579
     if not (query or bq):
571 580
         raise ValueError("Need query or bq")
572 581
     params = {}
@@ -578,9 +587,9 @@ def _encode_query(query, bq, facets, size, start, rank, return_fields):
578 587
     params["size"] = size
579 588
     params["start"] = start
580 589
     params["rank"] = rank
581  
-    if facets:
582  
-        params["facet"] = ",".join(facets.iterkeys())
583  
-        for facet, options in facets.iteritems():
  590
+    if faceting:
  591
+        params["facet"] = ",".join(faceting.iterkeys())
  592
+        for facet, options in faceting.iteritems():
584 593
             params["facet-%s-top-n" % facet] = options.get("count", 20)
585 594
             if "sort" in options:
586 595
                 params["facet-%s-sort" % facet] = options["sort"]
@@ -600,7 +609,8 @@ class CloudSearchQuery(object):
600 609
     default_syntax = "plain"
601 610
     lucene_parser = None
602 611
     
603  
-    def __init__(self, query, sr=None, sort=None, syntax=None, raw_sort=None):
  612
+    def __init__(self, query, sr=None, sort=None, syntax=None, raw_sort=None,
  613
+                 faceting=None):
604 614
         if syntax is None:
605 615
             syntax = self.default_syntax
606 616
         elif syntax not in self.known_syntaxes:
@@ -614,6 +624,7 @@ def __init__(self, query, sr=None, sort=None, syntax=None, raw_sort=None):
614 624
             self.sort = raw_sort
615 625
         else:
616 626
             self.sort = self.sorts[sort]
  627
+        self.faceting = faceting
617 628
         self.bq = ''
618 629
         self.results = None
619 630
     
@@ -644,8 +655,8 @@ def _run(self, start=0, num=1000, _update=False):
644 655
             q = self.query
645 656
         if g.sqlprinting:
646 657
             g.log.info("%s", self)
647  
-        return self._run_cached(q, self.bq, self.sort, start=start, num=num,
648  
-                                _update=_update)
  658
+        return self._run_cached(q, self.bq, self.sort, self.faceting,
  659
+                                start=start, num=num, _update=_update)
649 660
     
650 661
     def customize_query(self, bq):
651 662
         return bq
@@ -663,8 +674,8 @@ def __repr__(self):
663 674
         return ''.join(result)
664 675
     
665 676
     @classmethod
666  
-    def _run_cached(cls, query, bq, sort="relevance", start=0, num=1000,
667  
-                    _update=False):
  677
+    def _run_cached(cls, query, bq, sort="relevance", faceting=None, start=0,
  678
+                    num=1000, _update=False):
668 679
         '''Query the cloudsearch API. _update parameter allows for supposed
669 680
         easy memoization at later date.
670 681
         
@@ -701,7 +712,7 @@ def _run_cached(cls, query, bq, sort="relevance", start=0, num=1000,
701 712
         '''
702 713
         response = basic_query(query=query, bq=bq, size=num, start=start,
703 714
                                rank=sort, search_api=cls.search_api,
704  
-                               record_stats=True)
  715
+                               faceting=faceting, record_stats=True)
705 716
         
706 717
         warnings = response['info'].get('messages', [])
707 718
         for warning in warnings:
5  r2/r2/templates/searchbar.html
@@ -78,10 +78,9 @@ <h4 style="color:gray">${thing.header}</h4>
78 78
 <div class="searchfacets">
79 79
   <h4 class="title">${_("too many results? narrow it down to a subreddit!")}</h4>
80 80
   <ol class="list">
81  
-  %for facet in thing.facets:
82  
-    <% subreddit, count = facet %>
  81
+  %for subreddit, count in thing.facets:
83 82
     <li class="searchfacet reddit">
84  
-      <a class="facet title word" href="${search_url(thing.prev_search, subreddit, restrict_sr='on', sort=thing.sort)}">/r/${subreddit}</a>&nbsp;
  83
+      <a class="facet title word" href="${search_url(thing.prev_search, subreddit.name, restrict_sr='on', sort=thing.sort)}">/r/${subreddit.name}</a>&nbsp;
85 84
       <span class="facet count number">(${count})</span>
86 85
     </li>&nbsp;
87 86
   %endfor

No commit comments for this range

Something went wrong with that request. Please try again.