Explorar o código

[search] Adding range facets with numbers

Romain Rigaux %!s(int64=11) %!d(string=hai) anos
pai
achega
3f3986d

+ 14 - 4
apps/search/src/search/api.py

@@ -110,10 +110,6 @@ class SolrApi(object):
         if facet['type'] == 'query':
           params += (('facet.query', '%s' % facet['field']),)
         if facet['type'] == 'range':
-          if not facet['properties']:
-            facet['properties']['start'] = '2014-02-25T15:00:00Z'
-            facet['properties']['end'] = '2014-02-26T12:00:00Z'
-            facet['properties']['gap'] = '+1HOURS'
           params += tuple([
              ('facet.range', facet['field']),
              ('f.%s.facet.range.start' % facet['field'], facet['properties']['start']),
@@ -253,4 +249,18 @@ class SolrApi(object):
       return self._get_json(response)    
     except RestException, e:
       raise PopupException(e, title=_('Error while accessing Solr'))
+    
+  def stats(self, core, fields):
+    try:
+      params = (
+          ('q', EMPTY_QUERY.get()),
+          ('wt', 'json'),
+          ('rows', 0),
+          ('stats', 'true'),
+      )      
+      params += tuple([('stats.field', field) for field in fields])
+      response = self._root.get('%(core)s/select' % {'core': core}, params=params)
+      return self._get_json(response)
+    except RestException, e:
+      raise PopupException(e, title=_('Error while accessing Solr'))
     

+ 3 - 2
apps/search/src/search/models.py

@@ -515,7 +515,8 @@ def augment_solr_response2(response, collection, solr_query):
             'label': name,
             'count': value,
           }        
-          normalized_facets.append(facet)          
+          normalized_facets.append(facet)
+      # pivot_facet          
 
   # TODO HTML escape docs!
   
@@ -552,7 +553,7 @@ def augment_solr_exception(response, collection, solr_query):
         "type": facet['type'],
         "label": facet['label']
       }
