Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Use fulltext search for products (#9344)
Patryk Zawadzki4b6f25964c13
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f7903ddaa9..fd989d896c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -49,6 +49,7 @@ All notable, unreleased changes to this project will be documented in this file.- Allow plugins to create their custom error code - #9300 by @LeOndaz#### Other+- Use full-text search for products search API - #9344 by @patrys- Include required permission in mutations' descriptions - #9363 by @maarcingebala- Make GraphQL list items non-nullable - #9391 by @maarcingebaladiff --git a/poetry.lock b/poetry.lockindex 094878fe25..8f198ac429 100644--- a/poetry.lock+++ b/poetry.lock@@ -2531,6 +2531,22 @@ virtualenv = ">=16.0.0,<20.0.0 || >20.0.0,<20.0.1 || >20.0.1,<20.0.2 || >20.0.2,docs = ["pygments-github-lexers (>=0.0.5)", "sphinx (>=2.0.0)", "sphinxcontrib-autoprogram (>=0.1.5)", "towncrier (>=18.5.0)"]testing = ["flaky (>=3.4.0)", "freezegun (>=0.3.11)", "pytest (>=4.0.0)", "pytest-cov (>=2.5.1)", "pytest-mock (>=1.10.0)", "pytest-randomly (>=1.0.0)", "psutil (>=5.6.1)", "pathlib2 (>=2.3.3)"]+[[package]]+name = "types-certifi"+version = "2021.10.8.1"+description = "Typing stubs for certifi"+category = "dev"+optional = false+python-versions = "*"++[[package]]+name = "types-freezegun"+version = "1.1.9"+description = "Typing stubs for freezegun"+category = "dev"+optional = false+python-versions = "*"+[[package]]name = "types-pkg-resources"version = "0.1.3"@@ -2566,6 +2582,14 @@ python-versions = "*"[package.dependencies]types-urllib3 = "<1.27"+[[package]]+name = "types-six"+version = "1.16.15"+description = "Typing stubs for six"+category = "dev"+optional = false+python-versions = "*"+[[package]]name = "types-urllib3"version = "1.26.13"@@ -2774,7 +2798,7 @@ test = ["pytest"][metadata]lock-version = "1.1"python-versions = "~3.9"-content-hash = "b364295d4d8e1097a4ba53b0364c8baf2815ac2137a121594222c02dcf9f833f"+content-hash = "274762230a58713e4737812e179a7a6f6fae561f8ccb5a1ca643a8cc1a2cb5de"[metadata.files]adyen = [@@ -4276,6 +4300,14 @@ tox = [{file = "tox-3.25.0-py2.py3-none-any.whl", hash = "sha256:0805727eb4d6b049de304977dfc9ce315a1938e6619c3ab9f38682bb04662a5a"},{file = "tox-3.25.0.tar.gz", hash = "sha256:37888f3092aa4e9f835fc8cc6dadbaaa0782651c41ef359e3a5743fcb0308160"},]+types-certifi = [+ {file = "types-certifi-2021.10.8.1.tar.gz", hash = "sha256:546cd3ca4466855959fbc8868fd7139a50eb55a2d1fae497e13b60af439597a3"},+ {file = "types_certifi-2021.10.8.1-py3-none-any.whl", hash = "sha256:2290008f32e6ac7c69e779d04fa1bc4c6bb4c7200aa3b3b072ad5475a8968aa5"},+]+types-freezegun = [+ {file = "types-freezegun-1.1.9.tar.gz", hash = "sha256:6f05108d468baecadf999873bd37e57b25ceb35d35d3f83e7a742f25d6fe8b0e"},+ {file = "types_freezegun-1.1.9-py3-none-any.whl", hash = "sha256:fe1dd73372d96358dcb93e3aeb66d39f6ac63749e0724f13554cc145e2120efe"},+]types-pkg-resources = [{file = "types-pkg_resources-0.1.3.tar.gz", hash = "sha256:834a9b8d3dbea343562fd99d5d3359a726f6bf9d3733bccd2b4f3096fbab9dae"},{file = "types_pkg_resources-0.1.3-py2.py3-none-any.whl", hash = "sha256:0cb9972cee992249f93fff1a491bf2dc3ce674e5a1926e27d4f0866f7d9b6d9c"},@@ -4292,6 +4324,10 @@ types-requests = [{file = "types-requests-2.27.20.tar.gz", hash = "sha256:63344573cde6c4efd44d867c0158d9fb7e6beb95721cbe9882f3f857ee8a5398"},{file = "types_requests-2.27.20-py3-none-any.whl", hash = "sha256:68b8de86552116424ec23b77afc925e111afb6496d3821b183b7d151b3b834d4"},]+types-six = [+ {file = "types-six-1.16.15.tar.gz", hash = "sha256:d244f0537dab0d0570a5bc6f8a60c4da7f0546d960a8677520e6bff214a64fb8"},+ {file = "types_six-1.16.15-py3-none-any.whl", hash = "sha256:18f6856a7df44fc7a292c2d73093908333e5f7cb858667b8cbefc8ed1e91942e"},+]types-urllib3 = [{file = "types-urllib3-1.26.13.tar.gz", hash = "sha256:40f8fb5e8cd7d57e8aefdee3fdd5e930aa1a1bb4179cdadd55226cea588af790"},{file = "types_urllib3-1.26.13-py3-none-any.whl", hash = "sha256:ff7500641824f881b2c7bde4cc57e6c3abf03d1e005bae83aca752e77213a5da"},diff --git a/pyproject.toml b/pyproject.tomlindex d46ea4678a..7e19e96f70 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -118,6 +118,9 @@ documentation = "https://docs.saleor.io/"django-stubs = "1.8.0"pytest-socket = "^0.5.1"before_after = "^1.0.1"+ types-certifi = "^2021.10.8"+ types-freezegun = "^1.1.7"+ types-six = "^1.16.12"[tool.black]target_version = [ "py35", "py36", "py37", "py38" ]diff --git a/requirements_dev.txt b/requirements_dev.txtindex fee1b915a7..8b5c426980 100644--- a/requirements_dev.txt+++ b/requirements_dev.txt@@ -201,10 +201,13 @@ toml==0.10.2; python_version >= "3.7" and python_full_version < "3.0.0" or pythotomli==2.0.1; python_version < "3.11" and python_full_version >= "3.6.2" and python_version >= "3.7" and (python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.4.0" and python_version >= "3.7")tornado==6.1; python_version >= "3.7"tox==3.25.0; (python_version >= "2.7" and python_full_version < "3.0.0") or (python_full_version >= "3.5.0")+types-certifi==2021.10.8.1+types-freezegun==1.1.9types-pkg-resources==0.1.3types-python-dateutil==2.8.12types-pytz==2021.3.6types-requests==2.27.20+types-six==1.16.15types-urllib3==1.26.13typing-extensions==4.2.0; python_version < "3.10" and python_full_version >= "3.6.2" and python_version >= "3.7"urllib3==1.26.9; python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version < "4" and python_version >= "3.7"diff --git a/saleor/core/management/commands/update_search_indexes.py b/saleor/core/management/commands/update_search_indexes.pyindex c8e813844b..1ee4549f39 100644--- a/saleor/core/management/commands/update_search_indexes.py+++ b/saleor/core/management/commands/update_search_indexes.py@@ -1,8 +1,5 @@from django.core.management.base import BaseCommand-from ....account.models import User-from ....order.models import Order-from ....product.models import Productfrom ...search_tasks import (set_order_search_document_values,set_product_search_document_values,@@ -15,16 +12,13 @@ class Command(BaseCommand):def handle(self, *args, **options):# Update products- products_total_count = Product.objects.filter(search_document="").count()- self.stdout.write(f"Updating products: {products_total_count}")+ self.stdout.write("Updating products")set_product_search_document_values.delay()# Update orders- orders_total_count = Order.objects.filter(search_document="").count()- self.stdout.write(f"Updating orders: {orders_total_count}")+ self.stdout.write("Updating orders")set_order_search_document_values.delay()# Update users- users_total_count = User.objects.filter(search_document="").count()- self.stdout.write(f"Updating users: {users_total_count}")+ self.stdout.write("Updating users")set_user_search_document_values.delay()diff --git a/saleor/core/search_tasks.py b/saleor/core/search_tasks.pyindex 995c0edfd7..f15873015d 100644--- a/saleor/core/search_tasks.py+++ b/saleor/core/search_tasks.py@@ -10,7 +10,7 @@ from ..order.search import prepare_order_search_document_valuefrom ..product.models import Productfrom ..product.search import (PRODUCT_FIELDS_TO_PREFETCH,- prepare_product_search_document_value,+ prepare_product_search_vector_value,)task_logger = get_task_logger(__name__)@@ -82,7 +82,7 @@ def set_order_search_document_values(updated_count: int = 0) -> None:@app.taskdef set_product_search_document_values(updated_count: int = 0) -> None:products = list(- Product.objects.filter(search_document="")+ Product.objects.filter(search_vector=None).prefetch_related(*PRODUCT_FIELDS_TO_PREFETCH)[:BATCH_SIZE].iterator())@@ -91,8 +91,9 @@ def set_product_search_document_values(updated_count: int = 0) -> None:task_logger.info("No products to update.")return- updated_count += set_search_document_values(- products, prepare_product_search_document_value+ updated_count += set_search_vector_values(+ products,+ prepare_product_search_vector_value,)task_logger.info("Updated %d products", updated_count)@@ -117,3 +118,17 @@ def set_search_document_values(instances: List, prepare_search_document_func):Model.objects.bulk_update(instances, ["search_document"])return len(instances)+++def set_search_vector_values(+ instances,+ prepare_search_vector_func,+):+ Model = instances[0]._meta.model+ for instance in instances:+ instance.search_vector = prepare_search_vector_func(+ instance, already_prefetched=True+ )+ Model.objects.bulk_update(instances, ["search_vector"])++ return len(instances)diff --git a/saleor/core/tests/test_postgresql_search.py b/saleor/core/tests/test_postgresql_search.pyindex ed75104176..9c6b3fecc6 100644--- a/saleor/core/tests/test_postgresql_search.py+++ b/saleor/core/tests/test_postgresql_search.py@@ -1,4 +1,6 @@import pytest+from django.contrib.postgres.search import SearchVector+from django.db.models import Valuefrom django.utils.text import slugifyfrom ...account.models import Address@@ -24,6 +26,10 @@ def named_products(category, product_type, channel_USD):product_type=product_type,category=category,search_document=f"{name}{description}",+ search_vector=(+ SearchVector(Value(name), weight="A")+ + SearchVector(Value(description), weight="C")+ ),)ProductChannelListing.objects.create(product=product,diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex 81586c0770..b1270e7b52 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -80,7 +80,7 @@ from ...product.models import (ProductVariantChannelListing,VariantMedia,)-from ...product.search import update_products_search_document+from ...product.search import update_products_search_vectorfrom ...product.tasks import update_products_discounted_prices_of_discount_taskfrom ...product.thumbnails import (create_category_background_image_thumbnails,@@ -472,7 +472,7 @@ def create_products_by_schema(placeholder_dir, create_images):assign_products_to_collections(associations=types["product.collectionproduct"])all_products_qs = Product.objects.all()- update_products_search_document(all_products_qs)+ update_products_search_vector(all_products_qs)update_products_discounted_prices(all_products_qs)diff --git a/saleor/graphql/attribute/bulk_mutations.py b/saleor/graphql/attribute/bulk_mutations.pyindex d92ad06648..3b6bb117d0 100644--- a/saleor/graphql/attribute/bulk_mutations.py+++ b/saleor/graphql/attribute/bulk_mutations.py@@ -4,7 +4,7 @@ from django.db.models import Exists, OuterRef, Qfrom ...attribute import modelsfrom ...core.permissions import PageTypePermissionsfrom ...product import models as product_models-from ...product.search import update_products_search_document+from ...product.search import update_products_search_vectorfrom ..core.mutations import ModelBulkDeleteMutationfrom ..core.types import AttributeError, NonNullListfrom ..utils import resolve_global_ids_to_primary_keys@@ -32,7 +32,7 @@ class AttributeBulkDelete(ModelBulkDeleteMutation):_, attribute_pks = resolve_global_ids_to_primary_keys(ids, "Attribute")product_ids = cls.get_product_ids_to_update(attribute_pks)response = super().perform_mutation(_root, info, ids, **data)- update_products_search_document(+ update_products_search_vector(product_models.Product.objects.filter(id__in=product_ids))return response@@ -86,7 +86,7 @@ class AttributeValueBulkDelete(ModelBulkDeleteMutation):_, attribute_pks = resolve_global_ids_to_primary_keys(ids, "AttributeValue")product_ids = cls.get_product_ids_to_update(attribute_pks)response = super().perform_mutation(_root, info, ids, **data)- update_products_search_document(+ update_products_search_vector(product_models.Product.objects.filter(id__in=product_ids))return responsediff --git a/saleor/graphql/attribute/mutations.py b/saleor/graphql/attribute/mutations.pyindex 12ca5b99a7..250a7951ce 100644--- a/saleor/graphql/attribute/mutations.py+++ b/saleor/graphql/attribute/mutations.py@@ -17,7 +17,7 @@ from ...core.permissions import (from ...core.tracing import traced_atomic_transactionfrom ...core.utils import generate_unique_slugfrom ...product import models as product_models-from ...product.search import update_products_search_document+from ...product.search import update_products_search_vectorfrom ..core.enums import MeasurementUnitsEnumfrom ..core.fields import JSONStringfrom ..core.inputs import ReorderInput@@ -734,7 +734,7 @@ class AttributeValueUpdate(AttributeValueCreate):Q(Exists(instance.productassignments.filter(product_id=OuterRef("id"))))| Q(Exists(variants.filter(product_id=OuterRef("id")))))- update_products_search_document(products)+ update_products_search_vector(products)class AttributeValueDelete(ModelDeleteMutation):@@ -757,7 +757,7 @@ class AttributeValueDelete(ModelDeleteMutation):instance = cls.get_node_or_error(info, node_id, only_type=AttributeValue)product_ids = cls.get_product_ids_to_update(instance)response = super().perform_mutation(_root, info, **data)- update_products_search_document(+ update_products_search_vector(product_models.Product.objects.filter(id__in=product_ids))return responsediff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py b/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.pyindex be65312399..8451e47964 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py@@ -87,10 +87,6 @@ def test_delete_attribute_value_product_search_document_updated(with pytest.raises(value._meta.model.DoesNotExist):value.refresh_from_db()- product.refresh_from_db()- assert product.search_document- assert name.lower() not in product.search_document-def test_delete_attribute_value_product_search_document_updated_variant_attribute(staff_api_client,@@ -121,7 +117,3 @@ def test_delete_attribute_value_product_search_document_updated_variant_attribut# thenwith pytest.raises(value._meta.model.DoesNotExist):value.refresh_from_db()-- product.refresh_from_db()- assert product.search_document- assert name.lower() not in product.search_documentdiff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.pyindex f0d4898699..e1d6594e33 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py@@ -127,9 +127,6 @@ def test_update_attribute_value_product_search_document_updated(value["node"]["name"] for value in data["attribute"]["choices"]["edges"]]- product.refresh_from_db()- assert name.lower() in product.search_document-def test_update_attribute_value_product_search_document_updated_variant_attribute(staff_api_client,@@ -167,9 +164,6 @@ def test_update_attribute_value_product_search_document_updated_variant_attributvalue["node"]["name"] for value in data["attribute"]["choices"]["edges"]]- product.refresh_from_db()- assert name.lower() in product.search_document-def test_update_swatch_attribute_value(staff_api_client,diff --git a/saleor/graphql/attribute/tests/mutations/test_bulk_delete.py b/saleor/graphql/attribute/tests/mutations/test_bulk_delete.pyindex 689ec86155..322919d1bb 100644--- a/saleor/graphql/attribute/tests/mutations/test_bulk_delete.py+++ b/saleor/graphql/attribute/tests/mutations/test_bulk_delete.py@@ -104,16 +104,6 @@ def test_delete_attributes_products_search_document_updated(id__in=[attr.id for attr in product_type_attribute_list]).exists()- product_1.refresh_from_db()- product_2.refresh_from_db()- assert product_1.search_document- assert attr_1_name not in product_1.search_document- assert color_attribute_value.name.lower() in product_1.search_document- assert attr_3_name not in product_1.search_document-- assert product_2.search_document- assert attr_2_name not in product_2.search_document-ATTRIBUTE_VALUE_BULK_DELETE_MUTATION = """mutation attributeValueBulkDelete($ids: [ID!]!) {@@ -160,11 +150,6 @@ def test_delete_attribute_values_search_document_updated(slug="orange", name="Orange", attribute=attribute, value="#ABCD")- val_1_name = value_1.name- val_2_name = value_2.name- val_3_name = value_3.name- val_4_name = value_4.name-product_1 = product_list[0]product_2 = product_list[1]variant_1 = product_1.variants.first()@@ -195,10 +180,5 @@ def test_delete_attribute_values_search_document_updated(product_1.refresh_from_db()product_2.refresh_from_db()- assert product_1.search_document- assert val_1_name not in product_1.search_document- assert val_4_name.lower() in product_1.search_document- assert val_3_name not in product_1.search_document-- assert product_2.search_document- assert val_2_name not in product_2.search_document+ assert product_1.search_vector+ assert product_2.search_vectordiff --git a/saleor/graphql/core/connection.py b/saleor/graphql/core/connection.pyindex cda2ef5087..747bc6f1a7 100644--- a/saleor/graphql/core/connection.py+++ b/saleor/graphql/core/connection.py@@ -1,5 +1,5 @@import json-from decimal import Decimal+from decimal import Decimal, InvalidOperationfrom typing import Any, Dict, Iterable, List, Optional, Tuple, Union, castimport graphene@@ -51,6 +51,28 @@ def get_field_value(instance: DjangoModel, field_name: str):return attr+def _prepare_filter_by_rank_expression(+ cursor: List[str],+ sorting_direction: str,+) -> Q:+ try:+ rank = Decimal(cursor[0])+ int(cursor[1])+ except (InvalidOperation, ValueError, TypeError, KeyError):+ raise ValueError("Invalid cursor for sorting by rank.")++ # Because rank is float number, it gets mangled by PostgreSQL's query parser+ # making equal comparisons impossible. Instead we compare rank against small+ # range of values, constructed using epsilon.+ if sorting_direction == "gt":+ return Q(+ search_rank__range=(rank - EPSILON, rank + EPSILON), id__lt=cursor[1]+ ) | Q(search_rank__gt=rank + EPSILON)+ return Q(search_rank__range=(rank - EPSILON, rank + EPSILON), id__gt=cursor[1]) | Q(+ search_rank__lt=rank - EPSILON+ )++def _prepare_filter_expression(field_name: str,index: int,@@ -92,6 +114,9 @@ def _prepare_filter(('first_field', 'first_value_form_cursor')))"""+ if sorting_fields == ["search_rank", "id"]:+ # Fast path for filtering by rank+ return _prepare_filter_by_rank_expression(cursor, sorting_direction)filter_kwargs = Q()for index, field_name in enumerate(sorting_fields):if cursor[index] is None and sorting_direction == "gt":diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.pyindex cd1cb5681a..6b9a810d36 100644--- a/saleor/graphql/product/bulk_mutations/products.py+++ b/saleor/graphql/product/bulk_mutations/products.py@@ -19,8 +19,8 @@ from ....order.tasks import recalculate_orders_taskfrom ....product import modelsfrom ....product.error_codes import ProductErrorCodefrom ....product.search import (- prepare_product_search_document_value,- update_product_search_document,+ prepare_product_search_vector_value,+ update_product_search_vector,)from ....product.tasks import update_product_discounted_price_taskfrom ....product.utils import delete_categories@@ -556,7 +556,7 @@ class ProductVariantBulkCreate(BaseMutation):ChannelContext(node=instance, channel_slug=None) for instance in instances]- update_product_search_document(product)+ update_product_search_vector(product)transaction.on_commit(lambda: [@@ -643,10 +643,14 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):pk__in=product_pks, default_variant__isnull=True)for product in products:- product.search_document = prepare_product_search_document_value(product)+ product.search_vector = prepare_product_search_vector_value(product)product.default_variant = product.variants.first()product.save(- update_fields=["default_variant", "search_document", "updated_at"]+ update_fields=[+ "default_variant",+ "search_vector",+ "updated_at",+ ])return responsediff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.pyindex 1cff122a0e..67e7ddc1b2 100644--- a/saleor/graphql/product/mutations/attributes.py+++ b/saleor/graphql/product/mutations/attributes.py@@ -11,7 +11,7 @@ from ....core.permissions import ProductPermissions, ProductTypePermissionsfrom ....core.tracing import traced_atomic_transactionfrom ....product import modelsfrom ....product.error_codes import ProductErrorCode-from ....product.search import update_products_search_document+from ....product.search import update_products_search_vectorfrom ...attribute.mutations import (BaseReorderAttributesMutation,BaseReorderAttributeValuesMutation,@@ -344,7 +344,7 @@ class ProductAttributeUnassign(BaseMutation):cls.save_field_values(product_type, "product_attributes", attribute_pks)cls.save_field_values(product_type, "variant_attributes", attribute_pks)- update_products_search_document(product_type.products.all())+ update_products_search_vector(product_type.products.all())return cls(product_type=product_type)diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex a33da85b02..2d775c3ae3 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -25,8 +25,8 @@ from ....order.tasks import recalculate_orders_taskfrom ....product import ProductMediaTypes, ProductTypeKind, modelsfrom ....product.error_codes import CollectionErrorCode, ProductErrorCodefrom ....product.search import (- update_product_search_document,- update_products_search_document,+ update_product_search_vector,+ update_products_search_vector,)from ....product.tasks import (update_product_discounted_price_task,@@ -676,7 +676,7 @@ class ProductCreate(ModelMutation):@classmethoddef post_save_action(cls, info, instance, _cleaned_input):product = models.Product.objects.prefetched_for_webhook().get(pk=instance.pk)- update_product_search_document(instance)+ update_product_search_vector(instance)info.context.plugins.product_created(product)@classmethod@@ -729,7 +729,7 @@ class ProductUpdate(ProductCreate):@classmethoddef post_save_action(cls, info, instance, _cleaned_input):product = models.Product.objects.prefetched_for_webhook().get(pk=instance.pk)- update_product_search_document(instance)+ update_product_search_vector(instance)info.context.plugins.product_updated(product)@@ -1057,7 +1057,7 @@ class ProductVariantCreate(ModelMutation):AttributeAssignmentMixin.save(instance, attributes)generate_and_set_variant_name(instance, cleaned_input.get("sku"))- update_product_search_document(instance.product)+ update_product_search_vector(instance.product)event_to_call = (info.context.plugins.product_variant_createdif new_variant@@ -1153,7 +1153,7 @@ class ProductVariantDelete(ModelDeleteMutation):# Update the "discounted_prices" of the parent productupdate_product_discounted_price_task.delay(instance.product_id)product = models.Product.objects.get(id=instance.product_id)- update_product_search_document(product)+ update_product_search_vector(product)# if the product default variant has been removed set the new oneif not product.default_variant:product.default_variant = product.variants.first()@@ -1394,7 +1394,7 @@ class ProductTypeUpdate(ProductTypeCreate):or "variant_attributes" in cleaned_input):products = models.Product.objects.filter(product_type=instance)- update_products_search_document(products)+ update_products_search_vector(products)class ProductTypeDelete(ModelDeleteMutation):diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.pyindex edcc8fa2d5..8d67e7e0ed 100644--- a/saleor/graphql/product/schema.py+++ b/saleor/graphql/product/schema.py@@ -1,8 +1,10 @@-import graphene+from typing import List, Optional-from saleor.core.tracing import traced_resolver+import graphene+from graphql import GraphQLErrorfrom ...core.permissions import ProductPermissions, has_one_of_permissions+from ...core.tracing import traced_resolverfrom ...product.models import ALL_PRODUCTS_PERMISSIONSfrom ..channel import ChannelContextfrom ..channel.utils import get_default_channel_slug_or_graphql_error@@ -110,6 +112,7 @@ from .sorters import (CategorySortingInput,CollectionSortingInput,ProductOrder,+ ProductOrderField,ProductTypeSortingInput,ProductVariantSortingInput,)@@ -129,6 +132,14 @@ from .types import ()+def search_string_in_kwargs(kwargs: dict) -> bool:+ return bool(kwargs.get("filter", {}).get("search", "").strip())+++def sort_field_from_kwargs(kwargs: dict) -> Optional[List[str]]:+ return kwargs.get("sort_by", {}).get("field") or None++class ProductQueries(graphene.ObjectType):digital_content = graphene.Field(DigitalContent,@@ -253,13 +264,17 @@ class ProductQueries(graphene.ObjectType):description="List of top selling products.",)- def resolve_categories(self, info, level=None, **kwargs):+ @staticmethod+ def resolve_categories(_root, info: graphene.ResolveInfo, level=None, **kwargs):qs = resolve_categories(info, level=level, **kwargs)qs = filter_connection_queryset(qs, kwargs)return create_connection_slice(qs, info, kwargs, CategoryCountableConnection)+ @staticmethod@traced_resolver- def resolve_category(self, info, id=None, slug=None, **kwargs):+ def resolve_category(+ _root, _info: graphene.ResolveInfo, id=None, slug=None, **kwargs+ ):validate_one_of_args_is_in_query("id", id, "slug", slug)if id:_, id = from_global_id_or_error(id, Category)@@ -267,8 +282,11 @@ class ProductQueries(graphene.ObjectType):if slug:return resolve_category_by_slug(slug=slug)+ @staticmethod@traced_resolver- def resolve_collection(self, info, id=None, slug=None, channel=None, **_kwargs):+ def resolve_collection(+ _root, info: graphene.ResolveInfo, id=None, slug=None, channel=None+ ):validate_one_of_args_is_in_query("id", id, "slug", slug)requestor = get_user_or_app_from_context(info.context)@@ -290,7 +308,8 @@ class ProductQueries(graphene.ObjectType):else None)- def resolve_collections(self, info, channel=None, *_args, **kwargs):+ @staticmethod+ def resolve_collections(_root, info: graphene.ResolveInfo, channel=None, **kwargs):requestor = get_user_or_app_from_context(info.context)has_required_permissions = has_one_of_permissions(requestor, ALL_PRODUCTS_PERMISSIONS@@ -302,20 +321,25 @@ class ProductQueries(graphene.ObjectType):qs = filter_connection_queryset(qs, kwargs)return create_connection_slice(qs, info, kwargs, CollectionCountableConnection)+ @staticmethod@permission_required(ProductPermissions.MANAGE_PRODUCTS)- def resolve_digital_content(self, info, id):+ def resolve_digital_content(_root, _info: graphene.ResolveInfo, id):_, id = from_global_id_or_error(id, DigitalContent)return resolve_digital_content_by_id(id)+ @staticmethod@permission_required(ProductPermissions.MANAGE_PRODUCTS)- def resolve_digital_contents(self, info, **kwargs):+ def resolve_digital_contents(_root, info: graphene.ResolveInfo, **kwargs):qs = resolve_digital_contents(info)return create_connection_slice(qs, info, kwargs, DigitalContentCountableConnection)+ @staticmethod@traced_resolver- def resolve_product(self, info, id=None, slug=None, channel=None, **_kwargs):+ def resolve_product(+ _root, info: graphene.ResolveInfo, id=None, slug=None, channel=None+ ):validate_one_of_args_is_in_query("id", id, "slug", slug)requestor = get_user_or_app_from_context(info.context)@@ -336,8 +360,23 @@ class ProductQueries(graphene.ObjectType):)return ChannelContext(node=product, channel_slug=channel) if product else None+ @staticmethod@traced_resolver- def resolve_products(self, info, channel=None, **kwargs):+ def resolve_products(_root, info: graphene.ResolveInfo, channel=None, **kwargs):+ if sort_field_from_kwargs(kwargs) == ProductOrderField.RANK:+ # sort by RANK can be used only with search filter+ if not search_string_in_kwargs(kwargs):+ raise GraphQLError(+ "Sorting by RANK is available only when using a search filter."+ )+ if search_string_in_kwargs(kwargs) and not sort_field_from_kwargs(kwargs):+ # default to sorting by RANK if search is used+ # and no explicit sorting is requested+ product_type = info.schema.get_type("ProductOrder")+ kwargs["sort_by"] = product_type.create_container(+ {"direction": "-", "field": ["search_rank", "id"]}+ )+requestor = get_user_or_app_from_context(info.context)has_required_permissions = has_one_of_permissions(requestor, ALL_PRODUCTS_PERMISSIONS@@ -349,19 +388,22 @@ class ProductQueries(graphene.ObjectType):qs = filter_connection_queryset(qs, kwargs)return create_connection_slice(qs, info, kwargs, ProductCountableConnection)- def resolve_product_type(self, info, id, **_kwargs):+ @staticmethod+ def resolve_product_type(_root, _info: graphene.ResolveInfo, id):_, id = from_global_id_or_error(id, ProductType)return resolve_product_type_by_id(id)- def resolve_product_types(self, info, **kwargs):+ @staticmethod+ def resolve_product_types(_root, info: graphene.ResolveInfo, **kwargs):qs = resolve_product_types(info, **kwargs)qs = filter_connection_queryset(qs, kwargs)return create_connection_slice(qs, info, kwargs, ProductTypeCountableConnection)+ @staticmethod@traced_resolverdef resolve_product_variant(- self,- info,+ _root,+ info: graphene.ResolveInfo,id=None,sku=None,channel=None,@@ -393,7 +435,10 @@ class ProductQueries(graphene.ObjectType):)return ChannelContext(node=variant, channel_slug=channel) if variant else None- def resolve_product_variants(self, info, ids=None, channel=None, **kwargs):+ @staticmethod+ def resolve_product_variants(+ _root, info: graphene.ResolveInfo, ids=None, channel=None, **kwargs+ ):requestor = get_user_or_app_from_context(info.context)has_required_permissions = has_one_of_permissions(requestor, ALL_PRODUCTS_PERMISSIONS@@ -413,9 +458,12 @@ class ProductQueries(graphene.ObjectType):qs, info, kwargs, ProductVariantCountableConnection)+ @staticmethod@permission_required(ProductPermissions.MANAGE_PRODUCTS)@traced_resolver- def resolve_report_product_sales(self, info, *_args, period, channel, **kwargs):+ def resolve_report_product_sales(+ _root, info: graphene.ResolveInfo, period, channel, **kwargs+ ):qs = resolve_report_product_sales(period, channel_slug=channel)kwargs["channel"] = qs.channel_slugreturn create_connection_slice(diff --git a/saleor/graphql/product/sorters.py b/saleor/graphql/product/sorters.pyindex 38386d1f2a..2631e2d6a0 100644--- a/saleor/graphql/product/sorters.py+++ b/saleor/graphql/product/sorters.py@@ -123,7 +123,7 @@ class CollectionSortingInput(ChannelSortInputObjectType):class ProductOrderField(graphene.Enum):NAME = ["name", "slug"]- RANK = ["name", "slug"]+ RANK = ["search_rank", "id"]PRICE = ["min_variants_price_amount", "name", "slug"]MINIMAL_PRICE = ["discounted_price_amount", "name", "slug"]LAST_MODIFIED = ["updated_at", "name", "slug"]@@ -144,7 +144,9 @@ class ProductOrderField(graphene.Enum):"collection. Note: ""This option is available only for the `Collection.products` query."),- ProductOrderField.RANK.name: (f"rank. {DEPRECATED_IN_3X_INPUT}"),+ ProductOrderField.RANK.name: (+ "rank. Note: This option is available only with the `search` filter."+ ),ProductOrderField.NAME.name: "name.",ProductOrderField.PRICE.name: "price.",ProductOrderField.TYPE.name: "type.",diff --git a/saleor/graphql/product/tests/test_attributes.py b/saleor/graphql/product/tests/test_attributes.pyindex 851736dada..2d4affbe0f 100644--- a/saleor/graphql/product/tests/test_attributes.py+++ b/saleor/graphql/product/tests/test_attributes.py@@ -1087,10 +1087,6 @@ def test_unassign_attributes_from_product_type(== remaining_attribute_global_id)- product.refresh_from_db()- assert product.search_document- assert product_attr_value.name not in product.search_document-def test_unassign_attributes_not_in_product_type(staff_api_client,diff --git a/saleor/graphql/product/tests/test_bulk_delete.py b/saleor/graphql/product/tests/test_bulk_delete.pyindex a12dc32217..d1e7054bd6 100644--- a/saleor/graphql/product/tests/test_bulk_delete.py+++ b/saleor/graphql/product/tests/test_bulk_delete.py@@ -894,7 +894,6 @@ def test_delete_product_variants(assert ProductVariantChannelListing.objects.filter(variant_id__in=[variant.id for variant in product_variant_list]).exists()- variants_sku = [variant.sku for variant in product_variant_list]variables = {"ids": [@@ -917,10 +916,6 @@ def test_delete_product_variants(== content["data"]["productVariantBulkDelete"]["count"])mocked_recalculate_orders_task.assert_not_called()- product.refresh_from_db()- assert product.search_document- for sku in variants_sku:- assert sku not in product.search_documentdef test_delete_product_variants_invalid_object_typed_of_given_ids(diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.pyindex 8b823bd914..d25eac2b02 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -27,7 +27,6 @@ from ....attribute.models import Attribute, AttributeValuefrom ....attribute.utils import associate_attribute_values_to_instancefrom ....core.taxes import TaxTypefrom ....core.units import MeasurementUnits, WeightUnits-from ....core.utils.editorjs import clean_editor_jsfrom ....order import OrderEvents, OrderStatusfrom ....order.models import OrderEvent, OrderLinefrom ....plugins.manager import PluginsManager, get_plugins_manager@@ -44,7 +43,7 @@ from ....product.models import (ProductVariant,ProductVariantChannelListing,)-from ....product.search import prepare_product_search_document_value+from ....product.search import prepare_product_search_vector_valuefrom ....product.tasks import update_variants_namesfrom ....product.tests.utils import create_image, create_pdf_file_with_image_extfrom ....product.utils.availability import get_variant_availability@@ -2686,8 +2685,8 @@ def test_products_query_with_filter_category_and_search(product.save()for pr in [product, second_product]:- pr.search_document = prepare_product_search_document_value(pr)- Product.objects.bulk_update([product, second_product], ["search_document"])+ pr.search_vector = prepare_product_search_vector_value(pr)+ Product.objects.bulk_update([product, second_product], ["search_vector"])category_id = graphene.Node.to_global_id("Category", category.id)variables = {"filter": {"categories": [category_id], "search": product.name}}@@ -2818,10 +2817,8 @@ def test_products_query_with_filter(channel=channel_USD,is_published=False,)- second_product.search_document = prepare_product_search_document_value(- second_product- )- second_product.save(update_fields=["search_document"])+ second_product.search_vector = prepare_product_search_vector_value(second_product)+ second_product.save(update_fields=["search_vector"])variables = {"filter": products_filter, "channel": channel_USD.slug}staff_api_client.user.user_permissions.add(permission_manage_products)response = staff_api_client.post_graphql(query_products_with_filter, variables)@@ -2931,10 +2928,10 @@ def test_products_query_with_filter_search_by_dropdown_attribute_value(product_with_dropdown_attr.refresh_from_db()- product_with_dropdown_attr.search_document = prepare_product_search_document_value(+ product_with_dropdown_attr.search_vector = prepare_product_search_vector_value(product_with_dropdown_attr)- product_with_dropdown_attr.save(update_fields=["search_document"])+ product_with_dropdown_attr.save(update_fields=["search_document", "search_vector"])variables = {"filter": {"search": search_value}, "channel": channel_USD.slug}@@ -2954,7 +2951,7 @@ def test_products_query_with_filter_search_by_dropdown_attribute_value(@pytest.mark.parametrize(- "search_value", ["eco mode", "ECO Performance", "performa", "mod"]+ "search_value", ["eco mode", "ECO Performance", "performant*", "modes"])def test_products_query_with_filter_search_by_multiselect_attribute_value(search_value,@@ -2993,10 +2990,10 @@ def test_products_query_with_filter_search_by_multiselect_attribute_value(product_with_multiselect_attr.refresh_from_db()- product_with_multiselect_attr.search_document = (- prepare_product_search_document_value(product_with_multiselect_attr)+ product_with_multiselect_attr.search_vector = prepare_product_search_vector_value(+ product_with_multiselect_attr)- product_with_multiselect_attr.save(update_fields=["search_document"])+ product_with_multiselect_attr.save(update_fields=["search_vector"])variables = {"filter": {"search": search_value}, "channel": channel_USD.slug}@@ -3041,10 +3038,10 @@ def test_products_query_with_filter_search_by_rich_text_attribute(product_with_rich_text_attr.refresh_from_db()- product_with_rich_text_attr.search_document = prepare_product_search_document_value(+ product_with_rich_text_attr.search_vector = prepare_product_search_vector_value(product_with_rich_text_attr)- product_with_rich_text_attr.save(update_fields=["search_document"])+ product_with_rich_text_attr.save(update_fields=["search_vector"])variables = {"filter": {"search": search_value}, "channel": channel_USD.slug}@@ -3092,10 +3089,10 @@ def test_products_query_with_filter_search_by_numeric_attribute_value(product_with_numeric_attr.refresh_from_db()- product_with_numeric_attr.search_document = prepare_product_search_document_value(+ product_with_numeric_attr.search_vector = prepare_product_search_vector_value(product_with_numeric_attr)- product_with_numeric_attr.save(update_fields=["search_document"])+ product_with_numeric_attr.save(update_fields=["search_vector"])variables = {"filter": {"search": search_value}, "channel": channel_USD.slug}@@ -3139,10 +3136,10 @@ def test_products_query_with_filter_search_by_numeric_attribute_value_without_unproduct_with_numeric_attr.refresh_from_db()- product_with_numeric_attr.search_document = prepare_product_search_document_value(+ product_with_numeric_attr.search_vector = prepare_product_search_vector_value(product_with_numeric_attr)- product_with_numeric_attr.save(update_fields=["search_document"])+ product_with_numeric_attr.save(update_fields=["search_vector"])variables = {"filter": {"search": "13456"}, "channel": channel_USD.slug}@@ -3161,7 +3158,7 @@ def test_products_query_with_filter_search_by_numeric_attribute_value_without_unassert products[0]["node"]["name"] == product_with_numeric_attr.name[email protected]("search_value", ["2020", "2020 10 10", "2020-10-10"])[email protected]("search_value", ["2020", "2020-10-10"])def test_products_query_with_filter_search_by_date_attribute_value(search_value,query_products_with_filter,@@ -3187,10 +3184,10 @@ def test_products_query_with_filter_search_by_date_attribute_value(product_with_date_attr.refresh_from_db()- product_with_date_attr.search_document = prepare_product_search_document_value(+ product_with_date_attr.search_vector = prepare_product_search_vector_value(product_with_date_attr)- product_with_date_attr.save(update_fields=["search_document"])+ product_with_date_attr.save(update_fields=["search_vector"])variables = {"filter": {"search": search_value}, "channel": channel_USD.slug}@@ -3209,7 +3206,7 @@ def test_products_query_with_filter_search_by_date_attribute_value(assert products[0]["node"]["name"] == product_with_date_attr.name[email protected]("search_value", ["2020", "2020 10 10", "2020-10-10", "22:20"])[email protected]("search_value", ["2020", "2020-10-10", "22:20"])def test_products_query_with_filter_search_by_date_time_attribute_value(search_value,query_products_with_filter,@@ -3235,10 +3232,10 @@ def test_products_query_with_filter_search_by_date_time_attribute_value(product_with_date_time_attr.refresh_from_db()- product_with_date_time_attr.search_document = prepare_product_search_document_value(+ product_with_date_time_attr.search_vector = prepare_product_search_vector_value(product_with_date_time_attr)- product_with_date_time_attr.save(update_fields=["search_document"])+ product_with_date_time_attr.save(update_fields=["search_vector"])variables = {"filter": {"search": search_value}, "channel": channel_USD.slug}@@ -4361,10 +4358,6 @@ def test_create_product(product = Product.objects.first()created_webhook_mock.assert_called_once_with(product)- assert product.search_document- assert product_name.lower() in product.search_document- assert color_value_slug.lower() in product.search_document- assert non_existent_attr_value.lower() in product.search_documentupdated_webhook_mock.assert_not_called()@@ -4415,7 +4408,6 @@ def test_create_product_description_plaintext(product = Product.objects.all().first()assert product.description_plaintext == description- assert description in product.search_documentdef test_create_product_with_rich_text_attribute(@@ -4492,13 +4484,6 @@ def test_create_product_with_rich_text_attribute(for attr_data in data["product"]["attributes"]:assert attr_data in expected_attributes_data- product = Product.objects.first()- assert product.search_document- assert product_name.lower() in product.search_document- assert (- clean_editor_js(rich_text_value, to_string=True).lower()- in product.search_document- )def test_create_product_no_value_for_rich_text_attribute(@@ -4609,10 +4594,6 @@ def test_create_product_with_date_time_attribute(}assert expected_attributes_data in data["product"]["attributes"]- product = Product.objects.first()- assert product.search_document- assert product_name.lower() in product.search_document- assert str(value.isoformat()).lower() in product.search_document@freeze_time(datetime(2020, 5, 5, 5, 5, 5, tzinfo=pytz.utc))@@ -4674,10 +4655,6 @@ def test_create_product_with_date_attribute(}assert expected_attributes_data in data["product"]["attributes"]- product = Product.objects.first()- assert product.search_document- assert product_name.lower() in product.search_document- assert str(value).lower() in product.search_documentdef test_create_product_no_value_for_date_attribute(@@ -4883,10 +4860,11 @@ def test_search_product_by_description_and_name(product_list.append(product)for prod in product_list:- prod.search_document = prepare_product_search_document_value(prod)+ prod.search_vector = prepare_product_search_vector_value(prod)Product.objects.bulk_update(- product_list, ["search_document", "name", "description_plaintext"]+ product_list,+ ["search_document", "search_vector", "name", "description_plaintext"],)variables = {@@ -4908,22 +4886,23 @@ def test_search_product_by_description_and_name(def test_sort_product_by_rank_without_search(- user_api_client, product_list, product, channel_USD, category, product_type+ user_api_client, product_list, channel_USD):- product_count = Product.objects.count()-variables = {"sortBy": {"field": "RANK", "direction": "DESC"},"channel": channel_USD.slug,}response = user_api_client.post_graphql(SEARCH_PRODUCTS_QUERY, variables)- content = get_graphql_content(response)- data = content["data"]["products"]["edges"]- assert len(data) == product_count+ content = get_graphql_content(response, ignore_errors=True)+ assert "errors" in content+ assert (+ content["errors"][0]["message"]+ == "Sorting by RANK is available only when using a search filter."+ )def test_search_product_by_description_and_name_without_sort_by(- user_api_client, product_list, product, channel_USD, category, product_type+ user_api_client, product_list, product, channel_USD):product.description_plaintext = "new big new product"@@ -4934,10 +4913,11 @@ def test_search_product_by_description_and_name_without_sort_by(product_list.append(product)for prod in product_list:- prod.search_document = prepare_product_search_document_value(prod)+ prod.search_vector = prepare_product_search_vector_value(prod)Product.objects.bulk_update(- product_list, ["search_document", "name", "description_plaintext"]+ product_list,+ ["search_vector", "name", "description_plaintext"],)variables = {@@ -4970,10 +4950,11 @@ def test_search_product_by_description_and_name_and_use_cursor(product_list.append(product)for prod in product_list:- prod.search_document = prepare_product_search_document_value(prod)+ prod.search_vector = prepare_product_search_vector_value(prod)Product.objects.bulk_update(- product_list, ["search_document", "name", "description_plaintext"]+ product_list,+ ["search_vector", "name", "description_plaintext"],)variables = {@@ -4998,7 +4979,6 @@ def test_search_product_by_description_and_name_and_use_cursor(data = content["data"]["products"]["edges"]assert len(data) == 2- assert {node["node"]["name"] for node in data} == {product_1.name, product_2.name}@freeze_time("2020-03-18 12:00:00")@@ -6709,10 +6689,6 @@ def test_update_product(updated_webhook_mock.assert_called_once_with(product)created_webhook_mock.assert_not_called()- product.refresh_from_db()- assert product.search_document- assert attr_value.lower() in product.search_document- assert product_name.lower() in product.search_documentdef test_update_and_search_product_by_description(@@ -7024,10 +7000,6 @@ def test_update_product_with_numeric_attribute_value(updated_webhook_mock.assert_called_once_with(product)- product.refresh_from_db()- assert product.search_document- assert f"{new_value}{numeric_attribute.unit}" in product.search_document-@patch("saleor.plugins.manager.PluginsManager.product_updated")def test_update_product_with_numeric_attribute_value_new_value_is_not_created(@@ -9525,9 +9497,6 @@ def test_product_type_update_mutation(require_shipping = Falseproduct_type_id = graphene.Node.to_global_id("ProductType", product_type.id)- product_attr = product.attributes.first()- value = product_attr.values.first()-# Test scenario: remove all product attributes using [] as input# but do not change variant attributesproduct_attributes = []@@ -9555,10 +9524,6 @@ def test_product_type_update_mutation(assert not data["productAttributes"]assert len(data["variantAttributes"]) == (variant_attributes.count())- product.refresh_from_db()- assert product.search_document- assert value.name not in product.search_document-def test_product_type_update_mutation_not_valid_attributes(staff_api_client,@@ -9637,9 +9602,9 @@ UPDATE_PRODUCT_TYPE_SLUG_MUTATION = """(None, "", "Slug value cannot be blank."),],)-@patch("saleor.product.search.update_products_search_document")+@patch("saleor.product.search.update_products_search_vector")def test_update_product_type_slug(- update_products_search_document_mock,+ update_products_search_vector_mock,staff_api_client,product_type,permission_manage_product_types_and_attributes,@@ -9663,7 +9628,7 @@ def test_update_product_type_slug(if not error_message:assert not errorsassert data["productType"]["slug"] == expected_slug- update_products_search_document_mock.assert_not_called()+ update_products_search_vector_mock.assert_not_called()else:assert errorsassert errors[0]["field"] == "slug"diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.pyindex ac9f9b90a3..86d9140eda 100644--- a/saleor/graphql/product/tests/test_variant.py+++ b/saleor/graphql/product/tests/test_variant.py@@ -605,10 +605,6 @@ def test_create_variant(created_webhook_mock.assert_called_once_with(product.variants.last())updated_webhook_mock.assert_not_called()- product.refresh_from_db()- assert product.search_document- assert sku in product.search_document-@patch("saleor.plugins.manager.PluginsManager.product_variant_created")@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")@@ -715,10 +711,6 @@ def test_create_variant_no_required_attributes(created_webhook_mock.assert_called_once_with(product.variants.last())updated_webhook_mock.assert_not_called()- product.refresh_from_db()- assert product.search_document- assert sku in product.search_document-@patch("saleor.plugins.manager.PluginsManager.product_variant_created")def test_create_variant_with_file_attribute(@@ -1970,10 +1962,6 @@ def test_product_variant_update_with_new_attributes(assert len(attributes) == 1assert attributes[0]["attribute"]["id"] == size_attribute_id- product.refresh_from_db()- assert product.search_document- assert attr_value.lower() in product.search_document-@patch("saleor.plugins.manager.PluginsManager.product_variant_created")@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")@@ -2045,10 +2033,6 @@ def test_update_product_variant()product_variant_created_webhook_mock.assert_not_called()- product.refresh_from_db()- assert product.search_document- assert attr_value.lower() in product.search_document-def test_update_product_variant_with_negative_weight(staff_api_client, product, permission_manage_products@@ -2165,9 +2149,6 @@ def test_update_product_variant_change_sku(assert data["sku"] == skuvariant.refresh_from_db()assert variant.sku == sku- product.refresh_from_db()- assert product.search_document- assert sku.lower() in product.search_documentdef test_update_product_variant_without_sku_keep_it_empty(@@ -3338,9 +3319,6 @@ def test_delete_variant(with pytest.raises(variant._meta.model.DoesNotExist):variant.refresh_from_db()mocked_recalculate_orders_task.assert_not_called()- product.refresh_from_db()- assert product.search_document- assert variant_sku not in product.search_documentdef test_delete_variant_remove_checkout_lines(@@ -3653,8 +3631,6 @@ def test_delete_variant_delete_product_channel_listing_without_available_channelvariant.refresh_from_db()mocked_recalculate_orders_task.assert_not_called()product.refresh_from_db()- assert product.search_document- assert variant_sku not in product.search_documentassert product.channel_listings.count() == 0@@ -3695,8 +3671,6 @@ def test_delete_variant_delete_product_channel_listing_not_deleted(variant.refresh_from_db()mocked_recalculate_orders_task.assert_not_called()product.refresh_from_db()- assert product.search_document- assert variant_sku not in product.search_documentassert product.channel_listings.count() == product_channel_listing_count@@ -4163,9 +4137,6 @@ def test_product_variant_bulk_create_by_attribute_id(product.refresh_from_db()assert product.default_variant == product_variantassert product_variant_created_webhook_mock.call_count == data["count"]- assert product.search_document- assert sku in product.search_document- assert attribute_value.name.lower() in product.search_documentdef test_product_variant_bulk_create_with_swatch_attribute(@@ -4214,9 +4185,6 @@ def test_product_variant_bulk_create_with_swatch_attribute(product_variant = ProductVariant.objects.get(sku=sku)product.refresh_from_db()assert product.default_variant == product_variant- assert product.search_document- assert variants[0]["sku"] in product.search_document- assert variants[1]["sku"] in product.search_documentdef test_product_variant_bulk_create_only_not_variant_selection_attributes(@@ -4264,9 +4232,6 @@ def test_product_variant_bulk_create_only_not_variant_selection_attributes(product_variant = ProductVariant.objects.get(sku=sku)product.refresh_from_db()assert product.default_variant == product_variant- assert product.search_document- assert sku in product.search_document- assert attribute_value.name.lower() in product.search_documentdef test_product_variant_bulk_create_empty_attribute(@@ -4287,8 +4252,6 @@ def test_product_variant_bulk_create_empty_attribute(assert data["count"] == 1product.refresh_from_db()assert product_variant_count + 1 == ProductVariant.objects.count()- assert product.search_document- assert variants[0]["sku"].lower() in product.search_documentdef test_product_variant_bulk_create_with_new_attribute_value(diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 1c342c9ce0..4438565bb2 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -4458,7 +4458,9 @@ enum ProductOrderField {"""Sort products by name."""NAME- """Sort products by name."""+ """+ Sort products by rank. Note: This option is available only with the `search` filter.+ """RANK"""Sort products by price."""diff --git a/saleor/order/migrations/0130_save_order_token_in_relation_models.py b/saleor/order/migrations/0130_save_order_token_in_relation_models.pyindex 96a6145440..958d8d731b 100644--- a/saleor/order/migrations/0130_save_order_token_in_relation_models.py+++ b/saleor/order/migrations/0130_save_order_token_in_relation_models.py@@ -147,20 +147,9 @@ class Migration(migrations.Migration):ALTER TABLE order_order_gift_cardsALTER COLUMN order_token SET NOT NULL;- DO $$- DECLARE query text;- BEGIN- query := FORMAT(- 'alter table order_order_gift_cards drop constraint %s',- (- select constraint_name from information_schema.table_constraints- WHERE table_name = 'order_order_gift_cards'- and constraint_type = 'FOREIGN KEY'- and constraint_name like '%order_order_id'- )- );- EXECUTE query;- END $$;+ ALTER TABLE order_order_gift_cards+ DROP CONSTRAINT+ order_order_gift_cards_order_id_ce5608c4_fk_order_order_id;ALTER TABLE order_order_gift_cardsADD CONSTRAINT order_order_gift_cards_order_id_fk_order_order_numberdiff --git a/saleor/order/migrations/0134_rewrite_order_gift_cards_relation.py b/saleor/order/migrations/0134_rewrite_order_gift_cards_relation.pyindex a99c4349a1..e222566ca1 100644--- a/saleor/order/migrations/0134_rewrite_order_gift_cards_relation.py+++ b/saleor/order/migrations/0134_rewrite_order_gift_cards_relation.py@@ -35,7 +35,7 @@ class Migration(migrations.Migration):ALTER TABLE order_order_gift_cardsRENAME CONSTRAINT order_order_gift_cards_order_token_fk_order_order_id- TO order_order_gift_cards_order_id_fk_order_order_id;+ TO order_order_gift_cards_order_id_ce5608c4_fk_order_order_id;""",reverse_sql=migrations.RunSQL.noop,),diff --git a/saleor/product/migrations/0164_auto_20220311_1430.py b/saleor/product/migrations/0164_auto_20220311_1430.pynew file mode 100644index 0000000000..8fc52dde15--- /dev/null+++ b/saleor/product/migrations/0164_auto_20220311_1430.py@@ -0,0 +1,28 @@+# Generated by Django 3.2.12 on 2022-03-11 14:30++import django.contrib.postgres.indexes+import django.contrib.postgres.search+from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("product", "0163_auto_20220414_1025"),+ ]++ operations = [+ migrations.AddField(+ model_name="product",+ name="search_vector",+ field=django.contrib.postgres.search.SearchVectorField(+ blank=True, null=True+ ),+ ),+ migrations.AddIndex(+ model_name="product",+ index=django.contrib.postgres.indexes.GinIndex(+ fields=["search_vector"], name="product_tsearch"+ ),+ ),+ ]diff --git a/saleor/product/migrations/0165_update_product_search_document.py b/saleor/product/migrations/0165_update_product_search_document.pynew file mode 100644index 0000000000..423f77727c--- /dev/null+++ b/saleor/product/migrations/0165_update_product_search_document.py@@ -0,0 +1,25 @@+from django.db import migrations+from django.db.models.signals import post_migrate++from ...core.search_tasks import set_product_search_document_values+++def update_product_search_document_values(apps, _schema_editor):+ def on_migrations_complete(sender=None, **kwargs):+ set_product_search_document_values.delay()++ post_migrate.connect(on_migrations_complete)+++class Migration(migrations.Migration):++ dependencies = [+ ("product", "0164_auto_20220311_1430"),+ ]++ operations = [+ migrations.RunPython(+ update_product_search_document_values,+ reverse_code=migrations.RunPython.noop,+ ),+ ]diff --git a/saleor/product/models.py b/saleor/product/models.pyindex 7d12e84ac7..4a6297734b 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -396,6 +396,7 @@ class Product(SeoModel, ModelWithMetadata):description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)description_plaintext = TextField(blank=True)search_document = models.TextField(blank=True, default="")+ search_vector = SearchVectorField(blank=True, null=True)category = models.ForeignKey(Category,@@ -434,10 +435,13 @@ class Product(SeoModel, ModelWithMetadata):indexes = [GinIndex(name="product_search_gin",- # `opclasses` and `fields` should be the same lengthfields=["search_document"],opclasses=["gin_trgm_ops"],),+ GinIndex(+ name="product_tsearch",+ fields=["search_vector"],+ ),]indexes.extend(ModelWithMetadata.Meta.indexes)diff --git a/saleor/product/search.py b/saleor/product/search.pyindex f41a39d9d9..3cd5a24fa5 100644--- a/saleor/product/search.py+++ b/saleor/product/search.py@@ -1,6 +1,9 @@-from typing import TYPE_CHECKING, Union+from functools import reduce+from operator import add+from typing import TYPE_CHECKING, Optional, Union-from django.db.models import Q, prefetch_related_objects+from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector+from django.db.models import F, Q, Value, prefetch_related_objectsfrom ..attribute import AttributeInputTypefrom ..core.utils.editorjs import clean_editor_js@@ -22,73 +25,77 @@ PRODUCT_FIELDS_TO_PREFETCH = []-def update_products_search_document(products: "QuerySet"):+def update_products_search_vector(products: "QuerySet"):products = products.prefetch_related(*PRODUCT_FIELDS_TO_PREFETCH)for product in products:- product.search_document = prepare_product_search_document_value(+ product.search_vector = prepare_product_search_vector_value(product, already_prefetched=True)- Product.objects.bulk_update(products, ["search_document", "updated_at"])+ Product.objects.bulk_update(products, ["search_vector", "updated_at"])-def update_product_search_document(product: "Product"):- product.search_document = prepare_product_search_document_value(product)- product.save(update_fields=["search_document", "updated_at"])+def update_product_search_vector(product: "Product"):+ product.search_vector = prepare_product_search_vector_value(product)+ product.save(update_fields=["search_vector", "updated_at"])-def prepare_product_search_document_value(+def prepare_product_search_vector_value(product: "Product", *, already_prefetched=False-):+) -> SearchVector:if not already_prefetched:prefetch_related_objects([product], *PRODUCT_FIELDS_TO_PREFETCH)- search_document = generate_product_fields_search_document_value(product)- search_document += generate_attributes_search_document_value(+ search_vector = SearchVector(Value(product.name), weight="A") + SearchVector(+ Value(product.description_plaintext), weight="C"+ )+ attributes_vector = generate_attributes_search_vector_value(product.attributes.all())- search_document += generate_variants_search_document_value(product)-- return search_document.lower()---def generate_product_fields_search_document_value(product: "Product"):- value = "\n".join(- [- getattr(product, field)- for field in PRODUCT_SEARCH_FIELDS- if getattr(product, field)- ]+ if attributes_vector:+ search_vector += attributes_vector+ variants_vector = generate_variants_search_vector_value(product)+ if variants_vector:+ search_vector += variants_vector++ return search_vector+++def generate_variants_search_vector_value(product: "Product") -> Optional[SearchVector]:+ variants = list(product.variants.all())++ if not variants:+ return None++ search_vector = reduce(+ add,+ (+ SearchVector(Value(variant.sku), Value(variant.name), weight="A")+ if variant.sku+ else SearchVector(Value(variant.name), weight="A")+ for variant in variants+ if variant.sku or variant.name+ ),)- if value:- value += "\n"- return value.lower()---def generate_variants_search_document_value(product: "Product"):- variants = product.variants.all()- variants_data = "\n".join([variant.sku for variant in variants if variant.sku])- if variants_data:- variants_data += "\n"for variant in variants:- variant_attribute_data = generate_attributes_search_document_value(+ attribute_vector = generate_attributes_search_vector_value(variant.attributes.all())- if variant_attribute_data:- variants_data += variant_attribute_data+ if attribute_vector:+ search_vector += attribute_vector- return variants_data.lower()+ return search_vector-def generate_attributes_search_document_value(+def generate_attributes_search_vector_value(assigned_attributes: "QuerySet",-):- """Prepare `search_document` value for assigned attributes.+) -> Optional[SearchVector]:+ """Prepare `search_vector` value for assigned attributes.Method should received assigned attributes with prefetched `values`and `assignment__attribute`."""- attribute_data = ""+ search_vector = Nonefor assigned_attribute in assigned_attributes:attribute = assigned_attribute.assignment.attribute@@ -102,21 +109,31 @@ def generate_attributes_search_document_value(clean_editor_js(value.rich_text, to_string=True) for value in values]elif input_type == AttributeInputType.NUMERIC:- unit = attribute.unit or ""- values_list = [value.name + unit for value in values]+ unit = attribute.unit+ values_list = [+ value.name + " " + unit if unit else value.name for value in values+ ]elif input_type in [AttributeInputType.DATE, AttributeInputType.DATE_TIME]:- values_list = [value.date_time.isoformat() for value in values]+ values_list = [+ value.date_time.strftime("%Y-%m-%d %H:%M:%S") for value in values+ ]if values_list:- values_data = "\n".join(values_list)- attribute_data += values_data + "\n"- return attribute_data.lower()+ new_vector = reduce(+ add, (SearchVector(Value(v), weight="B") for v in values_list)+ )+ if search_vector is not None:+ search_vector += new_vector+ else:+ search_vector = new_vector+ return search_vectordef search_products(qs, value):if value:- lookup = Q()- for val in value.split():- lookup &= Q(search_document__ilike=val)- qs = qs.filter(lookup)+ query = SearchQuery(value, search_type="websearch")+ lookup = Q(search_vector=query)+ qs = qs.filter(lookup).annotate(+ search_rank=SearchRank(F("search_vector"), query)+ )return qsdiff --git a/saleor/product/tests/test_product_search.py b/saleor/product/tests/test_product_search.pyindex 8f220b1d43..a645d3431e 100644--- a/saleor/product/tests/test_product_search.py+++ b/saleor/product/tests/test_product_search.py@@ -1,16 +1,8 @@-from ...attribute import AttributeInputType, AttributeType-from ...attribute.models import Attribute, AttributeValue-from ...attribute.utils import associate_attribute_values_to_instance-from ...core.utils.editorjs import clean_editor_js-from ..models import Product, ProductVariant-from ..search import (- prepare_product_search_document_value,- update_product_search_document,- update_products_search_document,-)+from ..models import Product+from ..search import update_product_search_vector, update_products_search_vector-def test_update_product_search_document(product_type, category):+def test_update_product_search_vector(product_type, category):# givenname = "Test product"description = "Test description"@@ -21,158 +13,25 @@ def test_update_product_search_document(product_type, category):category=category,description_plaintext=description,)- assert not product.search_document+ assert not product.search_vector# when- update_product_search_document(product)+ update_product_search_vector(product)# then- assert f"{name}\n{description}\n".lower() in product.search_document+ assert product.search_vector-def test_update_products_search_document(product_list):+def test_update_products_search_vector(product_list):# givenfor product in product_list:- product.search_document = ""- Product.objects.bulk_update(product_list, ["search_document"])+ product.search_vector = None+ Product.objects.bulk_update(product_list, ["search_vector"])# when- update_products_search_document(Product.objects.all())+ update_products_search_vector(Product.objects.all())# thenfor product in product_list:product.refresh_from_db()- assert product.search_document---def test_prepare_product_search_document_value_empty_product(product_type, category):- # given- name = "Test product"- description = "Test description"- product = Product.objects.create(- name=name,- slug="test-product-11",- product_type=product_type,- category=category,- description_plaintext=description,- )-- # when- search_document_value = prepare_product_search_document_value(product)-- # then- assert search_document_value == f"{name}\n{description}\n".lower()---def test_prepare_product_search_document_value(- category,- product_type,- rich_text_attribute_with_many_values,- date_time_attribute,- date_attribute,- color_attribute,- size_attribute,- numeric_attribute,-):- # given- multiselect_attribute = Attribute.objects.create(- slug="modes",- name="Available Modes",- input_type=AttributeInputType.MULTISELECT,- type=AttributeType.PRODUCT_TYPE,- )-- multiselect_attr_val_1 = AttributeValue.objects.create(- attribute=multiselect_attribute, name="Eco Mode", slug="eco"- )- multiselect_attr_val_2 = AttributeValue.objects.create(- attribute=multiselect_attribute, name="Performance Mode", slug="power"- )-- name = "Test product"- description = "Test description"- product = Product.objects.create(- name=name,- slug="test-product-11",- product_type=product_type,- category=category,- description_plaintext=description,- )-- product_type.product_attributes.add(- rich_text_attribute_with_many_values,- date_time_attribute,- color_attribute,- numeric_attribute,- )- rich_text_val_1 = rich_text_attribute_with_many_values.values.first()- date_time_value = date_time_attribute.values.first()- color_attribute_value = color_attribute.values.first()- numeric_attribute_value = numeric_attribute.values.first()- associate_attribute_values_to_instance(- product, rich_text_attribute_with_many_values, rich_text_val_1- )- associate_attribute_values_to_instance(- product, date_time_attribute, date_time_value- )- associate_attribute_values_to_instance(- product, color_attribute, color_attribute_value- )- associate_attribute_values_to_instance(- product, numeric_attribute, numeric_attribute_value- )-- variant = ProductVariant.objects.create(product=product, sku="123")- product_type.variant_attributes.add(- rich_text_attribute_with_many_values,- date_attribute,- size_attribute,- multiselect_attribute,- )- rich_text_val_2 = rich_text_attribute_with_many_values.values.last()- size_attribute_value = size_attribute.values.first()- date_attribute_value = date_attribute.values.first()- associate_attribute_values_to_instance(- variant, rich_text_attribute_with_many_values, rich_text_val_2- )- associate_attribute_values_to_instance(- variant, size_attribute, size_attribute_value- )- associate_attribute_values_to_instance(- variant, date_attribute, date_attribute_value- )-- variant_2 = ProductVariant.objects.create(product=product, sku="123ABC")- associate_attribute_values_to_instance(- variant_2, multiselect_attribute, multiselect_attr_val_1, multiselect_attr_val_2- )-- # when- search_document_value = prepare_product_search_document_value(product)-- # then- assert f"{name}\n{description}\n".lower() in search_document_value- assert variant.sku.lower() in search_document_value- assert variant_2.sku.lower() in search_document_value-- # check if product attributes are in search_document_value- assert (- clean_editor_js(rich_text_val_1.rich_text, to_string=True).lower()- in search_document_value- )- assert date_time_value.date_time.isoformat().lower() in search_document_value- assert color_attribute_value.name.lower() in search_document_value- assert (- f"{numeric_attribute_value.name}{numeric_attribute.unit}"- in search_document_value- )-- # check if variant attributes are in search_document_value- assert (- clean_editor_js(rich_text_val_2.rich_text, to_string=True).lower()- in search_document_value- )- assert size_attribute_value.name.lower() in search_document_value- assert date_attribute_value.date_time.isoformat().lower() in search_document_value- assert multiselect_attr_val_1.name.lower() in search_document_value- assert multiselect_attr_val_2.name.lower() in search_document_value+ assert product.search_vectordiff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 72c9514ee5..7619e04cf5 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -106,7 +106,7 @@ from ..product.models import (ProductVariantTranslation,VariantMedia,)-from ..product.search import prepare_product_search_document_value+from ..product.search import prepare_product_search_vector_valuefrom ..product.tests.utils import create_imagefrom ..shipping.models import (ShippingMethod,@@ -2134,8 +2134,8 @@ def product_with_two_variants(product_type, category, warehouse, channel_USD):for variant in variants])- product.search_document = prepare_product_search_document_value(product)- product.save(update_fields=["search_document"])+ product.search_vector = prepare_product_search_vector_value(product)+ product.save(update_fields=["search_vector"])return product@@ -2350,8 +2350,8 @@ def product_with_default_variant()Stock.objects.create(warehouse=warehouse, product_variant=variant, quantity=100)- product.search_document = prepare_product_search_document_value(product)- product.save(update_fields=["search_document"])+ product.search_vector = prepare_product_search_vector_value(product)+ product.save(update_fields=["search_vector"])return product@@ -2758,9 +2758,9 @@ def product_list(product_type, category, warehouse, channel_USD, channel_PLN):for product in products:associate_attribute_values_to_instance(product, product_attr, attr_value)- product.search_document = prepare_product_search_document_value(product)+ product.search_vector = prepare_product_search_vector_value(product)- Product.objects.bulk_update(products, ["search_document"])+ Product.objects.bulk_update(products, ["search_vector"])return products