Skip to content

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

Get rid of old index and backend retrieving

Jakub Draganek662d074c2cd7
diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.py
index 8cf05212d6..53029a406a 100644
--- a/saleor/dashboard/product/forms.py
+++ b/saleor/dashboard/product/forms.py
@@ -11,7 +11,6 @@ from django.utils.translation import pgettext_lazy
from ...product.models import (
AttributeChoiceValue, Product, ProductAttribute, ProductClass,
ProductImage, ProductVariant, Stock, StockLocation, VariantImage)
-from ...search import index as search_index
from .widgets import ImagePreviewWidget
from . import ProductBulkAction
@@ -146,7 +145,6 @@ class ProductForm(forms.ModelForm):
attributes[smart_text(attr.pk)] = value
self.instance.attributes = attributes
instance = super(ProductForm, self).save(commit=commit)
- search_index.insert_or_update_object(instance)
return instance
diff --git a/saleor/dashboard/search/forms.py b/saleor/dashboard/search/forms.py
index 21551dc000..331ce69b82 100644
--- a/saleor/dashboard/search/forms.py
+++ b/saleor/dashboard/search/forms.py
@@ -1,11 +1,10 @@
-from ...search.backends import get_search_backend
from ...search.forms import SearchForm
+from .backends import newelastic
class DashboardSearchForm(SearchForm):
-
def search(self, queryset_map=None):
- backend = get_search_backend('dashboard')
query = self.cleaned_data['q']
- results = backend.search(query, queryset_map=queryset_map)
+ results = newelastic.SearchBackend.search(
+ query, queryset_map=queryset_map)
return results
diff --git a/saleor/order/models.py b/saleor/order/models.py
index f96c608d0b..0f95988fce 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -21,7 +21,6 @@ from . import OrderStatus, emails
from ..core.utils import build_absolute_uri
from ..discount.models import Voucher
from ..product.models import Product
-from ..search import index
from ..userprofile.models import Address
@@ -44,7 +43,7 @@ class OrderManager(models.Manager):
@python_2_unicode_compatible
-class Order(models.Model, ItemSet, index.Indexed):
+class Order(models.Model, ItemSet):
status = models.CharField(
pgettext_lazy('Order field', 'order status'),
max_length=32, choices=OrderStatus.CHOICES, default=OrderStatus.NEW)
@@ -97,12 +96,6 @@ class Order(models.Model, ItemSet, index.Indexed):
objects = OrderManager()
- search_fields = [
- index.SearchField('id'),
- index.SearchField('get_user_current_email'),
- index.SearchField('_index_billing_phone'),
- index.SearchField('_index_shipping_phone')]
-
class Meta:
ordering = ('-last_status_change',)
verbose_name = pgettext_lazy('Order model', 'Order')
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 3942730875..68655d6b72 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -22,7 +22,6 @@ from text_unidecode import unidecode
from versatileimagefield.fields import PPOIField, VersatileImageField
from ..discount.models import calculate_discounted_price
-from ..search import index
from .utils import get_attributes_display_map
@@ -118,7 +117,7 @@ class ProductManager(models.Manager):
@python_2_unicode_compatible
-class Product(models.Model, ItemRange, index.Indexed):
+class Product(models.Model, ItemRange):
product_class = models.ForeignKey(
ProductClass, related_name='products',
verbose_name=pgettext_lazy('Product field', 'product class'),
@@ -146,11 +145,6 @@ class Product(models.Model, ItemRange, index.Indexed):
objects = ProductManager()
- search_fields = [
- index.SearchField('name', partial_match=True),
- index.SearchField('description'),
- index.FilterField('available_on'),
- index.FilterField('is_published')]
class Meta:
app_label = 'product'
diff --git a/saleor/search/forms.py b/saleor/search/forms.py
index 4720a23bc9..670da51773 100644
--- a/saleor/search/forms.py
+++ b/saleor/search/forms.py
@@ -1,9 +1,6 @@
from django import forms
from django.utils.translation import pgettext
-
-from .backends import get_search_backend
-
-USE_BACKEND = 'newelastic'
+from .backends import newelastic
class SearchForm(forms.Form):
@@ -11,7 +8,7 @@ class SearchForm(forms.Form):
label=pgettext('Search form label', 'Query'), required=True)
def search(self, model_or_queryset):
- backend = get_search_backend(USE_BACKEND)
query = self.cleaned_data['q']
- results = backend.search(query, model_or_queryset=model_or_queryset)
+ results = newelastic.SearchBackend.search(
+ query, model_or_queryset=model_or_queryset)
return results
diff --git a/saleor/search/index.py b/saleor/search/index.py
deleted file mode 100644
index a8023dec7b..0000000000
--- a/saleor/search/index.py
+++ /dev/null
@@ -1,277 +0,0 @@
-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/commands/update_index.py b/saleor/search/management/commands/update_index.py
deleted file mode 100644
index 58560f1cfd..0000000000
--- a/saleor/search/management/commands/update_index.py
+++ /dev/null
@@ -1,163 +0,0 @@
-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, 'SEARCH_BACKENDS'):
- # index all backends listed in settings
- backend_names = settings.SEARCH_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/userprofile/models.py b/saleor/userprofile/models.py
index c16c6525e1..e8a9f47b92 100644
--- a/saleor/userprofile/models.py
+++ b/saleor/userprofile/models.py
@@ -8,7 +8,6 @@ from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import pgettext_lazy
from django_countries.fields import Country, CountryField
-from ..search import index
class AddressManager(models.Manager):
@@ -121,7 +120,7 @@ class UserManager(BaseUserManager):
email, password, is_staff=True, is_superuser=True, **extra_fields)
-class User(PermissionsMixin, AbstractBaseUser, index.Indexed):
+class User(PermissionsMixin, AbstractBaseUser):
email = models.EmailField(
pgettext_lazy('User field', 'email'), unique=True)
addresses = models.ManyToManyField(
@@ -149,9 +148,6 @@ class User(PermissionsMixin, AbstractBaseUser, index.Indexed):
objects = UserManager()
- search_fields = [
- index.SearchField('email')]
-
class Meta:
verbose_name = pgettext_lazy('User model', 'user')
verbose_name_plural = pgettext_lazy('User model', 'users')