Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add wagtailsearch based search app

Artur Smęt8d404f90806f
diff --git a/saleor/search/__init__.py b/saleor/search/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/search/backends/__init__.py b/saleor/search/backends/__init__.py
new file mode 100644
index 0000000000..2f1334f754
--- /dev/null
+++ b/saleor/search/backends/__init__.py
@@ -0,0 +1,103 @@
+# Search backends implementation
+# Adapted from Wagtail's 'wagtailsearch' app
+# https://github.com/torchbox/wagtail/tree/master/wagtail/wagtailsearch
+
+import sys
+from importlib import import_module
+
+from django.utils import six
+from django.utils.module_loading import import_string
+from django.core.exceptions import ImproperlyConfigured
+from django.conf import settings
+
+
+class InvalidSearchBackendError(ImproperlyConfigured):
+ pass
+
+
+def get_search_backend_config():
+ search_backends = getattr(settings, 'SEARCH_BACKENDS', {})
+ return search_backends
+
+
+def import_backend(dotted_path):
+ """
+ Theres two formats for the dotted_path.
+ One with the backend class (old) and one without (new)
+ eg:
+ old: wagtail.wagtailsearch.backends.elasticsearch.ElasticsearchSearchBackend
+ new: wagtail.wagtailsearch.backends.elasticsearch
+
+ If a new style dotted path was specified, this function would
+ look for a backend class from the "SearchBackend" attribute.
+ """
+ try:
+ # New
+ backend_module = import_module(dotted_path)
+ return backend_module.SearchBackend
+ except ImportError as e:
+ try:
+ # Old
+ return import_string(dotted_path)
+ except ImportError:
+ six.reraise(ImportError, e, sys.exc_info()[2])
+
+
+def get_search_backend(backend='default', **kwargs):
+ search_backends = get_search_backend_config()
+
+ # Try to find the backend
+ try:
+ # Try to get the WAGTAILSEARCH_BACKENDS entry for the given backend name first
+ conf = search_backends[backend]
+ except KeyError:
+ try:
+ # Trying to import the given backend, in case it's a dotted path
+ import_backend(backend)
+ except ImportError as e:
+ raise InvalidSearchBackendError("Could not find backend '%s': %s" % (
+ backend, e))
+ params = kwargs
+ else:
+ # Backend is a conf entry
+ params = conf.copy()
+ params.update(kwargs)
+ backend = params.pop('BACKEND')
+
+ # Try to import the backend
+ try:
+ backend_cls = import_backend(backend)
+ except ImportError as e:
+ raise InvalidSearchBackendError("Could not find backend '%s': %s" % (
+ backend, e))
+
+ # Create backend
+ return backend_cls(params)
+
+
+def _backend_requires_auto_update(backend_name, params):
+ if params.get('AUTO_UPDATE', True):
+ return True
+
+ # _WAGTAILSEARCH_FORCE_AUTO_UPDATE is only used by Wagtail tests. It allows
+ # us to test AUTO_UPDATE behaviour against Elasticsearch without having to
+ # have AUTO_UPDATE enabed for every test.
+ force_auto_update = getattr(settings, '_WAGTAILSEARCH_FORCE_AUTO_UPDATE', [])
+ if backend_name in force_auto_update:
+ return True
+
+ return False
+
+
+def get_search_backends_with_name(with_auto_update=False):
+ search_backends = get_search_backend_config()
+ for backend, params in search_backends.items():
+ if with_auto_update and _backend_requires_auto_update(backend, params) is False:
+ continue
+
+ yield backend, get_search_backend(backend)
+
+
+def get_search_backends(with_auto_update=False):
+ # For backwards compatibility
+ return (backend for _, backend in get_search_backends_with_name(with_auto_update=with_auto_update))
diff --git a/saleor/search/backends/base.py b/saleor/search/backends/base.py
new file mode 100644
index 0000000000..5997ab49a0
--- /dev/null
+++ b/saleor/search/backends/base.py
@@ -0,0 +1,266 @@
+
+from __future__ import absolute_import, unicode_literals
+
+from django.db.models.lookups import Lookup
+from django.db.models.query import QuerySet
+from django.db.models.sql.where import SubqueryConstraint, WhereNode
+from django.utils.six import text_type
+
+
+class FilterError(Exception):
+ pass
+
+
+class FieldError(Exception):
+ pass
+
+
+class BaseSearchQuery(object):
+ DEFAULT_OPERATOR = 'or'
+
+ def __init__(self, queryset, query_string, fields=None, operator=None, order_by_relevance=True):
+ self.queryset = queryset
+ self.query_string = query_string
+ self.fields = fields
+ self.operator = operator or self.DEFAULT_OPERATOR
+ self.order_by_relevance = order_by_relevance
+
+ def _get_filterable_field(self, field_attname):
+ # Get field
+ field = dict(
+ (field.get_attname(self.queryset.model), field)
+ for field in self.queryset.model.get_filterable_search_fields()
+ ).get(field_attname, None)
+
+ return field
+
+ def _process_lookup(self, field, lookup, value):
+ raise NotImplementedError
+
+ def _connect_filters(self, filters, connector, negated):
+ raise NotImplementedError
+
+ def _process_filter(self, field_attname, lookup, value):
+ # Get the field
+ field = self._get_filterable_field(field_attname)
+
+ if field is None:
+ raise FieldError(
+ 'Cannot filter search results with field "' + field_attname + '". Please add index.FilterField(\'' +
+ field_attname + '\') to ' + self.queryset.model.__name__ + '.search_fields.'
+ )
+
+ # Process the lookup
+ result = self._process_lookup(field, lookup, value)
+
+ if result is None:
+ raise FilterError(
+ 'Could not apply filter on search results: "' + field_attname + '__' +
+ lookup + ' = ' + text_type(value) + '". Lookup "' + lookup + '"" not recognised.'
+ )
+
+ return result
+
+ def _get_filters_from_where_node(self, where_node):
+ # Check if this is a leaf node
+ if isinstance(where_node, Lookup):
+ field_attname = where_node.lhs.target.attname
+ lookup = where_node.lookup_name
+ value = where_node.rhs
+
+ # Ignore pointer fields that show up in specific page type queries
+ if field_attname.endswith('_ptr_id'):
+ return
+
+ # Process the filter
+ return self._process_filter(field_attname, lookup, value)
+
+ elif isinstance(where_node, SubqueryConstraint):
+ raise FilterError('Could not apply filter on search results: Subqueries are not allowed.')
+
+ elif isinstance(where_node, WhereNode):
+ # Get child filters
+ connector = where_node.connector
+ child_filters = [self._get_filters_from_where_node(child) for child in where_node.children]
+ child_filters = [child_filter for child_filter in child_filters if child_filter]
+
+ return self._connect_filters(child_filters, connector, where_node.negated)
+
+ else:
+ raise FilterError('Could not apply filter on search results: Unknown where node: ' + str(type(where_node)))
+
+ def _get_filters_from_queryset(self):
+ return self._get_filters_from_where_node(self.queryset.query.where)
+
+
+class BaseSearchResults(object):
+ def __init__(self, backend, query, prefetch_related=None):
+ self.backend = backend
+ self.query = query
+ self.prefetch_related = prefetch_related
+ self.start = 0
+ self.stop = None
+ self._results_cache = None
+ self._count_cache = None
+ self._score_field = None
+
+ def _set_limits(self, start=None, stop=None):
+ if stop is not None:
+ if self.stop is not None:
+ self.stop = min(self.stop, self.start + stop)
+ else:
+ self.stop = self.start + stop
+
+ if start is not None:
+ if self.stop is not None:
+ self.start = min(self.stop, self.start + start)
+ else:
+ self.start = self.start + start
+
+ def _clone(self):
+ klass = self.__class__
+ new = klass(self.backend, self.query, prefetch_related=self.prefetch_related)
+ new.start = self.start
+ new.stop = self.stop
+ return new
+
+ def _do_search(self):
+ raise NotImplementedError
+
+ def _do_count(self):
+ raise NotImplementedError
+
+ def results(self):
+ if self._results_cache is None:
+ self._results_cache = self._do_search()
+ return self._results_cache
+
+ def count(self):
+ if self._count_cache is None:
+ if self._results_cache is not None:
+ self._count_cache = len(self._results_cache)
+ else:
+ self._count_cache = self._do_count()
+ return self._count_cache
+
+ def __getitem__(self, key):
+ new = self._clone()
+
+ if isinstance(key, slice):
+ # Set limits
+ start = int(key.start) if key.start else None
+ stop = int(key.stop) if key.stop else None
+ new._set_limits(start, stop)
+
+ # Copy results cache
+ if self._results_cache is not None:
+ new._results_cache = self._results_cache[key]
+
+ return new
+ else:
+ if self._results_cache is not None:
+ return self._results_cache[key]
+
+ new.start = self.start + key
+ new.stop = self.start + key + 1
+ return list(new)[0]
+
+ def __iter__(self):
+ return iter(self.results())
+
+ def __len__(self):
+ return len(self.results())
+
+ def __repr__(self):
+ data = list(self[:21])
+ if len(data) > 20:
+ data[-1] = "...(remaining elements truncated)..."
+ return '<SearchResults %r>' % data
+
+ def annotate_score(self, field_name):
+ clone = self._clone()
+ clone._score_field = field_name
+ return clone
+
+
+class BaseSearchBackend(object):
+ query_class = None
+ results_class = None
+ rebuilder_class = None
+
+ def __init__(self, params):
+ pass
+
+ def get_index_for_model(self, model):
+ return None
+
+ def get_rebuilder(self):
+ return None
+
+ def reset_index(self):
+ raise NotImplementedError
+
+ def add_type(self, model):
+ raise NotImplementedError
+
+ def refresh_index(self):
+ raise NotImplementedError
+
+ def add(self, obj):
+ raise NotImplementedError
+
+ def add_bulk(self, model, obj_list):
+ raise NotImplementedError
+
+ def delete(self, obj):
+ raise NotImplementedError
+
+ def search(self, query_string, model_or_queryset, fields=None, filters=None,
+ prefetch_related=None, operator=None, order_by_relevance=True):
+ # Find model/queryset
+ if isinstance(model_or_queryset, QuerySet):
+ model = model_or_queryset.model
+ queryset = model_or_queryset
+ else:
+ model = model_or_queryset
+ queryset = model_or_queryset.objects.all()
+
+ # # Model must be a class that is in the index
+ # if not class_is_indexed(model):
+ # return []
+
+ # Check that theres still a query string after the clean up
+ if query_string == "":
+ return []
+
+ # Only fields that are indexed as a SearchField can be passed in fields
+ if fields:
+ allowed_fields = {field.field_name for field in model.get_searchable_search_fields()}
+
+ for field_name in fields:
+ if field_name not in allowed_fields:
+ raise FieldError(
+ 'Cannot search with field "' + field_name + '". Please add index.SearchField(\'' +
+ field_name + '\') to ' + model.__name__ + '.search_fields.'
+ )
+
+ # Apply filters to queryset
+ if filters:
+ queryset = queryset.filter(**filters)
+
+ # Prefetch related
+ if prefetch_related:
+ for prefetch in prefetch_related:
+ queryset = queryset.prefetch_related(prefetch)
+
+ # Check operator
+ if operator is not None:
+ operator = operator.lower()
+ if operator not in ['or', 'and']:
+ raise ValueError("operator must be either 'or' or 'and'")
+
+ # Search
+ search_query = self.query_class(
+ queryset, query_string, fields=fields, operator=operator, order_by_relevance=order_by_relevance
+ )
+ return self.results_class(self, search_query)
diff --git a/saleor/search/backends/dashboard.py b/saleor/search/backends/dashboard.py
new file mode 100644
index 0000000000..c40125e67d
--- /dev/null
+++ b/saleor/search/backends/dashboard.py
@@ -0,0 +1,135 @@
+from . import elasticsearch2
+from .base import BaseSearchQuery
+from ..index import get_indexed_models
+
+CONTENT_TYPES_MAP = {
+ model.indexed_get_content_type(): model
+ for model in get_indexed_models()}
+
+
+class DashboardSearchQuery(BaseSearchQuery):
+
+ def __init__(self, query_string,
+ fields=None, operator=None, order_by_relevance=True,
+ queryset_map=None):
+ if queryset_map:
+ queryset_map = {model.indexed_get_content_type(): queryset
+ for model, queryset in queryset_map.items()}
+ else:
+ queryset_map = {content_type: model.objects.all()
+ for content_type, model in CONTENT_TYPES_MAP.items()}
+ self.queryset_map = queryset_map
+ super(DashboardSearchQuery, self).__init__(
+ query_string=query_string, queryset=None, fields=fields,
+ operator=operator, order_by_relevance=order_by_relevance)
+
+ def get_inner_query(self):
+ if self.query_string is not None:
+ fields = self.fields or ['_all', '_partials']
+
+ if len(fields) == 1:
+ if self.operator == 'or':
+ query = {
+ 'match': {
+ fields[0]: self.query_string,
+ }
+ }
+ else:
+ query = {
+ 'match': {
+ fields[0]: {
+ 'query': self.query_string,
+ 'operator': self.operator,
+ }
+ }
+ }
+ else:
+ query = {
+ 'multi_match': {
+ 'query': self.query_string,
+ 'fields': fields,
+ }
+ }
+
+ if self.operator != 'or':
+ query['multi_match']['operator'] = self.operator
+ else:
+ query = {
+ 'match_all': {}
+ }
+
+ return query
+
+ def get_query(self):
+ return self.get_inner_query()
+
+
+class DashboardSearchResults(elasticsearch2.Elasticsearch2SearchResults):
+
+ def _do_search(self):
+ # Params for elasticsearch query
+ params = dict(
+ body=self._get_es_body(),
+ _source=False,
+ from_=self.start,
+ )
+ params[self.fields_param_name] = 'pk'
+
+ # Add size if set
+ if self.stop is not None:
+ params['size'] = self.stop - self.start
+ # Send to Elasticsearch
+ hits = self.backend.es.search(**params)
+ from collections import defaultdict
+ search_hits = defaultdict(list)
+ scores = {}
+ for hit in hits['hits']['hits']:
+ hit_type = hit['_type']
+ hit_pk = hit['fields']['pk'][0]
+ search_hits[hit_type].append(hit_pk)
+ scores[hit['_id']] = hit['_score']
+
+ results_by_model = {}
+ for content_type, hit_pks in search_hits.items():
+ queryset = self.query.queryset_map[content_type]
+ results_by_model[content_type] = queryset.filter(pk__in=hit_pks)
+
+ all_results = []
+ for content_type, hits in results_by_model.items():
+ for hit in hits:
+ score_key = '%s:%d' % (content_type, hit.pk)
+ setattr(hit, 'search_score', scores[score_key])
+ setattr(hit, 'content_type', content_type)
+ all_results.append(hit)
+ sorted_results = sorted(
+ all_results, key=lambda h: h.search_score, reverse=True)
+ return list(sorted_results)
+
+ def _get_es_body(self, for_count=False):
+ body = {
+ 'query': self.query.get_query()
+ }
+
+ if not for_count:
+ sort = None
+
+ if sort is not None:
+ body['sort'] = sort
+
+ return body
+
+
+class DashboardMultiTypeSearchBackend(elasticsearch2.Elasticsearch2SearchBackend):
+ results_class = DashboardSearchResults
+ query_class = DashboardSearchQuery
+
+ def search(self, query_string,
+ model_or_queryset=None, fields=None, filters=None,
+ prefetch_related=None, operator=None, order_by_relevance=True,
+ queryset_map=None):
+ search_query = self.query_class(
+ query_string=query_string, fields=fields, operator=operator,
+ order_by_relevance=order_by_relevance, queryset_map=queryset_map)
+ return self.results_class(self, search_query)
+
+SearchBackend = DashboardMultiTypeSearchBackend
diff --git a/saleor/search/backends/db.py b/saleor/search/backends/db.py
new file mode 100644
index 0000000000..2067bc6ee4
--- /dev/null
+++ b/saleor/search/backends/db.py
@@ -0,0 +1,114 @@
+from __future__ import absolute_import, unicode_literals
+
+from django.db import models
+from django.db.models.expressions import Value
+
+from .base import (
+ BaseSearchBackend, BaseSearchQuery, BaseSearchResults)
+
+
+class DatabaseSearchQuery(BaseSearchQuery):
+ DEFAULT_OPERATOR = 'and'
+
+ def _process_lookup(self, field, lookup, value):
+ return models.Q(**{field.get_attname(self.queryset.model) + '__' + lookup: value})
+
+ def _connect_filters(self, filters, connector, negated):
+ if connector == 'AND':
+ q = models.Q(*filters)
+ elif connector == 'OR':
+ q = models.Q(filters[0])
+ for fil in filters[1:]:
+ q |= fil
+ else:
+ return
+
+ if negated:
+ q = ~q
+
+ return q
+
+ def get_extra_q(self):
+ # Run _get_filters_from_queryset to test that no fields that are not
+ # a FilterField have been used in the query.
+ self._get_filters_from_queryset()
+
+ q = models.Q()
+ model = self.queryset.model
+
+ if self.query_string is not None:
+ # Get fields
+ fields = self.fields or [field.field_name for field in model.get_searchable_search_fields()]
+
+ # Get terms
+ terms = self.query_string.split()
+ if not terms:
+ return model.objects.none()
+
+ # Filter by terms
+ for term in terms:
+ term_query = models.Q()
+ for field_name in fields:
+ # Check if the field exists (this will filter out indexed callables)
+ try:
+ model._meta.get_field(field_name)
+ except models.fields.FieldDoesNotExist:
+ continue
+
+ # Filter on this field
+ term_query |= models.Q(**{'%s__icontains' % field_name: term})
+
+ if self.operator == 'or':
+ q |= term_query
+ elif self.operator == 'and':
+ q &= term_query
+
+ return q
+
+
+class DatabaseSearchResults(BaseSearchResults):
+ def get_queryset(self):
+ queryset = self.query.queryset
+ q = self.query.get_extra_q()
+
+ return queryset.filter(q).distinct()[self.start:self.stop]
+
+ def _do_search(self):
+ queryset = self.get_queryset()
+
+ if self._score_field:
+ queryset = queryset.annotate(**{self._score_field: Value(None, output_field=models.FloatField())})
+
+ return queryset
+
+ def _do_count(self):
+ return self.get_queryset().count()
+
+
+class DatabaseSearchBackend(BaseSearchBackend):
+ query_class = DatabaseSearchQuery
+ results_class = DatabaseSearchResults
+
+ def __init__(self, params):
+ super(DatabaseSearchBackend, self).__init__(params)
+
+ def reset_index(self):
+ pass # Not needed
+
+ def add_type(self, model):
+ pass # Not needed
+
+ def refresh_index(self):
+ pass # Not needed
+
+ def add(self, obj):
+ pass # Not needed
+
+ def add_bulk(self, model, obj_list):
+ return # Not needed
+
+ def delete(self, obj):
+ pass # Not needed
+
+
+SearchBackend = DatabaseSearchBackend
diff --git a/saleor/search/backends/elasticsearch.py b/saleor/search/backends/elasticsearch.py
new file mode 100644
index 0000000000..c770ea534b
--- /dev/null
+++ b/saleor/search/backends/elasticsearch.py
@@ -0,0 +1,801 @@
+from __future__ import absolute_import, unicode_literals
+
+import copy
+import json
+
+from django.db import models
+from django.utils.crypto import get_random_string
+from django.utils.six.moves.urllib.parse import urlparse
+from elasticsearch import Elasticsearch, NotFoundError
+from elasticsearch.helpers import bulk
+
+from .base import (
+ BaseSearchBackend, BaseSearchQuery, BaseSearchResults)
+from ..index import (
+ FilterField, Indexed, RelatedFields, SearchField, class_is_indexed)
+
+
+class ElasticsearchMapping(object):
+ type_map = {
+ 'AutoField': 'integer',
+ 'BinaryField': 'binary',
+ 'BooleanField': 'boolean',
+ 'CharField': 'string',
+ 'CommaSeparatedIntegerField': 'string',
+ 'DateField': 'date',
+ 'DateTimeField': 'date',
+ 'DecimalField': 'double',
+ 'FileField': 'string',
+ 'FilePathField': 'string',
+ 'FloatField': 'double',
+ 'IntegerField': 'integer',
+ 'BigIntegerField': 'long',
+ 'IPAddressField': 'string',
+ 'GenericIPAddressField': 'string',
+ 'NullBooleanField': 'boolean',
+ 'OneToOneField': 'integer',
+ 'PositiveIntegerField': 'integer',
+ 'PositiveSmallIntegerField': 'integer',
+ 'SlugField': 'string',
+ 'SmallIntegerField': 'integer',
+ 'TextField': 'string',
+ 'TimeField': 'date',
+ }
+
+ keyword_type = 'string'
+ text_type = 'string'
+ set_index_not_analyzed_on_filter_fields = True
+
+ # Contains the configuration required to use the edgengram_analyzer
+ # on a field. It's different in Elasticsearch 2 so it's been put in
+ # an attribute here to make it easier to override in a subclass.
+ edgengram_analyzer_config = {
+ 'index_analyzer': 'edgengram_analyzer',
+ }
+
+ def __init__(self, model):
+ self.model = model
+
+ def get_parent(self):
+ for base in self.model.__bases__:
+ if issubclass(base, Indexed) and issubclass(base, models.Model):
+ return type(self)(base)
+
+ def get_document_type(self):
+ return self.model.indexed_get_content_type()
+
+ def get_field_column_name(self, field):
+ if isinstance(field, FilterField):
+ return field.get_attname(self.model) + '_filter'
+ elif isinstance(field, SearchField):
+ return field.get_attname(self.model)
+ elif isinstance(field, RelatedFields):
+ return field.field_name
+
+ def get_field_mapping(self, field):
+ if isinstance(field, RelatedFields):
+ mapping = {'type': 'nested', 'properties': {}}
+ nested_model = field.get_field(self.model).related_model
+ nested_mapping = type(self)(nested_model)
+
+ for sub_field in field.fields:
+ sub_field_name, sub_field_mapping = nested_mapping.get_field_mapping(sub_field)
+ mapping['properties'][sub_field_name] = sub_field_mapping
+
+ return self.get_field_column_name(field), mapping
+ else:
+ mapping = {'type': self.type_map.get(field.get_type(self.model), 'string')}
+
+ if isinstance(field, SearchField):
+ if mapping['type'] == 'string':
+ mapping['type'] = self.text_type
+
+ if field.boost:
+ mapping['boost'] = field.boost
+
+ if field.partial_match:
+ mapping.update(self.edgengram_analyzer_config)
+
+ mapping['include_in_all'] = True
+
+ elif isinstance(field, FilterField):
+ if mapping['type'] == 'string':
+ mapping['type'] = self.keyword_type
+
+ if self.set_index_not_analyzed_on_filter_fields:
+ # Not required on ES5 as that uses the "keyword" type for
+ # filtered string fields
+ mapping['index'] = 'not_analyzed'
+
+ mapping['include_in_all'] = False
+
+ if 'es_extra' in field.kwargs:
+ for key, value in field.kwargs['es_extra'].items():
+ mapping[key] = value
+
+ return self.get_field_column_name(field), mapping
+
+ def get_mapping(self):
+ # Make field list
+ fields = {
+ 'pk': dict(type=self.keyword_type, store=True, include_in_all=False),
+ 'content_type': dict(type=self.keyword_type, include_in_all=False),
+ '_partials': dict(type=self.text_type, include_in_all=False),
+ }
+ fields['_partials'].update(self.edgengram_analyzer_config)
+
+ if self.set_index_not_analyzed_on_filter_fields:
+ # Not required on ES5 as that uses the "keyword" type for
+ # filtered string fields
+ fields['pk']['index'] = 'not_analyzed'
+ fields['content_type']['index'] = 'not_analyzed'
+
+ fields.update(dict(
+ self.get_field_mapping(field) for field in self.model.get_search_fields()
+ ))
+ return {
+ self.get_document_type(): {
+ 'properties': fields,
+ }
+ }
+
+ def get_document_id(self, obj):
+ return obj.indexed_get_toplevel_content_type() + ':' + str(obj.pk)
+
+ def _get_nested_document(self, fields, obj):
+ doc = {}
+ partials = []
+ model = type(obj)
+ mapping = type(self)(model)
+
+ for field in fields:
+ value = field.get_value(obj)
+ doc[mapping.get_field_column_name(field)] = value
+
+ # Check if this field should be added into _partials
+ if isinstance(field, SearchField) and field.partial_match:
+ partials.append(value)
+
+ return doc, partials
+
+ def get_document(self, obj):
+ # Build document
+ doc = dict(pk=str(obj.pk), content_type=self.model.indexed_get_content_type())
+ partials = []
+ for field in self.model.get_search_fields():
+ value = field.get_value(obj)
+
+ if isinstance(field, RelatedFields):
+ if isinstance(value, models.Manager):
+ nested_docs = []
+
+ for nested_obj in value.all():
+ nested_doc, extra_partials = self._get_nested_document(field.fields, nested_obj)
+ nested_docs.append(nested_doc)
+ partials.extend(extra_partials)
+
+ value = nested_docs
+ elif isinstance(value, models.Model):
+ value, extra_partials = self._get_nested_document(field.fields, value)
+ partials.extend(extra_partials)
+
+ doc[self.get_field_column_name(field)] = value
+
+ # Check if this field should be added into _partials
+ if isinstance(field, SearchField) and field.partial_match:
+ partials.append(value)
+
+ # Add partials to document
+ doc['_partials'] = partials
+
+ return doc
+
+ def __repr__(self):
+ return '<ElasticsearchMapping: %s>' % (self.model.__name__, )
+
+
+class ElasticsearchSearchQuery(BaseSearchQuery):
+ mapping_class = ElasticsearchMapping
+ DEFAULT_OPERATOR = 'or'
+
+ def __init__(self, *args, **kwargs):
+ super(ElasticsearchSearchQuery, self).__init__(*args, **kwargs)
+ self.mapping = self.mapping_class(self.queryset.model)
+
+ # Convert field names into index column names
+ if self.fields:
+ fields = []
+ searchable_fields = {f.field_name: f for f in self.queryset.model.get_searchable_search_fields()}
+ for field_name in self.fields:
+ if field_name in searchable_fields:
+ field_name = self.mapping.get_field_column_name(searchable_fields[field_name])
+
+ fields.append(field_name)
+
+ self.fields = fields
+
+ def _process_lookup(self, field, lookup, value):
+ column_name = self.mapping.get_field_column_name(field)
+
+ if lookup == 'exact':
+ if value is None:
+ return {
+ 'missing': {
+ 'field': column_name,
+ }
+ }
+ else:
+ return {
+ 'term': {
+ column_name: value,
+ }
+ }
+
+ if lookup == 'isnull':
+ if value:
+ return {
+ 'missing': {
+ 'field': column_name,
+ }
+ }
+ else:
+ return {
+ 'exists': {
+ 'field': column_name,
+ }
+ }
+
+ if lookup in ['startswith', 'prefix']:
+ return {
+ 'prefix': {
+ column_name: value,
+ }
+ }
+
+ if lookup in ['gt', 'gte', 'lt', 'lte']:
+ return {
+ 'range': {
+ column_name: {
+ lookup: value,
+ }
+ }
+ }
+
+ if lookup == 'range':
+ lower, upper = value
+
+ return {
+ 'range': {
+ column_name: {
+ 'gte': lower,
+ 'lte': upper,
+ }
+ }
+ }
+
+ if lookup == 'in':
+ return {
+ 'terms': {
+ column_name: list(value),
+ }
+ }
+
+ def _connect_filters(self, filters, connector, negated):
+ if filters:
+ if len(filters) == 1:
+ filter_out = filters[0]
+ else:
+ filter_out = {
+ connector.lower(): [
+ fil for fil in filters if fil is not None
+ ]
+ }
+
+ if negated:
+ filter_out = {
+ 'not': filter_out
+ }
+
+ return filter_out
+
+ def get_inner_query(self):
+ if self.query_string is not None:
+ fields = self.fields or ['_all', '_partials']
+
+ if len(fields) == 1:
+ if self.operator == 'or':
+ query = {
+ 'match': {
+ fields[0]: self.query_string,
+ }
+ }
+ else:
+ query = {
+ 'match': {
+ fields[0]: {
+ 'query': self.query_string,
+ 'operator': self.operator,
+ }
+ }
+ }
+ else:
+ query = {
+ 'multi_match': {
+ 'query': self.query_string,
+ 'fields': fields,
+ }
+ }
+
+ if self.operator != 'or':
+ query['multi_match']['operator'] = self.operator
+ else:
+ query = {
+ 'match_all': {}
+ }
+
+ return query
+
+ def get_content_type_filter(self):
+ return {
+ 'prefix': {
+ 'content_type': self.queryset.model.indexed_get_content_type()
+ }
+ }
+
+ def get_filters(self):
+ filters = []
+
+ # Filter by content type
+ filters.append(self.get_content_type_filter())
+
+ # Apply filters from queryset
+ queryset_filters = self._get_filters_from_queryset()
+ if queryset_filters:
+ filters.append(queryset_filters)
+
+ return filters
+
+ def get_query(self):
+ inner_query = self.get_inner_query()
+ filters = self.get_filters()
+
+ if len(filters) == 1:
+ return {
+ 'filtered': {
+ 'query': inner_query,
+ 'filter': filters[0],
+ }
+ }
+ elif len(filters) > 1:
+ return {
+ 'filtered': {
+ 'query': inner_query,
+ 'filter': {
+ 'and': filters,
+ }
+ }
+ }
+ else:
+ return inner_query
+
+ def get_sort(self):
+ # Ordering by relevance is the default in Elasticsearch
+ if self.order_by_relevance:
+ return
+
+ # Get queryset and make sure its ordered
+ if self.queryset.ordered:
+ order_by_fields = self.queryset.query.order_by
+ sort = []
+
+ for order_by_field in order_by_fields:
+ reverse = False
+ field_name = order_by_field
+
+ if order_by_field.startswith('-'):
+ reverse = True
+ field_name = order_by_field[1:]
+
+ field = self._get_filterable_field(field_name)
+ column_name = self.mapping.get_field_column_name(field)
+
+ sort.append({
+ column_name: 'desc' if reverse else 'asc'
+ })
+
+ return sort
+
+ else:
+ # Order by pk field
+ return ['pk']
+
+ def __repr__(self):
+ return json.dumps(self.get_query())
+
+
+class ElasticsearchSearchResults(BaseSearchResults):
+ fields_param_name = 'fields'
+
+ def _get_es_body(self, for_count=False):
+ body = {
+ 'query': self.query.get_query()
+ }
+
+ if not for_count:
+ sort = self.query.get_sort()
+
+ if sort is not None:
+ body['sort'] = sort
+
+ return body
+
+ def _do_search(self):
+ # Params for elasticsearch query
+ params = dict(
+ index=self.backend.get_index_for_model(self.query.queryset.model).name,
+ body=self._get_es_body(),
+ _source=False,
+ from_=self.start,
+ )
+
+ params[self.fields_param_name] = 'pk'
+
+ # Add size if set
+ if self.stop is not None:
+ params['size'] = self.stop - self.start
+ # Send to Elasticsearch
+ hits = self.backend.es.search(**params)
+
+ # Get pks from results
+ pks = [hit['fields']['pk'][0] for hit in hits['hits']['hits']]
+ scores = {str(hit['fields']['pk'][0]): hit['_score'] for hit in hits['hits']['hits']}
+
+ # Initialise results dictionary
+ results = dict((str(pk), None) for pk in pks)
+
+ # Find objects in database and add them to dict
+ queryset = self.query.queryset.filter(pk__in=pks)
+ for obj in queryset:
+ results[str(obj.pk)] = obj
+
+ if self._score_field:
+ setattr(obj, self._score_field, scores.get(str(obj.pk)))
+
+ # Return results in order given by Elasticsearch
+ return [results[str(pk)] for pk in pks if results[str(pk)]]
+
+ def _do_count(self):
+ # Get count
+ hit_count = self.backend.es.count(
+ index=self.backend.get_index_for_model(self.query.queryset.model).name,
+ body=self._get_es_body(for_count=True),
+ )['count']
+
+ # Add limits
+ hit_count -= self.start
+ if self.stop is not None:
+ hit_count = min(hit_count, self.stop - self.start)
+
+ return max(hit_count, 0)
+
+
+class ElasticsearchIndex(object):
+ def __init__(self, backend, name):
+ self.backend = backend
+ self.es = backend.es
+ self.mapping_class = backend.mapping_class
+ self.name = name
+
+ def put(self):
+ self.es.indices.create(self.name, self.backend.settings)
+
+ def delete(self):
+ try:
+ self.es.indices.delete(self.name)
+ except NotFoundError:
+ pass
+
+ def exists(self):
+ return self.es.indices.exists(self.name)
+
+ def is_alias(self):
+ return self.es.indices.exists_alias(self.name)
+
+ def aliased_indices(self):
+ """
+ If this index object represents an alias (which appear the same in the
+ Elasticsearch API), this method can be used to fetch the list of indices
+ the alias points to.
+
+ Use the is_alias method if you need to find out if this an alias. This
+ returns an empty list if called on an index.
+ """
+ return [
+ self.backend.index_class(self.backend, index_name)
+ for index_name in self.es.indices.get_alias(name=self.name).keys()
+ ]
+
+ def put_alias(self, name):
+ """
+ Creates a new alias to this index. If the alias already exists it will
+ be repointed to this index.
+ """
+ self.es.indices.put_alias(name=name, index=self.name)
+
+ def add_model(self, model):
+ # Get mapping
+ mapping = self.mapping_class(model)
+
+ # Put mapping
+ self.es.indices.put_mapping(
+ index=self.name, doc_type=mapping.get_document_type(), body=mapping.get_mapping()
+ )
+
+ def add_item(self, item):
+ # Make sure the object can be indexed
+ if not class_is_indexed(item.__class__):
+ return
+
+ # Get mapping
+ mapping = self.mapping_class(item.__class__)
+
+ # Add document to index
+ self.es.index(
+ self.name, mapping.get_document_type(), mapping.get_document(item), id=mapping.get_document_id(item)
+ )
+
+ def add_items(self, model, items):
+ if not class_is_indexed(model):
+ return
+
+ # Get mapping
+ mapping = self.mapping_class(model)
+ doc_type = mapping.get_document_type()
+
+ # Create list of actions
+ actions = []
+ for item in items:
+ # Create the action
+ action = {
+ '_index': self.name,
+ '_type': doc_type,
+ '_id': mapping.get_document_id(item),
+ }
+ action.update(mapping.get_document(item))
+ actions.append(action)
+
+ # Run the actions
+ bulk(self.es, actions)
+
+ def delete_item(self, item):
+ # Make sure the object can be indexed
+ if not class_is_indexed(item.__class__):
+ return
+
+ # Get mapping
+ mapping = self.mapping_class(item.__class__)
+
+ # Delete document
+ try:
+ self.es.delete(
+ self.name,
+ mapping.get_document_type(),
+ mapping.get_document_id(item),
+ )
+ except NotFoundError:
+ pass # Document doesn't exist, ignore this exception
+
+ def refresh(self):
+ self.es.indices.refresh(self.name)
+
+ def reset(self):
+ # Delete old index
+ self.delete()
+
+ # Create new index
+ self.put()
+
+
+class ElasticsearchIndexRebuilder(object):
+ def __init__(self, index):
+ self.index = index
+
+ def reset_index(self):
+ self.index.reset()
+
+ def start(self):
+ # Reset the index
+ self.reset_index()
+
+ return self.index
+
+ def finish(self):
+ self.index.refresh()
+
+
+class ElasticsearchAtomicIndexRebuilder(ElasticsearchIndexRebuilder):
+ def __init__(self, index):
+ self.alias = index
+ self.index = index.backend.index_class(
+ index.backend,
+ self.alias.name + '_' + get_random_string(7).lower()
+ )
+
+ def reset_index(self):
+ # Delete old index using the alias
+ # This should delete both the alias and the index
+ self.alias.delete()
+
+ # Create new index
+ self.index.put()
+
+ # Create a new alias
+ self.index.put_alias(self.alias.name)
+
+ def start(self):
+ # Create the new index
+ self.index.put()
+
+ return self.index
+
+ def finish(self):
+ self.index.refresh()
+
+ if self.alias.is_alias():
+ # Update existing alias, then delete the old index
+
+ # Find index that alias currently points to, we'll delete it after
+ # updating the alias
+ old_index = self.alias.aliased_indices()
+
+ # Update alias to point to new index
+ self.index.put_alias(self.alias.name)
+
+ # Delete old index
+ # aliased_indices() can return multiple indices. Delete them all
+ for index in old_index:
+ if index.name != self.index.name:
+ index.delete()
+
+ else:
+ # self.alias doesn't currently refer to an alias in Elasticsearch.
+ # This means that either nothing exists in ES with that name or
+ # there is currently an index with the that name
+
+ # Run delete on the alias, just in case it is currently an index.
+ # This happens on the first rebuild after switching ATOMIC_REBUILD on
+ self.alias.delete()
+
+ # Create the alias
+ self.index.put_alias(self.alias.name)
+
+
+class ElasticsearchSearchBackend(BaseSearchBackend):
+ index_class = ElasticsearchIndex
+ query_class = ElasticsearchSearchQuery
+ results_class = ElasticsearchSearchResults
+ mapping_class = ElasticsearchMapping
+ basic_rebuilder_class = ElasticsearchIndexRebuilder
+ atomic_rebuilder_class = ElasticsearchAtomicIndexRebuilder
+
+ settings = {
+ 'settings': {
+ 'analysis': {
+ 'analyzer': {
+ 'ngram_analyzer': {
+ 'type': 'custom',
+ 'tokenizer': 'lowercase',
+ 'filter': ['asciifolding', 'ngram']
+ },
+ 'edgengram_analyzer': {
+ 'type': 'custom',
+ 'tokenizer': 'lowercase',
+ 'filter': ['asciifolding', 'edgengram']
+ }
+ },
+ 'tokenizer': {
+ 'ngram_tokenizer': {
+ 'type': 'nGram',
+ 'min_gram': 3,
+ 'max_gram': 15,
+ },
+ 'edgengram_tokenizer': {
+ 'type': 'edgeNGram',
+ 'min_gram': 2,
+ 'max_gram': 15,
+ 'side': 'front'
+ }
+ },
+ 'filter': {
+ 'ngram': {
+ 'type': 'nGram',
+ 'min_gram': 3,
+ 'max_gram': 15
+ },
+ 'edgengram': {
+ 'type': 'edgeNGram',
+ 'min_gram': 1,
+ 'max_gram': 15
+ }
+ }
+ }
+ }
+ }
+
+ def __init__(self, params):
+ super(ElasticsearchSearchBackend, self).__init__(params)
+
+ # Get settings
+ self.hosts = params.pop('HOSTS', None)
+ self.index_name = params.pop('INDEX', 'wagtail')
+ self.timeout = params.pop('TIMEOUT', 10)
+
+ if params.pop('ATOMIC_REBUILD', False):
+ self.rebuilder_class = self.atomic_rebuilder_class
+ else:
+ self.rebuilder_class = self.basic_rebuilder_class
+
+ # If HOSTS is not set, convert URLS setting to HOSTS
+ es_urls = params.pop('URLS', ['http://localhost:9200'])
+ if self.hosts is None:
+ self.hosts = []
+
+ for url in es_urls:
+ parsed_url = urlparse(url)
+
+ use_ssl = parsed_url.scheme == 'https'
+ port = parsed_url.port or (443 if use_ssl else 80)
+
+ http_auth = None
+ if parsed_url.username is not None and parsed_url.password is not None:
+ http_auth = (parsed_url.username, parsed_url.password)
+
+ self.hosts.append({
+ 'host': parsed_url.hostname,
+ 'port': port,
+ 'url_prefix': parsed_url.path,
+ 'use_ssl': use_ssl,
+ 'verify_certs': use_ssl,
+ 'http_auth': http_auth,
+ })
+
+ self.settings = copy.deepcopy(self.settings)
+
+ # Get Elasticsearch interface
+ # Any remaining params are passed into the Elasticsearch constructor
+ options = params.pop('OPTIONS', {})
+ self.es = Elasticsearch(
+ hosts=self.hosts,
+ timeout=self.timeout,
+ **options)
+
+ def get_index_for_model(self, model):
+ return self.index_class(self, self.index_name)
+
+ def get_index(self):
+ return self.index_class(self, self.index_name)
+
+ def get_rebuilder(self):
+ return self.rebuilder_class(self.get_index())
+
+ def reset_index(self):
+ # Use the rebuilder to reset the index
+ self.get_rebuilder().reset_index()
+
+ def add_type(self, model):
+ self.get_index_for_model(model).add_model(model)
+
+ def refresh_index(self):
+ self.get_index().refresh()
+
+ def add(self, obj):
+ self.get_index_for_model(type(obj)).add_item(obj)
+
+ def add_bulk(self, model, obj_list):
+ self.get_index_for_model(model).add_items(model, obj_list)
+
+ def delete(self, obj):
+ self.get_index_for_model(type(obj)).delete_item(obj)
+
+
+SearchBackend = ElasticsearchSearchBackend
diff --git a/saleor/search/backends/elasticsearch2.py b/saleor/search/backends/elasticsearch2.py
new file mode 100644
index 0000000000..f62d9d883e
--- /dev/null
+++ b/saleor/search/backends/elasticsearch2.py
@@ -0,0 +1,153 @@
+from __future__ import absolute_import, unicode_literals
+
+from ..index import FilterField, RelatedFields, SearchField
+
+from .elasticsearch import (
+ ElasticsearchIndex, ElasticsearchMapping, ElasticsearchSearchBackend, ElasticsearchSearchQuery,
+ ElasticsearchSearchResults)
+
+
+def get_model_root(model):
+ """
+ This function finds the root model for any given model. The root model is
+ the highest concrete model that it descends from. If the model doesn't
+ descend from another concrete model then the model is it's own root model so
+ it is returned.
+
+ Examples:
+ >>> get_model_root(wagtailcore.Page)
+ wagtailcore.Page
+
+ >>> get_model_root(myapp.HomePage)
+ wagtailcore.Page
+
+ >>> get_model_root(wagtailimages.Image)
+ wagtailimages.Image
+ """
+ if model._meta.parents:
+ parent_model = list(model._meta.parents.items())[0][0]
+ return get_model_root(parent_model)
+
+ return model
+
+
+class Elasticsearch2Mapping(ElasticsearchMapping):
+ edgengram_analyzer_config = {
+ 'analyzer': 'edgengram_analyzer',
+ 'search_analyzer': 'standard',
+ }
+
+ def get_field_column_name(self, field):
+ # Fields in derived models get prefixed with their model name, fields
+ # in the root model don't get prefixed at all
+ # This is to prevent mapping clashes in cases where two page types have
+ # a field with the same name but a different type.
+ root_model = get_model_root(self.model)
+ definition_model = field.get_definition_model(self.model)
+
+ if definition_model != root_model:
+ prefix = definition_model._meta.app_label.lower() + '_' + definition_model.__name__.lower() + '__'
+ else:
+ prefix = ''
+
+ if isinstance(field, FilterField):
+ return prefix + field.get_attname(self.model) + '_filter'
+ elif isinstance(field, SearchField):
+ return prefix + field.get_attname(self.model)
+ elif isinstance(field, RelatedFields):
+ return prefix + field.field_name
+
+ def get_content_type(self):
+ """
+ Returns the content type as a string for the model.
+
+ For example: "wagtailcore.Page"
+ "myapp.MyModel"
+ """
+ return self.model._meta.app_label + '.' + self.model.__name__
+
+ def get_all_content_types(self):
+ """
+ Returns all the content type strings that apply to this model.
+ This includes the models' content type and all concrete ancestor
+ models that inherit from Indexed.
+
+ For example: ["myapp.MyPageModel", "wagtailcore.Page"]
+ ["myapp.MyModel"]
+ """
+ # Add our content type
+ content_types = [self.get_content_type()]
+
+ # Add all ancestor classes content types as well
+ ancestor = self.get_parent()
+ while ancestor:
+ content_types.append(ancestor.get_content_type())
+ ancestor = ancestor.get_parent()
+
+ return content_types
+
+ def get_document(self, obj):
+ # In the Elasticsearch 2 backend, we use a more efficient way to
+ # represent the content type of a document.
+
+ # Instead of using a long string of model names that is queried using a
+ # "prefix" query, we instead use a multi-value string field and query it
+ # using a simple "match" query.
+
+ # The only reason why this isn't implemented in the Elasticsearch 1.x
+ # backend yet is backwards compatibility
+ doc = super(Elasticsearch2Mapping, self).get_document(obj)
+ doc['content_type'] = self.get_all_content_types()
+ return doc
+
+
+class Elasticsearch2Index(ElasticsearchIndex):
+ def add_model(self, model):
+ # Get mapping
+ mapping = self.mapping_class(model)
+
+ # Put mapping
+ self.es.indices.put_mapping(
+ # pass update_all_types=True as a workaround to avoid "Can't redefine search field" errors -
+ # see https://github.com/torchbox/wagtail/issues/2968
+ index=self.name, doc_type=mapping.get_document_type(), body=mapping.get_mapping(),
+ update_all_types=True
+ )
+
+
+class Elasticsearch2SearchQuery(ElasticsearchSearchQuery):
+ mapping_class = Elasticsearch2Mapping
+
+ def get_content_type_filter(self):
+ # Query content_type using a "match" query. See comment in
+ # Elasticsearch2Mapping.get_document for more details
+ content_type = self.mapping_class(self.queryset.model).get_content_type()
+
+ return {
+ 'match': {
+ 'content_type': content_type
+ }
+ }
+
+
+class Elasticsearch2SearchResults(ElasticsearchSearchResults):
+ pass
+
+
+class Elasticsearch2SearchBackend(ElasticsearchSearchBackend):
+ mapping_class = Elasticsearch2Mapping
+ index_class = Elasticsearch2Index
+ query_class = Elasticsearch2SearchQuery
+ results_class = Elasticsearch2SearchResults
+
+ def get_index_for_model(self, model):
+ # Split models up into separate indices based on their root model.
+ # For example, all page-derived models get put together in one index,
+ # while images and documents each have their own index.
+ root_model = get_model_root(model)
+ index_suffix = '__' + root_model._meta.app_label.lower() + '_' + root_model.__name__.lower()
+
+ return self.index_class(self, self.index_name + index_suffix)
+
+
+SearchBackend = Elasticsearch2SearchBackend
diff --git a/saleor/search/backends/elasticsearch5.py b/saleor/search/backends/elasticsearch5.py
new file mode 100644
index 0000000000..92e7be5351
--- /dev/null
+++ b/saleor/search/backends/elasticsearch5.py
@@ -0,0 +1,84 @@
+from __future__ import absolute_import, unicode_literals
+
+from .elasticsearch2 import (
+ Elasticsearch2Index, Elasticsearch2Mapping, Elasticsearch2SearchBackend,
+ Elasticsearch2SearchQuery, Elasticsearch2SearchResults)
+
+
+class Elasticsearch5Mapping(Elasticsearch2Mapping):
+ keyword_type = 'keyword'
+ text_type = 'text'
+ set_index_not_analyzed_on_filter_fields = False
+
+
+class Elasticsearch5Index(Elasticsearch2Index):
+ pass
+
+
+class Elasticsearch5SearchQuery(Elasticsearch2SearchQuery):
+ mapping_class = Elasticsearch5Mapping
+
+ def _connect_filters(self, filters, connector, negated):
+ if filters:
+ if len(filters) == 1:
+ filter_out = filters[0]
+ elif connector == 'AND':
+ filter_out = {
+ 'bool': {
+ 'must': [
+ fil for fil in filters if fil is not None
+ ]
+ }
+ }
+ elif connector == 'OR':
+ filter_out = {
+ 'bool': {
+ 'should': [
+ fil for fil in filters if fil is not None
+ ]
+ }
+ }
+
+ if negated:
+ filter_out = {
+ 'bool': {
+ 'mustNot': filter_out
+ }
+ }
+
+ return filter_out
+
+ def get_query(self):
+ inner_query = self.get_inner_query()
+ filters = self.get_filters()
+
+ if len(filters) == 1:
+ return {
+ 'bool': {
+ 'must': inner_query,
+ 'filter': filters[0],
+ }
+ }
+ elif len(filters) > 1:
+ return {
+ 'bool': {
+ 'must': inner_query,
+ 'filter': filters,
+ }
+ }
+ else:
+ return inner_query
+
+
+class Elasticsearch5SearchResults(Elasticsearch2SearchResults):
+ fields_param_name = 'stored_fields'
+
+
+class Elasticsearch5SearchBackend(Elasticsearch2SearchBackend):
+ mapping_class = Elasticsearch5Mapping
+ index_class = Elasticsearch5Index
+ query_class = Elasticsearch5SearchQuery
+ results_class = Elasticsearch5SearchResults
+
+
+SearchBackend = Elasticsearch5SearchBackend
diff --git a/saleor/search/forms.py b/saleor/search/forms.py
new file mode 100644
index 0000000000..19592aef35
--- /dev/null
+++ b/saleor/search/forms.py
@@ -0,0 +1,13 @@
+from django import forms
+
+from .backends import get_search_backend
+
+
+class SearchForm(forms.Form):
+ q = forms.CharField(label='Query', required=True)
+
+ def search(self, model_or_queryset):
+ backend = get_search_backend('default')
+ query = self.cleaned_data['q']
+ results = backend.search(query, model_or_queryset=model_or_queryset)
+ return results
diff --git a/saleor/search/index.py b/saleor/search/index.py
new file mode 100644
index 0000000000..a8023dec7b
--- /dev/null
+++ b/saleor/search/index.py
@@ -0,0 +1,277 @@
+from __future__ import absolute_import, unicode_literals
+
+import inspect
+import logging
+
+from django.apps import apps
+from django.core import checks
+from django.db import models
+from django.db.models.fields import FieldDoesNotExist
+from django.db.models.fields.related import ForeignObjectRel, OneToOneRel, RelatedField
+
+from .backends import get_search_backends_with_name
+
+
+logger = logging.getLogger('wagtail.search.index')
+
+
+class Indexed(object):
+ @classmethod
+ def indexed_get_parent(cls, require_model=True):
+ for base in cls.__bases__:
+ if issubclass(base, Indexed) and (issubclass(base, models.Model) or require_model is False):
+ return base
+
+ @classmethod
+ def indexed_get_content_type(cls):
+ # Work out content type
+ content_type = (cls._meta.app_label + '_' + cls.__name__).lower()
+
+ # Get parent content type
+ parent = cls.indexed_get_parent()
+ if parent:
+ parent_content_type = parent.indexed_get_content_type()
+ return parent_content_type + '_' + content_type
+ else:
+ return content_type
+
+ @classmethod
+ def indexed_get_toplevel_content_type(cls):
+ # Get parent content type
+ parent = cls.indexed_get_parent()
+ if parent:
+ return parent.indexed_get_content_type()
+ else:
+ # At toplevel, return this content type
+ return (cls._meta.app_label + '_' + cls.__name__).lower()
+
+ @classmethod
+ def get_search_fields(cls):
+ search_fields = {}
+
+ for field in cls.search_fields:
+ search_fields[(type(field), field.field_name)] = field
+
+ return list(search_fields.values())
+
+ @classmethod
+ def get_searchable_search_fields(cls):
+ return [
+ field for field in cls.get_search_fields()
+ if isinstance(field, SearchField)
+ ]
+
+ @classmethod
+ def get_filterable_search_fields(cls):
+ return [
+ field for field in cls.get_search_fields()
+ if isinstance(field, FilterField)
+ ]
+
+ @classmethod
+ def get_indexed_objects(cls):
+ queryset = cls.objects.all()
+
+ # Add prefetch/select related for RelatedFields
+ for field in cls.get_search_fields():
+ if isinstance(field, RelatedFields):
+ queryset = field.select_on_queryset(queryset)
+
+ return queryset
+
+ def get_indexed_instance(self):
+ """
+ If the indexed model uses multi table inheritance, override this method
+ to return the instance in its most specific class so it reindexes properly.
+ """
+ return self
+
+ @classmethod
+ def _has_field(cls, name):
+ try:
+ cls._meta.get_field(name)
+ return True
+ except models.fields.FieldDoesNotExist:
+ return hasattr(cls, name)
+
+ @classmethod
+ def check(cls, **kwargs):
+ errors = super(Indexed, cls).check(**kwargs)
+ errors.extend(cls._check_search_fields(**kwargs))
+ return errors
+
+ @classmethod
+ def _check_search_fields(cls, **kwargs):
+ errors = []
+ for field in cls.get_search_fields():
+ message = "{model}.search_fields contains field '{name}' but it doesn't exist"
+ if not cls._has_field(field.field_name):
+ errors.append(
+ checks.Warning(
+ message.format(model=cls.__name__, name=field.field_name),
+ obj=cls,
+ )
+ )
+ return errors
+
+ search_fields = []
+
+
+def get_indexed_models():
+ return [
+ model for model in apps.get_models()
+ if issubclass(model, Indexed) and not model._meta.abstract
+ ]
+
+
+def class_is_indexed(cls):
+ return issubclass(cls, Indexed) and issubclass(cls, models.Model) and not cls._meta.abstract
+
+
+def get_indexed_instance(instance, check_exists=True):
+ indexed_instance = instance.get_indexed_instance()
+ if indexed_instance is None:
+ return
+
+ # Make sure that the instance is in its class's indexed objects
+ if check_exists and not type(indexed_instance).get_indexed_objects().filter(pk=indexed_instance.pk).exists():
+ return
+
+ return indexed_instance
+
+
+def insert_or_update_object(instance):
+ indexed_instance = get_indexed_instance(instance)
+
+ if indexed_instance:
+ for backend_name, backend in get_search_backends_with_name(with_auto_update=True):
+ try:
+ backend.add(indexed_instance)
+ except Exception:
+ # Catch and log all errors
+ logger.exception("Exception raised while adding %r into the '%s' search backend", indexed_instance, backend_name)
+
+
+def remove_object(instance):
+ indexed_instance = get_indexed_instance(instance, check_exists=False)
+
+ if indexed_instance:
+ for backend_name, backend in get_search_backends_with_name(with_auto_update=True):
+ try:
+ backend.delete(indexed_instance)
+ except Exception:
+ # Catch and log all errors
+ logger.exception("Exception raised while deleting %r from the '%s' search backend", indexed_instance, backend_name)
+
+
+class BaseField(object):
+ def __init__(self, field_name, **kwargs):
+ self.field_name = field_name
+ self.kwargs = kwargs
+
+ def get_field(self, cls):
+ return cls._meta.get_field(self.field_name)
+
+ def get_attname(self, cls):
+ try:
+ field = self.get_field(cls)
+ return field.attname
+ except models.fields.FieldDoesNotExist:
+ return self.field_name
+
+ def get_definition_model(self, cls):
+ try:
+ field = self.get_field(cls)
+ return field.model
+ except models.fields.FieldDoesNotExist:
+ # Find where it was defined by walking the inheritance tree
+ for base_cls in inspect.getmro(cls):
+ if self.field_name in base_cls.__dict__:
+ return base_cls
+
+ def get_type(self, cls):
+ if 'type' in self.kwargs:
+ return self.kwargs['type']
+
+ try:
+ field = self.get_field(cls)
+ return field.get_internal_type()
+ except models.fields.FieldDoesNotExist:
+ return 'CharField'
+
+ def get_value(self, obj):
+ try:
+ field = self.get_field(obj.__class__)
+ value = field.value_from_object(obj)
+ if hasattr(field, 'get_searchable_content'):
+ value = field.get_searchable_content(value)
+ return value
+ except models.fields.FieldDoesNotExist:
+ value = getattr(obj, self.field_name, None)
+ if hasattr(value, '__call__'):
+ value = value()
+ return value
+
+ def __repr__(self):
+ return '<%s: %s>' % (self.__class__.__name__, self.field_name)
+
+
+class SearchField(BaseField):
+ def __init__(self, field_name, boost=None, partial_match=False, **kwargs):
+ super(SearchField, self).__init__(field_name, **kwargs)
+ self.boost = boost
+ self.partial_match = partial_match
+
+
+class FilterField(BaseField):
+ pass
+
+
+class RelatedFields(object):
+ def __init__(self, field_name, fields):
+ self.field_name = field_name
+ self.fields = fields
+
+ def get_field(self, cls):
+ return cls._meta.get_field(self.field_name)
+
+ def get_definition_model(self, cls):
+ field = self.get_field(cls)
+ return field.model
+
+ def get_value(self, obj):
+ field = self.get_field(obj.__class__)
+
+ if isinstance(field, RelatedField):
+ return getattr(obj, self.field_name)
+
+ def select_on_queryset(self, queryset):
+ """
+ This method runs either prefetch_related or select_related on the queryset
+ to improve indexing speed of the relation.
+
+ It decides which method to call based on the number of related objects:
+ - single (eg ForeignKey, OneToOne), it runs select_related
+ - multiple (eg ManyToMany, reverse ForeignKey) it runs prefetch_related
+ """
+ try:
+ field = self.get_field(queryset.model)
+ except FieldDoesNotExist:
+ return queryset
+
+ if isinstance(field, RelatedField):
+ if field.many_to_one or field.one_to_one:
+ queryset = queryset.select_related(self.field_name)
+ elif field.one_to_many or field.many_to_many:
+ queryset = queryset.prefetch_related(self.field_name)
+
+ elif isinstance(field, ForeignObjectRel):
+ # Reverse relation
+ if isinstance(field, OneToOneRel):
+ # select_related for reverse OneToOneField
+ queryset = queryset.select_related(self.field_name)
+ else:
+ # prefetch_related for anything else (reverse ForeignKey/ManyToManyField)
+ queryset = queryset.prefetch_related(self.field_name)
+
+ return queryset
diff --git a/saleor/search/management/__init__.py b/saleor/search/management/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/search/management/commands/__init__.py b/saleor/search/management/commands/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/search/management/commands/update_index.py b/saleor/search/management/commands/update_index.py
new file mode 100644
index 0000000000..338a1cfdbc
--- /dev/null
+++ b/saleor/search/management/commands/update_index.py
@@ -0,0 +1,163 @@
+from __future__ import absolute_import, unicode_literals
+
+import collections
+
+from django.conf import settings
+from django.core.management.base import BaseCommand
+from django.db import transaction
+
+from ...backends import get_search_backend
+from ...index import get_indexed_models
+
+
+def group_models_by_index(backend, models):
+ """
+ This takes a search backend and a list of models. By calling the
+ get_index_for_model method on the search backend, it groups the models into
+ the indices that they will be indexed into.
+
+ It returns an ordered mapping of indices to lists of models within each
+ index.
+
+ For example, Elasticsearch 2 requires all page models to be together, but
+ separate from other content types (eg, images and documents) to prevent
+ field mapping collisions (eg, images and documents):
+
+ >>> group_models_by_index(elasticsearch2_backend, [
+ ... wagtailcore.Page,
+ ... myapp.HomePage,
+ ... myapp.StandardPage,
+ ... wagtailimages.Image
+ ... ])
+ {
+ <Index wagtailcore_page>: [wagtailcore.Page, myapp.HomePage, myapp.StandardPage],
+ <Index wagtailimages_image>: [wagtailimages.Image],
+ }
+ """
+ indices = {}
+ models_by_index = collections.OrderedDict()
+
+ for model in models:
+ index = backend.get_index_for_model(model)
+
+ if index:
+ indices.setdefault(index.name, index)
+ models_by_index.setdefault(index.name, [])
+ models_by_index[index.name].append(model)
+
+ return collections.OrderedDict([
+ (indices[index_name], index_models)
+ for index_name, index_models in models_by_index.items()
+ ])
+
+
+class Command(BaseCommand):
+ def update_backend(self, backend_name, schema_only=False):
+ self.stdout.write("Updating backend: " + backend_name)
+
+ backend = get_search_backend(backend_name)
+
+ if not backend.rebuilder_class:
+ self.stdout.write("Backend '%s' doesn't require rebuilding" % backend_name)
+ return
+
+ models_grouped_by_index = group_models_by_index(backend, get_indexed_models()).items()
+ if not models_grouped_by_index:
+ self.stdout.write(backend_name + ": No indices to rebuild")
+
+ for index, models in models_grouped_by_index:
+ self.stdout.write(backend_name + ": Rebuilding index %s" % index.name)
+
+ # Start rebuild
+ rebuilder = backend.rebuilder_class(index)
+ index = rebuilder.start()
+
+ # Add models
+ for model in models:
+ index.add_model(model)
+
+ # Add objects
+ object_count = 0
+ if not schema_only:
+ for model in models:
+ self.stdout.write('{}: {}.{} '.format(backend_name, model._meta.app_label, model.__name__).ljust(35), ending='')
+
+ # Add items (1000 at a time)
+ for chunk in self.print_iter_progress(self.queryset_chunks(model.get_indexed_objects())):
+ index.add_items(model, chunk)
+ object_count += len(chunk)
+
+ self.print_newline()
+
+ # Finish rebuild
+ rebuilder.finish()
+
+ self.stdout.write(backend_name + ": indexed %d objects" % object_count)
+ self.print_newline()
+
+ def add_arguments(self, parser):
+ parser.add_argument(
+ '--backend', action='store', dest='backend_name', default=None,
+ help="Specify a backend to update")
+ parser.add_argument(
+ '--schema-only', action='store_true', dest='schema_only', default=False,
+ help="Prevents loading any data into the index")
+
+ def handle(self, **options):
+ # Get list of backends to index
+ if options['backend_name']:
+ # index only the passed backend
+ backend_names = [options['backend_name']]
+ elif hasattr(settings, 'WAGTAILSEARCH_BACKENDS'):
+ # index all backends listed in settings
+ backend_names = settings.WAGTAILSEARCH_BACKENDS.keys()
+ else:
+ # index the 'default' backend only
+ backend_names = ['default']
+
+ # Update backends
+ for backend_name in backend_names:
+ self.update_backend(backend_name, schema_only=options['schema_only'])
+
+ def print_newline(self):
+ self.stdout.write('')
+
+ def print_iter_progress(self, iterable):
+ """
+ Print a progress meter while iterating over an iterable. Use it as part
+ of a ``for`` loop::
+
+ for item in self.print_iter_progress(big_long_list):
+ self.do_expensive_computation(item)
+
+ A ``.`` character is printed for every value in the iterable,
+ a space every 10 items, and a new line every 50 items.
+ """
+ for i, value in enumerate(iterable, start=1):
+ yield value
+ self.stdout.write('.', ending='')
+ if i % 40 == 0:
+ self.print_newline()
+ self.stdout.write(' ' * 35, ending='')
+
+ elif i % 10 == 0:
+ self.stdout.write(' ', ending='')
+
+ self.stdout.flush()
+
+ # Atomic so the count of models doesnt change as it is iterated
+ @transaction.atomic
+ def queryset_chunks(self, qs, chunk_size=1000):
+ """
+ Yield a queryset in chunks of at most ``chunk_size``. The chunk yielded
+ will be a list, not a queryset. Iterating over the chunks is done in a
+ transaction so that the order and count of items in the queryset
+ remains stable.
+ """
+ i = 0
+ while True:
+ items = list(qs[i * chunk_size:][:chunk_size])
+ if not items:
+ break
+ yield items
+ i += 1
diff --git a/saleor/search/migrations/__init__.py b/saleor/search/migrations/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/search/urls.py b/saleor/search/urls.py
new file mode 100644
index 0000000000..163425966d
--- /dev/null
+++ b/saleor/search/urls.py
@@ -0,0 +1,10 @@
+from __future__ import unicode_literals
+
+from django.conf.urls import url
+
+from . import views
+
+
+urlpatterns = [
+ url(r'^$', views.search, name='search')
+]
diff --git a/saleor/search/views.py b/saleor/search/views.py
new file mode 100644
index 0000000000..aca02a1ff3
--- /dev/null
+++ b/saleor/search/views.py
@@ -0,0 +1,34 @@
+from __future__ import unicode_literals
+
+from django.core.paginator import Paginator, InvalidPage
+from django.conf import settings
+from django.http import Http404
+from django.shortcuts import render
+from .forms import SearchForm
+from ..product.utils import products_with_details
+
+
+def paginate_results(results, get_data, paginate_by=25):
+ paginator = Paginator(results, paginate_by)
+ page_number = get_data.get('page', 1)
+ try:
+ page = paginator.page(page_number)
+ except InvalidPage:
+ raise Http404('No such page!')
+ return page
+
+
+def search(request):
+ form = SearchForm(data=request.GET or None)
+ if form.is_valid():
+ visible_products = products_with_details(request.user)
+ results = form.search(model_or_queryset=visible_products)
+ page = paginate_results(results, request.GET, settings.PAGINATE_BY)
+ else:
+ page = form.no_query_found()
+ query = form.cleaned_data['q']
+ ctx = {
+ 'query': query,
+ 'results': page,
+ 'query_string': '?q=%s' % query}
+ return render(request, 'search/results.html', ctx)
diff --git a/saleor/urls.py b/saleor/urls.py
index 269061899a..cd1b8cfec1 100644
--- a/saleor/urls.py
+++ b/saleor/urls.py
@@ -11,6 +11,7 @@ from .core.sitemaps import sitemaps
from .core.urls import urlpatterns as core_urls
from .order.urls import urlpatterns as order_urls
from .product.urls import urlpatterns as product_urls
+from .search.urls import urlpatterns as search_urls
from .userprofile.urls import urlpatterns as userprofile_urls
from .dashboard.urls import urlpatterns as dashboard_urls
@@ -27,6 +28,7 @@ urlpatterns = [
url(r'^order/', include(order_urls, namespace='order')),
url(r'^products/', include(product_urls, namespace='product')),
url(r'^profile/', include(userprofile_urls, namespace='profile')),
+ url(r'^search/', include(search_urls, namespace='search')),
url(r'^selectable/', include('selectable.urls')),
url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps},
name='django.contrib.sitemaps.views.sitemap'),
diff --git a/templates/base.html b/templates/base.html
index 2ef63f00ef..c7f667c629 100644
--- a/templates/base.html
+++ b/templates/base.html
@@ -71,6 +71,7 @@
</li>
{% endif %}
</ul>
+ {% include "search/search_form.html" %}
</div>
</nav>
</header>
diff --git a/templates/search/_items.html b/templates/search/_items.html
new file mode 100644
index 0000000000..77bd1d9e23
--- /dev/null
+++ b/templates/search/_items.html
@@ -0,0 +1,36 @@
+{% load i18n %}
+{% load staticfiles %}
+{% load price_range from price_ranges %}
+{% load discounted_price_range price_difference from discount %}
+
+{% for product in results %}
+ <div class="col-xs-12 col-sm-6 col-md-4 col-lg-3" itemscope itemtype="https://schema.org/Product">
+ <div class="panel panel-default text-center">
+ <div class="panel-body">
+ <a itemprop="url" href="{{ product.get_absolute_url }}">
+ {% if product.images.first %}
+ <img itemprop="image" class="img-responsive" src="{{ product.images.first.image.crop.400x400 }}" alt="">
+ {% else %}
+ <img src="{% static 'images/product-image-placeholder.png' %}" alt="" class="img-responsive">
+ {% endif %}
+ <span class="product-list-item-name" itemprop="name" title="{{ product }}">{{ product }}</span>
+ </a>
+ </div>
+
+ <div class="panel-footer">
+ {% if product.is_in_stock %}
+ {% with price_range=product|discounted_price_range:request.discounts undiscounted=product.get_price_range %}
+ {% with discount=undiscounted.min_price|price_difference:price_range.min_price %}
+ {% price_range price_range %}
+ {% if undiscounted.min_price != price_range.min_price %}
+ <span class="label label-success">{% trans "Discount!" %}</span>
+ {% endif %}
+ {% endwith %}
+ {% endwith %}
+ {% else %}
+ &nbsp;
+ {% endif %}
+ </div>
+ </div>
+ </div>
+{% endfor %}
diff --git a/templates/search/results.html b/templates/search/results.html
new file mode 100644
index 0000000000..807fccee87
--- /dev/null
+++ b/templates/search/results.html
@@ -0,0 +1,35 @@
+{% extends "base.html" %}
+{% load i18n %}
+{% load slice from shop %}
+{% load static from staticfiles %}
+{% load bootstrap_pagination from bootstrap3 %}
+
+{% block title %}{% trans "Search results" %} {{ block.super }}{% endblock %}
+
+{% block breadcrumb %}
+ {{ block.super }}
+ {% for breadcrumb in breadcrumbs %}
+ <li{% if forloop.last %} class="active"{% endif %}>
+ {% if not forloop.last %}
+ <a href="{{ breadcrumb.get_absolute_url }}">{{ breadcrumb }}</a>
+ {% else %}
+ <span>{{ breadcrumb }}</span>
+ {% endif %}
+ </li>
+ {% endfor %}
+{% endblock breadcrumb %}
+
+{% block content %}
+ <div class="row">
+ {% if query and results %}
+ {% include "search/_items.html" %}
+ <div class="col-md-12">
+ {% bootstrap_pagination results url=query_string %}
+ </div>
+ {% else %}
+ <div class="col-md-12">
+ <h3>{% blocktrans %}No results found{% endblocktrans %}</h3>
+ </div>
+ {% endif %}
+ </div>
+{% endblock content %}
diff --git a/templates/search/search_form.html b/templates/search/search_form.html
new file mode 100644
index 0000000000..439c3d5039
--- /dev/null
+++ b/templates/search/search_form.html
@@ -0,0 +1,12 @@
+{% if SEARCH_IS_ENABLED %}
+<form action="{% url "search:search" %}" method="get" class="navbar-form navbar-right">
+ <div class="input-group">
+ <input type="text" class="form-control" name="q" placeholder="Search..." value="{% if query %}{{ query }}{% endif %}" autofocus>
+ <span class="input-group-btn">
+ <button class="btn btn-default">
+ <span class="glyphicon glyphicon-search" aria-hidden="true"></span>
+ </button>
+ </span>
+ </div>
+</form>
+{% endif %}