Commits

Benoit C committed 80dd34e

execute a simple query (pyes.MatchAllQuery() )

Comments (0)

Files changed (1)

backend/elasticsearch_backend.py

 
 # django
 from django.conf import settings
+from django.utils import tree
 
 
 # from haystack
 from haystack.backends import BaseSearchBackend, BaseSearchQuery, log_query
-
+from haystack.backends import SearchNode as SearchNodeBase, SQ
 
 # pyes, python elasticsearch connector
 
         if not hasattr(settings, 'HAYSTACK_ELASTICSEARCH_INDEX'):
              raise ImproperlyConfigured('You must specify a HAYSTACK_ELASTICSEARCH_INDEX in your settings.')
 
-        timeout = getattr(settings, 'HAYSTACK_SOLR_TIMEOUT', 10)
+        timeout = getattr(settings, 'HAYSTACK_HAYSTACK_TIMEOUT', 10)
 
         self.conn = pyes.ES([settings.HAYSTACK_ELASTICSEARCH_URL], timeout=timeout)
         self.log = logging.getLogger('haystack')
 
     def update(self, index, iterable):
         print "update"
-        self.conn.create_index_if_missing(self.index_name)
-        self.conn.put_mapping(self.mapping_name, {'properties':self.mapping}, [self.index_name])
+        try:
+            ret = self.conn.create_index_if_missing(self.index_name)
+            # why the hell, if_missing should raise an exception ?
+            self.conn.put_mapping(self.mapping_name, {'properties':self.mapping}, [self.index_name])
+        except:
+            pass
+        
         docs = []
         for obj in iterable:
             doc = index.full_prepare(obj)
         print "clear"
         self.conn.delete_index_if_exists(self.index_name)
     
-    def search(self, query_string, sort_by=None, start_offset=0, end_offset=None, fields='', highlight=False, facets=None, date_facets=None, query_facets=None, narrow_queries=None, spelling_query=None, limit_to_registered_models=None, **kwargs):
+    @log_query
+    def search(self, query, sort_by=None, start_offset=0, end_offset=None,
+               fields='', highlight=False, facets=None, date_facets=None,
+               query_facets=None, narrow_queries=None, spelling_query=None,
+               limit_to_registered_models=True, **kwargs):
         print "search"
-        pass
+        
+        print type(query)
+        ret = self.conn.search(query=query)
+
+        print ret
+
+        return ret
 
     def prep_value(self, value):
         print "prep_value"
         for field_name, field_class in fields.items():
             mapping_field = {}
             mapping_field['store'] = field_class.stored
-            mapping_field['boost'] = field_class.weight
+            mapping_field['boost'] = field_class.boost
             mapping_field['type'] = field_class.field_type
             mapping[field_name] = mapping_field
 
         print "build_registered_models_list"
         pass
 
+
 class SearchQuery(BaseSearchQuery):
     def __init__(self, site=None, backend=None):
         super(SearchQuery, self).__init__(backend=backend)
-        
+
         if backend is not None:
             self.backend = backend
         else:
         print field
         print filter_type
 
+        value = unicode(value)
+
         filter_types = {
                 'exact': pyes.TermQuery(field, value),
                 'gt': "%s:{%s TO}",
             }
         return ''#filter_types[filter_type]
 
+    def _query_from_search_node(self, search_node, is_not=False):
+        query_list = []
+
+        for child in search_node.children:
+            if isinstance(child, tree.Node):
+                query_list.append(
+                    self._query_from_search_node(child, child.negated)
+                )
+            else:
+                expression, term = child
+                term = unicode(term)
+                field, filter_type = search_node.split_expression(expression)
+                print expression
+
+                
+                # if isinstance(term, (list, tuple)):
+                #     term = [_marshal_term(t) for t in term]
+                # else:
+                #     term = _marshal_term(term)
+                
+                if field == 'content':
+                            
+
+                    query_list.append(self._content_field(term, is_not))
+                else:
+                    if filter_type == 'exact':
+                        query_list.append(self._filter_exact(term, field, is_not))
+                    elif filter_type == 'gt':
+                        query_list.append(self._filter_gt(term, field, is_not))
+                    elif filter_type == 'gte':
+                        query_list.append(self._filter_gte(term, field, is_not))
+                    elif filter_type == 'lt':
+                        query_list.append(self._filter_lt(term, field, is_not))
+                    elif filter_type == 'lte':
+                        query_list.append(self._filter_lte(term, field, is_not))
+                    elif filter_type == 'startswith':
+                        query_list.append(self._filter_startswith(term, field, is_not))
+                    elif filter_type == 'in':
+                        query_list.append(self._filter_in(term, field, is_not))
+
+
+        print query_list
+
+    def _filter_exact(self, term, field, is_not):
+        term = pyes.TermQuery(field, term)
+        return term
+        pass
+
+    def _filter_gt(self, term, field, is_not):
+        pass
+
+    def _filter_gte(self, term, field, is_not):
+        pass
+
+    def _filter_lt(self, term, field, is_not):
+        pass
+
+    def _filter_lte(self, term, field, is_not):
+        pass
+    
+    def _filter_startswith(self, term, is_not):
+        pass
+    
+    def _filter_in(self, term, is_not):
+        pass
+
+
+
+
     def build_query(self):
         """
         Interprets the collected query metadata and builds the final query to
         be sent to the backend.
         """
-        query = pyes.Query()#self.query_filter.as_query_string(self.build_query_fragment)
+        if not self.query_filter:
+            query = pyes.Query('')
+        else:
+            query_list = self._query_from_search_node(self.query_filter)
+            andq = pyes.ANDFilter(query_list)
+            query = pyes.FilteredQuery(pyes.MatchAllQuery(), andq)
+            query = pyes.MatchAllQuery()
         
         if not query:
             # Match all.
             query = self.matching_all_fragment()
         
-        print self.models
+        print "models" , self.models
+
         # if len(self.models):
         #     models = sorted(['%s:%s.%s' % (DJANGO_CT, model._meta.app_label, model._meta.module_name) for model in self.models])
         #     models_clause = ' OR '.join(models)
         # else:
         #     final_query = query
         
-        if self.boost:
-            boost_list = []
-            
-            for boost_word, boost_value in self.boost.items():
-
-                boost_list.append(self.boost_fragment(boost_word, boost_value))
-            
-            final_query = "%s %s" % (final_query, " ".join(boost_list))
-        
-        return final_query
+        print query
+        return query
 
     def build_params(self):
         print "build_params"
 
     def clean(self, query_fragment):
+        print query_fragment
+        print type(query_fragment)
         print "clean"
 
+
     def run(self, spelling_query=None):
-
         final_query = self.build_query()
-        final_query = pyes.StringQuery("*")
-        results = self.backend.conn.search(query=final_query, indexes=[self.backend.index_name])
-
+        results = self.backend.search(final_query, indexes=[self.backend.index_name])
         self._results = results.get('hits', {}).get('hits')
         self._hit_count = results.get('hits').get('total')
         self._facet_counts = self.post_process_facets(results)
         self._spelling_suggestion = results.get('spelling_suggestion', None)
 
+        print self._results
+
     def run_mlt(self):
         print "run_mlt"
         pass