-      for categories in collection['facets'].values() for facet in categories
+      for facet in collection['facets']
     ],
     "responseHeader": {
       "status": -1,

+ 7 - 0
apps/search/src/search/templates/search2.mako

@@ -447,8 +447,15 @@ ${ commonheader(_('Search'), "search", user, "60px") | n,unicode }
       ${ _('Label') }: <input type="text" data-bind="value: label" />
       <br/>      
       ${ _('Field') }: <input type="text" data-bind="value: field" />
+      <br/>
+      ${ _('Start') }: <input type="text" data-bind="value: properties.start" />
+      ${ _('End') }: <input type="text" data-bind="value: properties.end" />
+      ${ _('Gap') }: <input type="text" data-bind="value: properties.gap" />
     </div>  
 
+    <a href="javascript:void(0)"><i class="fa fa-plus"></i></a>
+    <a href="javascript:void(0)"><i class="fa fa-minus"></i></a>
+
     <span data-bind="text: counts" />
   </div>
   <!-- /ko -->

+ 5 - 4
apps/search/src/search/urls.py

@@ -23,7 +23,7 @@ urlpatterns = patterns('search.views',
   url(r'^save$', 'save', name='save'),
   url(r'^new_search', 'new_search', name='new_search'),
   url(r'^download/(?P<format>(csv|xls))$', 'download', name='download'),
-
+  
   url(r'^dashboard$', 'dashboard', name='dashboard'),
 
   # All admin is deprecated
@@ -40,12 +40,13 @@ urlpatterns = patterns('search.views',
   # Ajax
   url(r'^suggest/(?P<collection_id>\w+)/(?P<query>\w+)?$', 'query_suggest', name='query_suggest'),
   url(r'^index/(?P<collection_id>\w+)/fields/dynamic$', 'index_fields_dynamic', name='index_fields_dynamic'),
+  url(r'^template/(?P<collection_id>\w+)/new_facet$', 'new_facet', name='new_facet'),
+  
+  # old
   url(r'^admin/collection/(?P<collection_id>\w+)/schema$', 'admin_collection_schema', name='admin_collection_schema'),
   url(r'^admin/collection/(?P<collection_id>\w+)/solr_properties$', 'admin_collection_solr_properties', name='admin_collection_solr_properties'),
   url(r'^admin/collection_delete$', 'admin_collection_delete', name='admin_collection_delete'),
   url(r'^admin/collection_copy$', 'admin_collection_copy', name='admin_collection_copy'),
-  
-  
-  
+
   url(r'^install_examples$', 'install_examples', name='install_examples'),
 )

+ 52 - 0
apps/search/src/search/views.py

@@ -468,6 +468,58 @@ def index_fields_dynamic(request, collection_id):
   return HttpResponse(json.dumps(result), mimetype="application/json")
 
 
+# TODO security
+def new_facet(request, collection_id):  
+  result = {'status': -1, 'message': 'Error'}
+
+  solr_query = {}
+  
+  try:
+    hue_collection = Collection.objects.get(id=collection_id)
+    solr_query['collection'] = hue_collection.name
+    
+    facet_id = request.POST['id']
+    facet_label = request.POST['label']
+    facet_field = request.POST['field']
+    widget_type = request.POST['widget_type']
+    
+    if widget_type == 'hit-widget':
+      facet_type = 'query'
+    elif widget_type == 'histogram-widget':
+      facet_type = 'range'
+    else:
+      facet_type = 'field'      
+
+    SLOTS = 50            
+            # todo: dates
+            #datetime.strptime('2013-06-05T00:00Z', '%Y-%m-%dT%H:%MZ'), coordinator.end)            
+#            facet['properties']['start'] = '2014-02-25T15:00:00Z'
+#            facet['properties']['end'] = '2014-02-26T12:00:00Z'
+#            facet['properties']['gap'] = '+1HOURS'    
+    
+    stats_json = SolrApi(SOLR_URL.get(), request.user).stats(hue_collection.name, [facet_field])
+    
+    stats_min = int(stats_json['stats']['stats_fields'][facet_field]['min']) # if field is int, cast as int
+    stats_max = int(float(stats_json['stats']['stats_fields'][facet_field]['max']))
+    
+    result['message'] = ''
+    result['facet'] = {
+      'id': facet_id,
+      'label': facet_label,
+      'field': facet_field,
+      'type': facet_type,
+      'properties': {
+          'start': stats_min,
+          'end': stats_max,
+          'gap': (stats_max - stats_min) / SLOTS,
+      }
+    }
+    result['status'] = 0
+  except Exception, e:
+    result['message'] = unicode(str(e), "utf8")
+
+  return HttpResponse(json.dumps(result), mimetype="application/json")
+
 
 def install_examples(request):
   result = {'status': -1, 'message': ''}

+ 12 - 9
apps/search/static/js/search.ko.js

@@ -232,18 +232,21 @@ var Collection = function (vm, collection) {
   self.fields = ko.mapping.fromJS(collection.fields);
 
   self.addFacet = function (facet_json) {
-	var facetType = facet_json.widgetType == 'hit-widget' ? 'query' : (facet_json.widgetType == 'histogram-widget' ? 'range' : 'field');
-    var facet = ko.mapping.fromJS({
+    $.post("/search/template/" + self.id + "/new_facet", {
         "id": facet_json.widget_id,
         "label": facet_json.name,
         "field": facet_json.name,
-        "type": facetType,
-        "properties": {}
-    });
-    facet.field.subscribe(function () {
-      vm.search();
-    });
-    self.facets.push(facet);
+        "widget_type": facet_json.widgetType
+      }, function (data) {
+      if (data.status == 0) {
+	    var facet = ko.mapping.fromJS(data.facet);
+	    facet.field.subscribe(function () {
+	      vm.search();
+	    });
+	    self.facets.push(facet);
+	    vm.search();
+      }
+    }).fail(function (xhr, textStatus, errorThrown) {});
   };
 
   self.removeFacet = function (widget_id) {