Skip to content

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

Dump all legacy stuff in code

Jakub Draganek834eccc212cb
diff --git a/saleor/search/backends/__init__.py b/saleor/search/backends/__init__.py
index 2f1334f754..8b13789179 100644
--- a/saleor/search/backends/__init__.py
+++ b/saleor/search/backends/__init__.py
@@ -1,103 +1 @@
-# 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
deleted file mode 100644
index a4a747a5d7..0000000000
--- a/saleor/search/backends/base.py
+++ /dev/null
@@ -1,278 +0,0 @@
-
-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):
- """
- Wraps search query, contains all filters and query parameters.
- """
- 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):
- 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):
- """
- This class wraps search results. Core search communication is performed
- here.
- """
- 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):
- # type (int, int)
- 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):
- """
- Execute search
- """
- 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):
- """
- Applies all fillters and prefetches and constructs SearchQuery and
- SearchResult objects.
- """
- # 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()
-
- # 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
deleted file mode 100644
index 1e5c6d6e34..0000000000
--- a/saleor/search/backends/dashboard.py
+++ /dev/null
@@ -1,163 +0,0 @@
-from collections import defaultdict
-
-from . import get_search_backend
-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()}
-
-DEFAULT_BACKEND = get_search_backend('default')
-DEFAULT_BACKEND_CLASS = DEFAULT_BACKEND.__class__
-DEFAULT_BACKEND_RESULTS_CLASS = DEFAULT_BACKEND.results_class
-
-
-class DashboardSearchQuery(BaseSearchQuery):
- """
- Query that will search in multiple indexes
- """
-
- 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(DEFAULT_BACKEND_RESULTS_CLASS):
-
- def _do_search(self):
- # Params for elasticsearch query
- params = dict(
- body=self._get_es_body(),
- _source=False,
- from_=self.start,
- index='{}*'.format(self.backend.get_index().name)
- )
- 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)
- search_hits = defaultdict(list)
- scores = {}
- for hit in hits['hits']['hits']:
- hit_type = hit['_type']
- hit_pk = hit['_source']['pk']
- search_hits[hit_type].append(hit_pk)
- scores[hit['_id']] = hit['_score']
-
- # Group results by content type
- 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)
-
- # Merge results back in one list ordered by search score
- 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
-
- def _do_count(self):
- # Get count
- hit_count = self.backend.es.count(
- body=self._get_es_body(for_count=True),
- index='{}*'.format(self.backend.get_index().name)
- )['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 DashboardMultiTypeSearchBackend(DEFAULT_BACKEND_CLASS):
- 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):
- """
- Multi-model search. Parameters that affect model or database
- structure are skipped and not used in dashboard query implementation.
- """
- 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/elasticsearch.py b/saleor/search/backends/elasticsearch.py
deleted file mode 100644
index 2d8a3b4b37..0000000000
--- a/saleor/search/backends/elasticsearch.py
+++ /dev/null
@@ -1,809 +0,0 @@
-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 {
- 'bool': {
- 'must_not': {
- 'term': {
- 'field': column_name
- }
- }
- }
- }
- else:
- return {
- 'term': {
- column_name: value,
- }
- }
-
- if lookup == 'isnull':
- if value:
- return {
- 'bool': {
- 'must_not': {
- 'term': {
- '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['_source']['pk'] for hit in hits['hits']['hits']]
- scores = {str(hit['_source']['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
deleted file mode 100644
index f62d9d883e..0000000000
--- a/saleor/search/backends/elasticsearch2.py
+++ /dev/null
@@ -1,153 +0,0 @@
-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
deleted file mode 100644
index b1480c3d41..0000000000
--- a/saleor/search/backends/elasticsearch5.py
+++ /dev/null
@@ -1,84 +0,0 @@
-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 = '_source'
-
-
-class Elasticsearch5SearchBackend(Elasticsearch2SearchBackend):
- mapping_class = Elasticsearch5Mapping
- index_class = Elasticsearch5Index
- query_class = Elasticsearch5SearchQuery
- results_class = Elasticsearch5SearchResults
-
-
-SearchBackend = Elasticsearch5SearchBackend
diff --git a/saleor/search/backends/newelastic.py b/saleor/search/backends/newelastic.py
index e455e995e4..2dc4b7e20d 100644
--- a/saleor/search/backends/newelastic.py
+++ b/saleor/search/backends/newelastic.py
@@ -52,6 +52,6 @@ def search_products(phrase):
search = (ProductDocument.search()
.query(query)
.source(False)
- .filter('term', is_published=True)
- .using(SearchBackend.client)) # TODO: use default
+ .filter('term', is_published=True))
+ #.using(SearchBackend.client)) # TODO: use default
return [hit.meta.id for hit in search.execute()]
diff --git a/saleor/search/forms.py b/saleor/search/forms.py
index b051409931..4720a23bc9 100644
--- a/saleor/search/forms.py
+++ b/saleor/search/forms.py
@@ -3,7 +3,7 @@ from django.utils.translation import pgettext
from .backends import get_search_backend
-USE_BACKEND = 'default'
+USE_BACKEND = 'newelastic'
class SearchForm(forms.Form):
diff --git a/saleor/settings.py b/saleor/settings.py
index 84f5afc40c..564da97aae 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -360,34 +360,8 @@ if ELASTICSEARCH_URL:
'hosts': ELASTICSEARCH_URL
},
}
- SEARCH_BACKENDS = {
- 'default': {
- 'BACKEND': 'saleor.search.backends.elasticsearch5',
- 'URLS': [ELASTICSEARCH_URL],
- 'INDEX': os.environ.get('ELASTICSEARCH_INDEX_NAME', 'storefront'),
- 'TIMEOUT': 5,
- 'AUTO_UPDATE': True},
- 'newelastic': {
- 'BACKEND': 'saleor.search.backends.newelastic',
- 'URLS': [ELASTICSEARCH_URL],
- 'INDEX': os.environ.get('ELASTICSEARCH_INDEX_NAME', 'storefront'),
- 'TIMEOUT': 5,
- 'AUTO_UPDATE': False},
- 'dashboard': {
- 'BACKEND': 'saleor.search.backends.dashboard',
- 'URLS': [ELASTICSEARCH_URL],
- 'INDEX': os.environ.get('ELASTICSEARCH_INDEX_NAME', 'storefront'),
- 'TIMEOUT': 5,
- 'AUTO_UPDATE': False},
- 'elasticsearch_dashboard': {
- 'BACKEND': 'saleor.search.backends.elasticsearch_dashboard',
- 'URLS': [ELASTICSEARCH_URL],
- 'INDEX': os.environ.get('ELASTICSEARCH_INDEX_NAME', 'storefront'),
- 'TIMEOUT': 5,
- 'AUTO_UPDATE': False}
- }
-else:
- SEARCH_BACKENDS = {}
+
+SEARCH_BACKENDS = {}
GRAPHENE = {