Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Improve product search (#8734)
Iga Karbowiak2221bdf61b03
diff --git a/saleor/account/migrations/0058_update_user_search_document.py b/saleor/account/migrations/0058_update_user_search_document.pynew file mode 100644index 0000000000..745a925dd7--- /dev/null+++ b/saleor/account/migrations/0058_update_user_search_document.py@@ -0,0 +1,24 @@+# Generated by Django 3.2.6 on 2021-12-27 09:47++from django.db import migrations++from ...core.search_tasks import set_user_search_document_values+++def update_user_search_document_values(apps, _schema_editor):+ User = apps.get_model("account", "User")+ total_count = User.objects.filter(search_document="").count()+ set_user_search_document_values.delay(total_count, 0)+++class Migration(migrations.Migration):++ dependencies = [+ ("account", "0057_user_search_document"),+ ]++ operations = [+ migrations.RunPython(+ update_user_search_document_values, reverse_code=migrations.RunPython.noop+ ),+ ]diff --git a/saleor/core/management/commands/set_order_search_document_values.py b/saleor/core/management/commands/set_order_search_document_values.pydeleted file mode 100644index 2572645720..0000000000--- a/saleor/core/management/commands/set_order_search_document_values.py+++ /dev/null@@ -1,14 +0,0 @@-from typing import Any--from django.core.management import BaseCommand--from ....order.models import Order-from ...search_tasks import set_order_search_document_values---class Command(BaseCommand):- help = "Used to set search document values for order."-- def handle(self, *args: Any, **options: Any):- total_count = Order.objects.filter(search_document="").count()- set_order_search_document_values.delay(total_count, 0)diff --git a/saleor/core/management/commands/set_user_search_document_values.py b/saleor/core/management/commands/set_user_search_document_values.pydeleted file mode 100644index df3c6d8b8d..0000000000--- a/saleor/core/management/commands/set_user_search_document_values.py+++ /dev/null@@ -1,14 +0,0 @@-from typing import Any--from django.core.management import BaseCommand--from ....account.models import User-from ...search_tasks import set_user_search_document_values---class Command(BaseCommand):- help = "Used to set search document values for users."-- def handle(self, *args: Any, **options: Any):- total_count = User.objects.filter(search_document="").count()- set_user_search_document_values.delay(total_count, 0)diff --git a/saleor/core/search_tasks.py b/saleor/core/search_tasks.pyindex 61816690ba..15f63e6b41 100644--- a/saleor/core/search_tasks.py+++ b/saleor/core/search_tasks.py@@ -5,6 +5,11 @@ from ..account.search import prepare_user_search_document_valuefrom ..celeryconf import appfrom ..order.models import Orderfrom ..order.search import prepare_order_search_document_value+from ..product.models import Product+from ..product.search import (+ PRODUCT_FIELDS_TO_PREFETCH,+ prepare_product_search_document_value,+)task_logger = get_task_logger(__name__)@@ -19,19 +24,9 @@ def set_user_search_document_values(total_count, updated_count):if not qs:task_logger.info("No users to update.")return- users = []- for user in qs:- user.search_document = prepare_user_search_document_value(- user, already_prefetched=True- )- users.append(user)- User.objects.bulk_update(users, ["search_document"])-- updated_count += len(users)- progress = round((updated_count / total_count) * 100, 2)- task_logger.info(- f"Updated {updated_count} from {total_count} users - {progress}% done."+ updated_count = set_search_document_values(+ qs, total_count, updated_count, prepare_user_search_document_value)if updated_count == total_count:@@ -55,19 +50,8 @@ def set_order_search_document_values(total_count, updated_count):task_logger.info("No orders to update.")return- orders = []- for order in qs:- order.search_document = prepare_order_search_document_value(- order, already_prefetched=True- )- orders.append(order)- Order.objects.bulk_update(orders, ["search_document"])-- updated_count += len(orders)- progress = round((updated_count / total_count) * 100, 2)-- task_logger.info(- f"Updated {updated_count} from {total_count} orders - {progress}% done."+ updated_count = set_search_document_values(+ qs, total_count, updated_count, prepare_order_search_document_value)if updated_count == total_count:@@ -75,3 +59,45 @@ def set_order_search_document_values(total_count, updated_count):returnreturn set_order_search_document_values.delay(total_count, updated_count)+++def set_product_search_document_values(total_count, updated_count):+ qs = Product.objects.filter(search_document="").prefetch_related(+ *PRODUCT_FIELDS_TO_PREFETCH+ )[:BATCH_SIZE]+ if not qs:+ task_logger.info("No products to update.")+ return++ updated_count = set_search_document_values(+ qs, total_count, updated_count, prepare_product_search_document_value+ )++ if updated_count == total_count:+ task_logger.info("Setting product search document values finished.")+ return++ return set_product_search_document_values.delay(total_count, updated_count)+++def set_search_document_values(+ qs, total_count, updated_count, prepare_search_document_func+):+ Model = qs.model+ instances = []+ for instance in qs:+ instance.search_document = prepare_search_document_func(+ instance, already_prefetched=True+ )+ instances.append(instance)+ Model.objects.bulk_update(instances, ["search_document"])++ updated_count += len(instances)+ progress = round((updated_count / total_count) * 100, 2)++ task_logger.info(+ f"Updated {updated_count} from {total_count} {Model.__name__.lower()}s - "+ f"{progress}% done."+ )+ return updated_countdiff --git a/saleor/core/tests/test_postgresql_search.py b/saleor/core/tests/test_postgresql_search.pyindex b54e016a33..ed75104176 100644--- a/saleor/core/tests/test_postgresql_search.py+++ b/saleor/core/tests/test_postgresql_search.py@@ -2,8 +2,8 @@ import pytestfrom django.utils.text import slugifyfrom ...account.models import Address-from ...graphql.product.filters import product_searchfrom ...product.models import Product, ProductChannelListing+from ...product.search import search_productsfrom ...tests.utils import dummy_editorjsPRODUCTS = [@@ -23,6 +23,7 @@ def named_products(category, product_type, channel_USD):description_plaintext=description,product_type=product_type,category=category,+ search_document=f"{name}{description}",)ProductChannelListing.objects.create(product=product,@@ -37,7 +38,7 @@ def named_products(category, product_type, channel_USD):def execute_search(phrase):"""Execute storefront search."""qs = Product.objects.all()- return product_search(qs, phrase)+ return search_products(qs, phrase)@pytest.mark.parametrize(diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex f10ba712cc..0b9c79166b 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -79,6 +79,7 @@ from ...product.models import (ProductVariantChannelListing,VariantMedia,)+from ...product.search import update_products_search_documentfrom ...product.tasks import update_products_discounted_prices_of_discount_taskfrom ...product.thumbnails import (create_category_background_image_thumbnails,@@ -461,6 +462,8 @@ def create_products_by_schema(placeholder_dir, create_images):)assign_products_to_collections(associations=types["product.collectionproduct"])+ update_products_search_document(Product.objects.all())+class SaleorProvider(BaseProvider):def money(self):diff --git a/saleor/graphql/attribute/bulk_mutations.py b/saleor/graphql/attribute/bulk_mutations.pyindex 92d39e6554..718b40e27a 100644--- a/saleor/graphql/attribute/bulk_mutations.py+++ b/saleor/graphql/attribute/bulk_mutations.py@@ -1,9 +1,13 @@import graphene+from django.db.models import Exists, OuterRef, Qfrom ...attribute import modelsfrom ...core.permissions import PageTypePermissions+from ...product import models as product_models+from ...product.search import update_products_search_documentfrom ..core.mutations import ModelBulkDeleteMutationfrom ..core.types.common import AttributeError+from ..utils import resolve_global_ids_to_primary_keysclass AttributeBulkDelete(ModelBulkDeleteMutation):@@ -19,6 +23,43 @@ class AttributeBulkDelete(ModelBulkDeleteMutation):error_type_class = AttributeErrorerror_type_field = "attribute_errors"+ @classmethod+ def perform_mutation(cls, _root, info, ids, **data):+ if not ids:+ return 0, {}+ _, 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(+ product_models.Product.objects.filter(id__in=product_ids)+ )+ return response++ @classmethod+ def get_product_ids_to_update(cls, attribute_pks):+ attribute_product = models.AttributeProduct.objects.filter(+ attribute_id__in=attribute_pks+ )+ assigned_product_attrs = models.AssignedProductAttribute.objects.filter(+ Exists(attribute_product.filter(id=OuterRef("assignment_id")))+ )++ attribute_variant = models.AttributeVariant.objects.filter(+ attribute_id__in=attribute_pks+ )+ assigned_variant_attrs = models.AssignedVariantAttribute.objects.filter(+ Exists(attribute_variant.filter(id=OuterRef("assignment_id")))+ )+ variants = product_models.ProductVariant.objects.filter(+ Exists(assigned_variant_attrs.filter(variant_id=OuterRef("id")))+ )++ product_ids = product_models.Product.objects.filter(+ Exists(assigned_product_attrs.filter(product_id=OuterRef("id")))+ | Q(Exists(variants.filter(product_id=OuterRef("id"))))+ ).values_list("id", flat=True)+ return list(product_ids)+class AttributeValueBulkDelete(ModelBulkDeleteMutation):class Arguments:@@ -34,3 +75,40 @@ class AttributeValueBulkDelete(ModelBulkDeleteMutation):permissions = (PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES,)error_type_class = AttributeErrorerror_type_field = "attribute_errors"++ @classmethod+ def perform_mutation(cls, _root, info, ids, **data):+ if not ids:+ return 0, {}+ _, 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(+ product_models.Product.objects.filter(id__in=product_ids)+ )+ return response++ @classmethod+ def get_product_ids_to_update(cls, value_pks):+ assigned_product_values = models.AssignedProductAttributeValue.objects.filter(+ value_id__in=value_pks+ )+ assigned_product_attrs = models.AssignedProductAttribute.objects.filter(+ Exists(assigned_product_values.filter(assignment_id=OuterRef("id")))+ )++ assigned_variant_values = models.AssignedVariantAttributeValue.objects.filter(+ value_id__in=value_pks+ )+ assigned_variant_attrs = models.AssignedVariantAttribute.objects.filter(+ Exists(assigned_variant_values.filter(assignment_id=OuterRef("id")))+ )+ variants = product_models.ProductVariant.objects.filter(+ Exists(Exists(assigned_variant_attrs.filter(variant_id=OuterRef("id"))))+ )++ product_ids = product_models.Product.objects.filter(+ Exists(assigned_product_attrs.filter(product_id=OuterRef("id")))+ | Q(Exists(variants.filter(product_id=OuterRef("id"))))+ ).values_list("id", flat=True)+ return list(product_ids)diff --git a/saleor/graphql/attribute/mutations.py b/saleor/graphql/attribute/mutations.pyindex 7a1bbfb1c0..91819a85b0 100644--- a/saleor/graphql/attribute/mutations.py+++ b/saleor/graphql/attribute/mutations.py@@ -2,6 +2,7 @@ from typing import TYPE_CHECKINGimport graphenefrom django.core.exceptions import ObjectDoesNotExist, ValidationError+from django.db.models import Exists, OuterRef, Qfrom django.utils.text import slugifyfrom ...attribute import ATTRIBUTE_PROPERTIES_CONFIGURATION, AttributeInputType@@ -14,6 +15,8 @@ from ...core.permissions import (ProductTypePermissions,)from ...core.tracing import traced_atomic_transaction+from ...product import models as product_models+from ...product.search import update_products_search_documentfrom ..attribute.types import Attribute, AttributeValuefrom ..core.enums import MeasurementUnitsEnumfrom ..core.inputs import ReorderInput@@ -712,6 +715,18 @@ class AttributeValueUpdate(AttributeValueCreate):response.attribute = instance.attributereturn response+ @classmethod+ def post_save_action(cls, info, instance, cleaned_input):+ super().post_save_action(info, instance, cleaned_input)+ variants = product_models.ProductVariant.objects.filter(+ Exists(instance.variantassignments.filter(variant_id=OuterRef("id")))+ )+ products = product_models.Product.objects.filter(+ Q(Exists(instance.productassignments.filter(product_id=OuterRef("id"))))+ | Q(Exists(variants.filter(product_id=OuterRef("id"))))+ )+ update_products_search_document(products)+class AttributeValueDelete(ModelDeleteMutation):attribute = graphene.Field(Attribute, description="The updated attribute.")@@ -726,6 +741,28 @@ class AttributeValueDelete(ModelDeleteMutation):error_type_class = AttributeErrorerror_type_field = "attribute_errors"+ @classmethod+ def perform_mutation(cls, _root, info, **data):+ node_id = data.get("id")+ 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(+ product_models.Product.objects.filter(id__in=product_ids)+ )+ return response++ @classmethod+ def get_product_ids_to_update(cls, instance):+ variants = product_models.ProductVariant.objects.filter(+ Exists(instance.variantassignments.filter(variant_id=OuterRef("id")))+ )+ product_ids = product_models.Product.objects.filter(+ Q(Exists(instance.productassignments.filter(product_id=OuterRef("id"))))+ | Q(Exists(variants.filter(product_id=OuterRef("id"))))+ ).values_list("id", flat=True)+ return list(product_ids)+@classmethoddef success_response(cls, instance):response = super().success_response(instance)diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py b/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.pyindex 60b1605d0f..e01a5f5bb2 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py@@ -3,6 +3,8 @@ from unittest.mock import patchimport grapheneimport pytest+from .....attribute.utils import associate_attribute_values_to_instance+ATTRIBUTE_VALUE_DELETE_MUTATION = """mutation AttributeValueDelete($id: ID!) {attributeValueDelete(id: $id) {@@ -63,3 +65,78 @@ def test_delete_file_attribute_value(with pytest.raises(value._meta.model.DoesNotExist):value.refresh_from_db()delete_from_storage_mock.assert_called_once_with(file_url)+++@patch("saleor.attribute.signals.delete_from_storage_task.delay")+def test_delete_attribute_value_product_search_document_updated(+ delete_from_storage_mock,+ staff_api_client,+ color_attribute,+ permission_manage_product_types_and_attributes,+ product,+):+ # given+ attribute = color_attribute+ name = "Red"+ value = color_attribute.values.get(name=name)++ product_type = product.product_type+ product_type.product_attributes.add(attribute)++ associate_attribute_values_to_instance(product, attribute, value)++ query = ATTRIBUTE_VALUE_DELETE_MUTATION+ node_id = graphene.Node.to_global_id("AttributeValue", value.id)+ variables = {"id": node_id}++ # when+ staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )++ # then+ with pytest.raises(value._meta.model.DoesNotExist):+ value.refresh_from_db()+ delete_from_storage_mock.assert_not_called()++ product.refresh_from_db()+ assert product.search_document+ assert name.lower() not in product.search_document+++@patch("saleor.attribute.signals.delete_from_storage_task.delay")+def test_delete_attribute_value_product_search_document_updated_variant_attribute(+ delete_from_storage_mock,+ staff_api_client,+ color_attribute,+ permission_manage_product_types_and_attributes,+ variant,+):+ # given+ name = "Red"+ attribute = color_attribute+ value = color_attribute.values.get(name=name)++ product = variant.product+ product_type = product.product_type+ product_type.variant_attributes.add(attribute)++ associate_attribute_values_to_instance(variant, attribute, value)++ query = ATTRIBUTE_VALUE_DELETE_MUTATION+ node_id = graphene.Node.to_global_id("AttributeValue", value.id)+ variables = {"id": node_id}++ # when+ staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )++ # then+ with pytest.raises(value._meta.model.DoesNotExist):+ value.refresh_from_db()+ delete_from_storage_mock.assert_not_called()++ 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 2243c3682a..449ea81a60 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py@@ -3,6 +3,7 @@ import pytestfrom django.utils.text import slugifyfrom .....attribute.error_codes import AttributeErrorCode+from .....attribute.utils import associate_attribute_values_to_instancefrom ....tests.utils import get_graphql_contentUPDATE_ATTRIBUTE_VALUE_MUTATION = """@@ -93,6 +94,85 @@ def test_update_attribute_value_name_not_unique(assert data["errors"][0]["code"] == AttributeErrorCode.ALREADY_EXISTS.name+def test_update_attribute_value_product_search_document_updated(+ staff_api_client,+ pink_attribute_value,+ permission_manage_product_types_and_attributes,+ product,+):+ # given+ query = UPDATE_ATTRIBUTE_VALUE_MUTATION+ attribute = pink_attribute_value.attribute+ value = pink_attribute_value++ product_type = product.product_type+ product_type.product_attributes.add(attribute)++ associate_attribute_values_to_instance(product, attribute, value)++ node_id = graphene.Node.to_global_id("AttributeValue", value.id)+ name = "Crimson name"+ variables = {"input": {"name": name}, "id": node_id}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["attributeValueUpdate"]+ value.refresh_from_db()+ assert data["attributeValue"]["name"] == name == value.name+ assert data["attributeValue"]["slug"] == slugify(name)+ assert name in [+ 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,+ pink_attribute_value,+ permission_manage_product_types_and_attributes,+ variant,+):+ # given+ query = UPDATE_ATTRIBUTE_VALUE_MUTATION+ attribute = pink_attribute_value.attribute+ value = pink_attribute_value++ product = variant.product+ product_type = product.product_type+ product_type.variant_attributes.add(attribute)++ associate_attribute_values_to_instance(variant, attribute, value)++ node_id = graphene.Node.to_global_id("AttributeValue", value.id)+ name = "Crimson name"+ variables = {"input": {"name": name}, "id": node_id}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["attributeValueUpdate"]+ value.refresh_from_db()+ assert data["attributeValue"]["name"] == name == value.name+ assert data["attributeValue"]["slug"] == slugify(name)+ assert name in [+ value["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,swatch_attribute,diff --git a/saleor/graphql/attribute/tests/mutations/test_bulk_delete.py b/saleor/graphql/attribute/tests/mutations/test_bulk_delete.pyindex 0064f1e344..fe10b2ff2e 100644--- a/saleor/graphql/attribute/tests/mutations/test_bulk_delete.py+++ b/saleor/graphql/attribute/tests/mutations/test_bulk_delete.py@@ -2,8 +2,17 @@ import grapheneimport pytestfrom .....attribute.models import Attribute, AttributeValue+from .....attribute.utils import associate_attribute_values_to_instancefrom ....tests.utils import get_graphql_content+ATTRIBUTE_BULK_DELETE_MUTATION = """+ mutation attributeBulkDelete($ids: [ID]!) {+ attributeBulkDelete(ids: $ids) {+ count+ }+ }+"""+@pytest.fixturedef attribute_value_list(color_attribute):@@ -24,13 +33,7 @@ def test_delete_attributes(product_type_attribute_list,permission_manage_page_types_and_attributes,):- query = """- mutation attributeBulkDelete($ids: [ID]!) {- attributeBulkDelete(ids: $ids) {- count- }- }- """+ query = ATTRIBUTE_BULK_DELETE_MUTATIONvariables = {"ids": [@@ -49,16 +52,82 @@ def test_delete_attributes().exists()-def test_delete_attribute_values(- staff_api_client, attribute_value_list, permission_manage_page_types_and_attributes+def test_delete_attributes_products_search_document_updated(+ staff_api_client,+ product_type_attribute_list,+ permission_manage_page_types_and_attributes,+ product_list,+ color_attribute,):- query = """+ query = ATTRIBUTE_BULK_DELETE_MUTATION+ product_1 = product_list[0]+ product_2 = product_list[1]+ variant_1 = product_1.variants.first()++ product_type = product_1.product_type++ attr_1, attr_2, attr_3 = product_type_attribute_list+ product_type.product_attributes.add(attr_1, attr_2, color_attribute)+ product_type.variant_attributes.add(attr_1, attr_3)++ attr_1_name = "attr 1 value"+ attr_1_value = AttributeValue.objects.create(name=attr_1_name, attribute=attr_1)++ color_attribute_value = color_attribute.values.first()++ attr_2_name = "attr 2 value"+ attr_2_value = AttributeValue.objects.create(name=attr_2_name, attribute=attr_2)++ attr_3_name = "attr 3 value"+ attr_3_value = AttributeValue.objects.create(name=attr_3_name, attribute=attr_3)++ associate_attribute_values_to_instance(product_1, attr_1, attr_1_value)+ associate_attribute_values_to_instance(+ product_1, color_attribute, color_attribute_value+ )+ associate_attribute_values_to_instance(product_2, attr_2, attr_2_value)+ associate_attribute_values_to_instance(variant_1, attr_3, attr_3_value)++ variables = {+ "ids": [+ graphene.Node.to_global_id("Attribute", attr.id)+ for attr in product_type_attribute_list+ ]+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_page_types_and_attributes]+ )+ content = get_graphql_content(response)++ assert content["data"]["attributeBulkDelete"]["count"] == 3+ assert not Attribute.objects.filter(+ 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]!) {attributeValueBulkDelete(ids: $ids) {count}}- """+"""+++def test_delete_attribute_values(+ staff_api_client, attribute_value_list, permission_manage_page_types_and_attributes+):+ query = ATTRIBUTE_VALUE_BULK_DELETE_MUTATIONvariables = {"ids": [@@ -75,3 +144,61 @@ def test_delete_attribute_values(assert not AttributeValue.objects.filter(id__in=[val.id for val in attribute_value_list]).exists()+++def test_delete_attribute_values_search_document_updated(+ staff_api_client,+ product_list,+ attribute_value_list,+ permission_manage_page_types_and_attributes,+):+ query = ATTRIBUTE_VALUE_BULK_DELETE_MUTATION+ value_1, value_2, value_3 = attribute_value_list++ attribute = value_1.attribute+ value_4 = AttributeValue.objects.create(+ 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()+ product_type = product_1.product_type++ product_type.product_attributes.add(attribute)+ product_type.variant_attributes.add(attribute)++ associate_attribute_values_to_instance(product_1, attribute, value_1, value_4)+ associate_attribute_values_to_instance(product_2, attribute, value_2)+ associate_attribute_values_to_instance(variant_1, attribute, value_3)++ variables = {+ "ids": [+ graphene.Node.to_global_id("AttributeValue", val.id)+ for val in attribute_value_list+ ]+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_page_types_and_attributes]+ )+ content = get_graphql_content(response)++ assert content["data"]["attributeValueBulkDelete"]["count"] == 3+ assert not AttributeValue.objects.filter(+ id__in=[val.id for val in attribute_value_list]+ ).exists()++ 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_documentdiff --git a/saleor/graphql/core/connection.py b/saleor/graphql/core/connection.pyindex 759a052c3e..61c0eabe78 100644--- a/saleor/graphql/core/connection.py+++ b/saleor/graphql/core/connection.py@@ -1,5 +1,5 @@import json-from decimal import Decimal, InvalidOperation+from decimal import Decimalfrom typing import Any, Dict, Iterable, List, Optional, Tuple, Union, castimport graphene@@ -51,28 +51,6 @@ 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(rank__range=(rank - EPSILON, rank + EPSILON), id__lt=cursor[1]) | Q(- rank__gt=rank + EPSILON- )- return Q(rank__range=(rank - EPSILON, rank + EPSILON), id__gt=cursor[1]) | Q(- rank__lt=rank - EPSILON- )--def _prepare_filter_expression(field_name: str,index: int,@@ -114,10 +92,6 @@ def _prepare_filter(('first_field', 'first_value_form_cursor')))"""- if sorting_fields == ["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 7807225026..ad384418d1 100644--- a/saleor/graphql/product/bulk_mutations/products.py+++ b/saleor/graphql/product/bulk_mutations/products.py@@ -15,6 +15,10 @@ from ....order import models as order_modelsfrom ....order.tasks import recalculate_orders_taskfrom ....product import modelsfrom ....product.error_codes import ProductErrorCode+from ....product.search import (+ prepare_product_search_document_value,+ update_product_search_document,+)from ....product.tasks import update_product_discounted_price_taskfrom ....product.utils import delete_categoriesfrom ....product.utils.variants import generate_and_set_variant_name@@ -531,6 +535,8 @@ class ProductVariantBulkCreate(BaseMutation):ChannelContext(node=instance, channel_slug=None) for instance in instances]+ update_product_search_document(product)+transaction.on_commit(lambda: [info.context.plugins.product_variant_created(instance.node)@@ -614,8 +620,9 @@ 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.default_variant = product.variants.first()- product.save(update_fields=["default_variant"])+ product.save(update_fields=["default_variant", "search_document"])return responsediff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.pyindex 91f1660af6..ad13c3715c 100644--- a/saleor/graphql/product/filters.py+++ b/saleor/graphql/product/filters.py@@ -4,8 +4,7 @@ from typing import Dict, Iterable, List, Optionalimport django_filtersimport graphene-from django.contrib.postgres.search import SearchQuery, SearchRank-from django.db.models import Exists, F, FloatField, OuterRef, Q, Subquery, Sum+from django.db.models import Exists, FloatField, OuterRef, Q, Subquery, Sumfrom django.db.models.expressions import ExpressionWrapperfrom django.db.models.fields import IntegerFieldfrom django.db.models.functions import Cast, Coalesce@@ -33,6 +32,7 @@ from ...product.models import (ProductVariant,ProductVariantChannelListing,)+from ...product.search import search_productsfrom ...warehouse.models import Allocation, Stock, Warehousefrom ..channel.filters import get_channel_slug_from_filter_datafrom ..core.filters import (@@ -458,34 +458,8 @@ def _filter_stock_availability(qs, _, value, channel_slug):return qs-def product_search(qs, phrase):- """Return matching products for storefront views.-- Name and description is matched using search vector.-- Args:- qs (ProductsQueryset): searched data set- phrase (str): searched phrase-- """- query = SearchQuery(phrase, config="english")- vector = F("search_vector")- ft_in_description_or_name = Q(search_vector=query)-- variants = ProductVariant.objects.filter(sku=phrase).values("id")- ft_by_sku = Q(Exists(variants.filter(product_id=OuterRef("pk"))))-- return (- qs.annotate(rank=SearchRank(vector, query))- .filter((ft_in_description_or_name | ft_by_sku))- .order_by("-rank", "id")- )--def filter_search(qs, _, value):- if value:- qs = product_search(qs, value)- return qs+ return search_products(qs, value)def _filter_collections_is_published(qs, _, value, channel_slug):diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.pyindex 970aa6a69f..e3ab1506d4 100644--- a/saleor/graphql/product/mutations/attributes.py+++ b/saleor/graphql/product/mutations/attributes.py@@ -11,6 +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_documentfrom ...attribute.mutations import (BaseReorderAttributesMutation,BaseReorderAttributeValuesMutation,@@ -343,6 +344,8 @@ 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())+return cls(product_type=product_type)diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex 75160a8be4..4c3c0d7769 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -21,6 +21,10 @@ from ....order import models as order_modelsfrom ....order.tasks import recalculate_orders_taskfrom ....product import ProductMediaTypes, modelsfrom ....product.error_codes import CollectionErrorCode, ProductErrorCode+from ....product.search import (+ update_product_search_document,+ update_products_search_document,+)from ....product.tasks import (update_product_discounted_price_task,update_products_discounted_prices_of_catalogues_task,@@ -653,6 +657,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)info.context.plugins.product_created(product)@classmethod@@ -694,6 +699,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)info.context.plugins.product_updated(product)@@ -992,6 +998,7 @@ class ProductVariantCreate(ModelMutation):AttributeAssignmentMixin.save(instance, attributes)generate_and_set_variant_name(instance, cleaned_input.get("sku"))+ update_product_search_document(instance.product)event_to_call = (info.context.plugins.product_variant_createdif new_variant@@ -1075,6 +1082,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)# if the product default variant has been removed set the new oneif not product.default_variant:product.default_variant = product.variants.first()@@ -1263,6 +1271,15 @@ class ProductTypeUpdate(ProductTypeCreate):update_variants_names.delay(instance.pk, variant_attr_ids)super().save(info, instance, cleaned_input)+ @classmethod+ def post_save_action(cls, info, instance, cleaned_input):+ if (+ "product_attributes" in cleaned_input+ or "variant_attributes" in cleaned_input+ ):+ products = models.Product.objects.filter(product_type=instance)+ update_products_search_document(products)+class ProductTypeDelete(ModelDeleteMutation):class Arguments:diff --git a/saleor/graphql/product/sorters.py b/saleor/graphql/product/sorters.pyindex 317d9c5fe9..05e6361d27 100644--- a/saleor/graphql/product/sorters.py+++ b/saleor/graphql/product/sorters.py@@ -14,7 +14,6 @@ from django.db.models import ()from django.db.models.expressions import Windowfrom django.db.models.functions import Coalesce, DenseRank-from graphql.error import GraphQLErrorfrom ...product.models import (Category,@@ -22,6 +21,7 @@ from ...product.models import (Product,ProductChannelListing,)+from ..core.descriptions import DEPRECATED_IN_3X_INPUTfrom ..core.types import ChannelSortInputObjectType, SortInputObjectType@@ -123,7 +123,7 @@ class CollectionSortingInput(ChannelSortInputObjectType):class ProductOrderField(graphene.Enum):NAME = ["name", "slug"]- RANK = ["rank", "id"]+ RANK = ["name", "slug"]PRICE = ["min_variants_price_amount", "name", "slug"]MINIMAL_PRICE = ["discounted_price_amount", "name", "slug"]DATE = ["updated_at", "name", "slug"]@@ -141,9 +141,7 @@ class ProductOrderField(graphene.Enum):"collection. Note: ""This option is available only for the `Collection.products` query."),- ProductOrderField.RANK.name: (- "rank. Note: This option is available only with the `search` filter."- ),+ ProductOrderField.RANK.name: (f"rank. {DEPRECATED_IN_3X_INPUT}"),ProductOrderField.NAME.name: "name.",ProductOrderField.PRICE.name: "price.",ProductOrderField.TYPE.name: "type.",@@ -212,12 +210,6 @@ class ProductOrderField(graphene.Enum):))- @staticmethod- def qs_with_rank(queryset: QuerySet, **_kwargs) -> QuerySet:- if "rank" in queryset.query.annotations.keys():- return queryset- raise GraphQLError("Sorting by Rank is available only with searching.")-class ProductOrder(ChannelSortInputObjectType):attribute_id = graphene.Argument(diff --git a/saleor/graphql/product/tests/test_attributes.py b/saleor/graphql/product/tests/test_attributes.pyindex 1d41057a04..88cf9228eb 100644--- a/saleor/graphql/product/tests/test_attributes.py+++ b/saleor/graphql/product/tests/test_attributes.py@@ -13,7 +13,7 @@ from ....attribute.models import (from ....attribute.utils import associate_attribute_values_to_instancefrom ....product import ProductTypeKindfrom ....product.error_codes import ProductErrorCode-from ....product.models import ProductType+from ....product.models import Product, ProductTypefrom ...attribute.enums import AttributeTypeEnumfrom ...core.utils import snake_to_camel_casefrom ...tests.utils import get_graphql_content@@ -980,14 +980,27 @@ def test_unassign_attributes_from_product_type(staff_api_client,permission_manage_product_types_and_attributes,product_type_attribute_list,+ category,):product_type = ProductType.objects.create(name="Type", kind=ProductTypeKind.NORMAL)product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)+ product = Product.objects.create(+ name="Test product",+ slug="test-product-11",+ product_type=product_type,+ category=category,+ )variant_attribute, *product_attributes = product_type_attribute_listproduct_type.product_attributes.add(*product_attributes)product_type.variant_attributes.add(variant_attribute)+ attribute = product_attributes[1]+ product_attr_value = AttributeValue.objects.create(+ attribute=attribute, name="Test value", slug="test-value"+ )+ associate_attribute_values_to_instance(product, attribute, product_attr_value)+remaining_attribute_global_id = graphene.Node.to_global_id("Attribute", product_attributes[1].pk)@@ -1018,6 +1031,10 @@ 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 5f06438883..2bcb609eaf 100644--- a/saleor/graphql/product/tests/test_bulk_delete.py+++ b/saleor/graphql/product/tests/test_bulk_delete.py@@ -832,9 +832,16 @@ def test_delete_product_variants():query = PRODUCT_VARIANT_BULK_DELETE_MUTATION+ product = product_variant_list[0].product++ variant = product.variants.get(sku="123")+ variant.sku = "abcd"+ variant.save(update_fields=["sku"])+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": [@@ -857,6 +864,10 @@ 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 4a14791014..b65771d9c1 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -23,7 +23,8 @@ from ....attribute import AttributeInputType, AttributeTypefrom ....attribute.models import Attribute, AttributeValuefrom ....attribute.utils import associate_attribute_values_to_instancefrom ....core.taxes import TaxType-from ....core.units import WeightUnits+from ....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@@ -40,6 +41,7 @@ from ....product.models import (ProductVariant,ProductVariantChannelListing,)+from ....product.search import prepare_product_search_document_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@@ -2275,6 +2277,10 @@ def test_products_query_with_filter_category_and_search(second_product.save()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"])+category_id = graphene.Node.to_global_id("Category", category.id)variables = {"filter": {"categories": [category_id], "search": product.name}}staff_api_client.user.user_permissions.add(permission_manage_products)@@ -2404,6 +2410,10 @@ 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"])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)@@ -2487,6 +2497,311 @@ def test_products_query_with_filter_search_by_sku(assert products[0]["node"]["name"] == product_with_default_variant.name[email protected]("search_value", ["new", "NEW color", "Color"])+def test_products_query_with_filter_search_by_dropdown_attribute_value(+ search_value,+ query_products_with_filter,+ staff_api_client,+ product_list,+ permission_manage_products,+ channel_USD,+ color_attribute,+):+ # given+ product_with_dropdown_attr = product_list[1]++ product_type = product_with_dropdown_attr.product_type+ product_type.product_attributes.add(color_attribute)++ dropdown_attr_value = color_attribute.values.first()+ dropdown_attr_value.name = "New color"+ dropdown_attr_value.save(update_fields=["name"])++ associate_attribute_values_to_instance(+ product_with_dropdown_attr, color_attribute, dropdown_attr_value+ )++ product_with_dropdown_attr.refresh_from_db()++ product_with_dropdown_attr.search_document = prepare_product_search_document_value(+ product_with_dropdown_attr+ )+ product_with_dropdown_attr.save(update_fields=["search_document"])++ variables = {"filter": {"search": search_value}, "channel": channel_USD.slug}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)++ # then+ response = staff_api_client.post_graphql(query_products_with_filter, variables)+ content = get_graphql_content(response)+ products = content["data"]["products"]["edges"]++ assert len(products) == 1+ assert products[0]["node"]["id"] == graphene.Node.to_global_id(+ "Product", product_with_dropdown_attr.id+ )+ assert products[0]["node"]["name"] == product_with_dropdown_attr.name+++ "search_value", ["eco mode", "ECO Performance", "performa", "mod"]+)+def test_products_query_with_filter_search_by_multiselect_attribute_value(+ search_value,+ query_products_with_filter,+ staff_api_client,+ product_list,+ permission_manage_products,+ channel_USD,+):+ # given+ product_with_multiselect_attr = product_list[2]++ 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"+ )++ product_type = product_with_multiselect_attr.product_type+ product_type.product_attributes.add(multiselect_attribute)++ associate_attribute_values_to_instance(+ product_with_multiselect_attr,+ multiselect_attribute,+ multiselect_attr_val_1,+ multiselect_attr_val_2,+ )++ 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.save(update_fields=["search_document"])++ variables = {"filter": {"search": search_value}, "channel": channel_USD.slug}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)++ # then+ response = staff_api_client.post_graphql(query_products_with_filter, variables)+ content = get_graphql_content(response)+ products = content["data"]["products"]["edges"]++ assert len(products) == 1+ assert products[0]["node"]["id"] == graphene.Node.to_global_id(+ "Product", product_with_multiselect_attr.id+ )+ assert products[0]["node"]["name"] == product_with_multiselect_attr.name++[email protected]("search_value", ["rich", "test rich", "RICH text"])+def test_products_query_with_filter_search_by_rich_text_attribute(+ search_value,+ query_products_with_filter,+ staff_api_client,+ product_list,+ permission_manage_products,+ channel_USD,+ rich_text_attribute,+):+ # given+ product_with_rich_text_attr = product_list[1]++ product_type = product_with_rich_text_attr.product_type+ product_type.product_attributes.add(rich_text_attribute)++ rich_text_value = rich_text_attribute.values.first()+ rich_text_value.rich_text = dummy_editorjs("Test rich text.")+ rich_text_value.save(update_fields=["rich_text"])++ associate_attribute_values_to_instance(+ product_with_rich_text_attr, rich_text_attribute, rich_text_value+ )++ 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+ )+ product_with_rich_text_attr.save(update_fields=["search_document"])++ variables = {"filter": {"search": search_value}, "channel": channel_USD.slug}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)++ # then+ response = staff_api_client.post_graphql(query_products_with_filter, variables)+ content = get_graphql_content(response)+ products = content["data"]["products"]["edges"]++ assert len(products) == 1+ assert products[0]["node"]["id"] == graphene.Node.to_global_id(+ "Product", product_with_rich_text_attr.id+ )+ assert products[0]["node"]["name"] == product_with_rich_text_attr.name++[email protected]("search_value", ["134", "134", "134 cm"])+def test_products_query_with_filter_search_by_numeric_attribute_value(+ search_value,+ query_products_with_filter,+ staff_api_client,+ product_list,+ permission_manage_products,+ channel_USD,+ numeric_attribute,+):+ # given+ product_with_numeric_attr = product_list[1]++ product_type = product_with_numeric_attr.product_type+ product_type.product_attributes.add(numeric_attribute)++ numeric_attribute.unit = MeasurementUnits.CM+ numeric_attribute.save(update_fields=["unit"])++ numeric_attr_value = numeric_attribute.values.first()+ numeric_attr_value.name = "134"+ numeric_attr_value.save(update_fields=["name"])++ associate_attribute_values_to_instance(+ product_with_numeric_attr, numeric_attribute, numeric_attr_value+ )++ product_with_numeric_attr.refresh_from_db()++ product_with_numeric_attr.search_document = prepare_product_search_document_value(+ product_with_numeric_attr+ )+ product_with_numeric_attr.save(update_fields=["search_document"])++ variables = {"filter": {"search": search_value}, "channel": channel_USD.slug}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)++ # then+ response = staff_api_client.post_graphql(query_products_with_filter, variables)+ content = get_graphql_content(response)+ products = content["data"]["products"]["edges"]++ assert len(products) == 1+ assert products[0]["node"]["id"] == graphene.Node.to_global_id(+ "Product", product_with_numeric_attr.id+ )+ assert products[0]["node"]["name"] == product_with_numeric_attr.name++[email protected]("search_value", ["2020", "2020 10 10", "2020-10-10"])+def test_products_query_with_filter_search_by_date_attribute_value(+ search_value,+ query_products_with_filter,+ staff_api_client,+ product_list,+ permission_manage_products,+ channel_USD,+ date_attribute,+):+ # given+ product_with_date_attr = product_list[2]++ product_type = product_with_date_attr.product_type+ product_type.product_attributes.add(date_attribute)++ date_attr_value = date_attribute.values.first()+ date_attr_value.date_time = datetime(2020, 10, 10, tzinfo=pytz.utc)+ date_attr_value.save(update_fields=["date_time"])++ associate_attribute_values_to_instance(+ product_with_date_attr, date_attribute, date_attr_value+ )++ product_with_date_attr.refresh_from_db()++ product_with_date_attr.search_document = prepare_product_search_document_value(+ product_with_date_attr+ )+ product_with_date_attr.save(update_fields=["search_document"])++ variables = {"filter": {"search": search_value}, "channel": channel_USD.slug}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)++ # then+ response = staff_api_client.post_graphql(query_products_with_filter, variables)+ content = get_graphql_content(response)+ products = content["data"]["products"]["edges"]++ assert len(products) == 1+ assert products[0]["node"]["id"] == graphene.Node.to_global_id(+ "Product", product_with_date_attr.id+ )+ assert products[0]["node"]["name"] == product_with_date_attr.name++[email protected]("search_value", ["2020", "2020 10 10", "2020-10-10", "22:20"])+def test_products_query_with_filter_search_by_date_time_attribute_value(+ search_value,+ query_products_with_filter,+ staff_api_client,+ product_list,+ permission_manage_products,+ channel_USD,+ date_time_attribute,+):+ # given+ product_with_date_time_attr = product_list[0]++ product_type = product_with_date_time_attr.product_type+ product_type.product_attributes.add(date_time_attribute)++ date_time_attr_value = date_time_attribute.values.first()+ date_time_attr_value.date_time = datetime(2020, 10, 10, 22, 20, tzinfo=pytz.utc)+ date_time_attr_value.save(update_fields=["date_time"])++ associate_attribute_values_to_instance(+ product_with_date_time_attr, date_time_attribute, date_time_attr_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+ )+ product_with_date_time_attr.save(update_fields=["search_document"])++ variables = {"filter": {"search": search_value}, "channel": channel_USD.slug}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)++ # then+ response = staff_api_client.post_graphql(query_products_with_filter, variables)+ content = get_graphql_content(response)+ products = content["data"]["products"]["edges"]++ assert len(products) == 1+ assert products[0]["node"]["id"] == graphene.Node.to_global_id(+ "Product", product_with_date_time_attr.id+ )+ assert products[0]["node"]["name"] == product_with_date_time_attr.name++def test_products_query_with_is_published_filter_variants_without_prices(query_products_with_filter,staff_api_client,@@ -3591,7 +3906,10 @@ 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()@@ -3642,6 +3960,7 @@ 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(@@ -3651,7 +3970,6 @@ def test_create_product_with_rich_text_attribute(rich_text_attribute,color_attribute,permission_manage_products,- product,):query = CREATE_PRODUCT_MUTATION@@ -3665,7 +3983,8 @@ def test_create_product_with_rich_text_attribute(rich_text_attribute_id = graphene.Node.to_global_id("Attribute", rich_text_attribute.id)- rich_text = json.dumps(dummy_editorjs("test product" * 5))+ rich_text_value = dummy_editorjs("test product" * 5)+ rich_text = json.dumps(rich_text_value)# test creating root productvariables = {@@ -3718,6 +4037,13 @@ 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+ )@freeze_time(datetime(2020, 5, 5, 5, 5, 5, tzinfo=pytz.utc))@@ -3727,7 +4053,6 @@ def test_create_product_with_date_time_attribute(date_time_attribute,color_attribute,permission_manage_products,- product,):query = CREATE_PRODUCT_MUTATION@@ -3782,6 +4107,10 @@ 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))@@ -3791,7 +4120,6 @@ def test_create_product_with_date_attribute(date_attribute,color_attribute,permission_manage_products,- product,):query = CREATE_PRODUCT_MUTATION@@ -3844,6 +4172,10 @@ 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_with_boolean_attribute(@@ -3948,24 +4280,27 @@ def test_search_product_by_description(user_api_client, product_list, channel_USdef test_search_product_by_description_and_name(user_api_client, product_list, product, channel_USD, category, product_type):- product.description_plaintext = "red big red product"- product.save()+ product.description_plaintext = "new big new product"product_2 = product_list[1]- product_2.name = "red product"- product_2.save()+ product_2.name = "new product"product_1 = product_list[0]- product_1.description_plaintext = "some red product"- product_1.save()+ product_1.description_plaintext = "some new product"product_3 = product_list[2]product_3.description_plaintext = "desc without searched word"- product_3.save()++ product_list.append(product)+ for prod in product_list:+ prod.search_document = prepare_product_search_document_value(prod)++ Product.objects.bulk_update(+ product_list, ["search_document", "name", "description_plaintext"]+ )variables = {"filters": {- "search": "red",+ "search": "new",},- "sortBy": {"field": "RANK", "direction": "DESC"},"channel": channel_USD.slug,}response = user_api_client.post_graphql(SEARCH_PRODUCTS_QUERY, variables)@@ -3973,89 +4308,49 @@ def test_search_product_by_description_and_name(data = content["data"]["products"]["edges"]assert len(data) == 3- assert data[0]["node"]["name"] == product_2.name- assert data[1]["node"]["name"] == product.name- assert data[2]["node"]["name"] == product_1.name+ assert {node["node"]["name"] for node in data} == {+ product.name,+ product_1.name,+ product_2.name,+ }def test_sort_product_by_rank_without_search(user_api_client, product_list, product, channel_USD, category, product_type):- product.description_plaintext = "red big red product"- product.save()-- product_2 = product_list[1]- product_2.name = "red product"- product_2.save()- product_1 = product_list[0]- product_1.description_plaintext = "some red product"- product_1.save()-- variables = {- "sortBy": {"field": "RANK", "direction": "DESC"},- "channel": channel_USD.slug,- }- response = user_api_client.post_graphql(SEARCH_PRODUCTS_QUERY, variables)- data = get_graphql_content(response, ignore_errors=True)- assert len(data["errors"]) == 1- assert (- data["errors"][0]["message"]- == "Sorting by Rank is available only with searching."- )--[email protected]("search_value", ["", " ", None])-def test_sort_product_by_rank_with_empty_search_value(- search_value,- user_api_client,- product_list,- product,- channel_USD,- category,- product_type,-):- product.description_plaintext = "red big red product"- product.save()-- product_2 = product_list[1]- product_2.name = "red product"- product_2.save()- product_1 = product_list[0]- product_1.description_plaintext = "some red product"- product_1.save()+ product_count = Product.objects.count()variables = {- "filters": {- "search": search_value,- },"sortBy": {"field": "RANK", "direction": "DESC"},"channel": channel_USD.slug,}response = user_api_client.post_graphql(SEARCH_PRODUCTS_QUERY, variables)- data = get_graphql_content(response, ignore_errors=True)- assert len(data["errors"]) == 1- assert (- data["errors"][0]["message"]- == "Sorting by Rank is available only with searching."- )+ content = get_graphql_content(response)+ data = content["data"]["products"]["edges"]+ assert len(data) == product_countdef test_search_product_by_description_and_name_without_sort_by(user_api_client, product_list, product, channel_USD, category, product_type):- product.description_plaintext = "red big red product"- product.save()+ product.description_plaintext = "new big new product"product_2 = product_list[1]- product_2.name = "red product"- product_2.save()+ product_2.name = "new product"product_1 = product_list[0]- product_1.description_plaintext = "some red product"- product_1.save()+ product_1.description_plaintext = "some new product"++ product_list.append(product)+ for prod in product_list:+ prod.search_document = prepare_product_search_document_value(prod)++ Product.objects.bulk_update(+ product_list, ["search_document", "name", "description_plaintext"]+ )variables = {"filters": {- "search": "red",+ "search": "new",},"channel": channel_USD.slug,}@@ -4063,27 +4358,35 @@ def test_search_product_by_description_and_name_without_sort_by(content = get_graphql_content(response)data = content["data"]["products"]["edges"]- assert data[0]["node"]["name"] == product_2.name- assert data[1]["node"]["name"] == product.name- assert data[2]["node"]["name"] == product_1.name+ assert len(data) == 3+ assert {node["node"]["name"] for node in data} == {+ product.name,+ product_1.name,+ product_2.name,+ }def test_search_product_by_description_and_name_and_use_cursor(user_api_client, product_list, product, channel_USD, category, product_type):- product.description_plaintext = "red big red product"- product.save()+ product.description_plaintext = "new big new product"product_2 = product_list[1]- product_2.name = "red product"- product_2.save()+ product_2.name = "new product"product_1 = product_list[0]- product_1.description_plaintext = "some red product"- product_1.save()+ product_1.description_plaintext = "some new product"++ product_list.append(product)+ for prod in product_list:+ prod.search_document = prepare_product_search_document_value(prod)++ Product.objects.bulk_update(+ product_list, ["search_document", "name", "description_plaintext"]+ )variables = {"filters": {- "search": "red",+ "search": "new",},"channel": channel_USD.slug,}@@ -4093,7 +4396,7 @@ def test_search_product_by_description_and_name_and_use_cursor(variables = {"filters": {- "search": "red",+ "search": "new",},"after": cursor,"channel": channel_USD.slug,@@ -4102,8 +4405,8 @@ def test_search_product_by_description_and_name_and_use_cursor(content = get_graphql_content(response)data = content["data"]["products"]["edges"]- assert data[0]["node"]["name"] == product.name- assert data[1]["node"]["name"] == product_1.name+ 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")@@ -5170,6 +5473,7 @@ def test_reorder_variants(content = get_graphql_content(response)data = content["data"]["productVariantReorder"]assert not data["errors"]+ product_with_two_variants.refresh_from_db()assert list(product_with_two_variants.variants.all()) == new_variants@@ -5695,6 +5999,7 @@ def test_update_product()attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.pk)+ attr_value = "Rainbow"variables = {"productId": product_id,@@ -5705,7 +6010,7 @@ def test_update_product("description": other_description_json,"chargeTaxes": product_charge_taxes,"taxCode": product_tax_rate,- "attributes": [{"id": attribute_id, "values": ["Rainbow"]}],+ "attributes": [{"id": attribute_id, "values": [attr_value]}],},}@@ -5733,6 +6038,10 @@ 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(@@ -6044,6 +6353,10 @@ 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(@@ -8274,7 +8587,10 @@ mutation updateProductType(def test_product_type_update_mutation(- staff_api_client, product_type, permission_manage_product_types_and_attributes+ staff_api_client,+ product_type,+ product,+ permission_manage_product_types_and_attributes,):query = PRODUCT_TYPE_UPDATE_MUTATIONproduct_type_name = "test type updated"@@ -8283,6 +8599,9 @@ 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 = []@@ -8310,6 +8629,10 @@ 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,@@ -8388,7 +8711,9 @@ UPDATE_PRODUCT_TYPE_SLUG_MUTATION = """(None, "", "Slug value cannot be blank."),],)+@patch("saleor.product.search.update_products_search_document")def test_update_product_type_slug(+ update_products_search_document_mock,staff_api_client,product_type,permission_manage_product_types_and_attributes,@@ -8412,6 +8737,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()else:assert errorsassert errors[0]["field"] == "slug"@@ -8637,6 +8963,8 @@ def test_product_type_delete_mutation_deletes_also_images(with pytest.raises(product_type._meta.model.DoesNotExist):product_type.refresh_from_db()delete_versatile_image_mock.assert_called_once_with(media_obj.image.name)+ with pytest.raises(product_with_image._meta.model.DoesNotExist):+ product_with_image.refresh_from_db()@patch("saleor.attribute.signals.delete_from_storage_task.delay")@@ -8674,6 +9002,10 @@ def test_product_type_delete_with_file_attributes(assert set(data.args[0] for data in delete_from_storage_task_mock.call_args_list) == {v.file_url for v in values}+ with pytest.raises(+ product_with_variant_with_file_attribute._meta.model.DoesNotExist+ ):+ product_with_variant_with_file_attribute.refresh_from_db()def test_product_type_delete_mutation_variants_in_draft_order(diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.pyindex a6f946d9a7..125cc7f211 100644--- a/saleor/graphql/product/tests/test_variant.py+++ b/saleor/graphql/product/tests/test_variant.py@@ -605,6 +605,10 @@ 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")@@ -1877,9 +1881,10 @@ def test_product_variant_update_with_new_attributes(variant_id = graphene.Node.to_global_id("ProductVariant", product.variants.first().pk)+ attr_value = "XXXL"variables = {- "attributes": [{"id": size_attribute_id, "values": ["XXXL"]}],+ "attributes": [{"id": size_attribute_id, "values": [attr_value]}],"id": variant_id,"sku": "21599567","trackInventory": True,@@ -1897,6 +1902,10 @@ 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")@@ -1942,13 +1951,14 @@ def test_update_product_variant(attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)sku = "test sku"quantity_limit_per_customer = 5+ attr_value = "S"variables = {"id": variant_id,"sku": sku,"trackInventory": True,"quantityLimitPerCustomer": quantity_limit_per_customer,- "attributes": [{"id": attribute_id, "values": ["S"]}],+ "attributes": [{"id": attribute_id, "values": [attr_value]}],}response = staff_api_client.post_graphql(@@ -1967,6 +1977,10 @@ 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@@ -2072,16 +2086,20 @@ def test_update_product_variant_change_sku():variant = product.variants.first()variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)- variables = {"id": variant_id, "sku": "n3wSKU"}+ sku = "n3wSKU"+ variables = {"id": variant_id, "sku": sku}response = staff_api_client.post_graphql(QUERY_UPDATE_VARIANT_SKU, variables, permissions=[permission_manage_products])variant.refresh_from_db()content = get_graphql_content(response)data = content["data"]["productVariantUpdate"]["productVariant"]- assert data["sku"] == "n3wSKU"+ assert data["sku"] == skuvariant.refresh_from_db()- assert variant.sku == "n3wSKU"+ 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(@@ -3244,6 +3262,7 @@ def test_delete_variant(query = DELETE_VARIANT_MUTATIONvariant = product.variants.first()variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ variant_sku = variant.skuvariables = {"id": variant_id}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_products]@@ -3253,10 +3272,13 @@ def test_delete_variant(data = content["data"]["productVariantDelete"]product_variant_deleted_webhook_mock.assert_called_once_with(variant)- assert data["productVariant"]["sku"] == variant.sku+ assert data["productVariant"]["sku"] == variant_skuwith 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(@@ -4032,6 +4054,9 @@ 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(@@ -4080,6 +4105,9 @@ 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(@@ -4127,6 +4155,9 @@ 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(@@ -4145,7 +4176,10 @@ def test_product_variant_bulk_create_empty_attribute(data = content["data"]["productVariantBulkCreate"]assert not data["errors"]assert data["count"] == 1+ product.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/utils/sorting.py b/saleor/graphql/utils/sorting.pyindex ec1c92ed94..8ee24327c3 100644--- a/saleor/graphql/utils/sorting.py+++ b/saleor/graphql/utils/sorting.py@@ -27,7 +27,6 @@ def _sort_queryset_by_attribute(queryset, sorting_attribute, sorting_direction):def sort_queryset_for_connection(iterable, args):sort_by = args.get("sort_by")reversed = True if "last" in args else False- query = getattr(iterable, "query", None)if sort_by:iterable = sort_queryset(queryset=iterable,@@ -36,8 +35,6 @@ def sort_queryset_for_connection(iterable, args):channel_slug=args.get("channel")or get_default_channel_slug_or_graphql_error(),)- elif query and "-rank" in query.order_by:- return iterable, {"field": ["rank", "id"], "direction": "-"}else:iterable, sort_by = sort_queryset_by_default(queryset=iterable, reversed=reversed@@ -89,15 +86,8 @@ def sort_queryset(if custom_sort_by:queryset = custom_sort_by(queryset, channel_slug=channel_slug)- if sorting_field_name == "rank":- # In rank sorting ID is sorted in opposite direction to rank- if sorting_direction == "-":- sorting_list = ["-rank", "id"]- else:- sorting_list = ["rank", "-id"]- else:- sorting_field_value = sorting_fields.value- sorting_list = [f"{sorting_direction}{field}" for field in sorting_field_value]+ sorting_field_value = sorting_fields.value+ sorting_list = [f"{sorting_direction}{field}" for field in sorting_field_value]return queryset.order_by(*sorting_list)diff --git a/saleor/order/migrations/0123_update_order_search_document.py b/saleor/order/migrations/0123_update_order_search_document.pynew file mode 100644index 0000000000..3ee9d3c223--- /dev/null+++ b/saleor/order/migrations/0123_update_order_search_document.py@@ -0,0 +1,25 @@+# Generated by Django 3.2.6 on 2021-12-27 09:45++from django.db import migrations++from ...core.search_tasks import set_order_search_document_values+++def update_order_search_document_values(apps, _schema_editor):+ Order = apps.get_model("order", "Order")+ total_count = Order.objects.filter(search_document="").count()+ set_order_search_document_values.delay(total_count, 0)+++class Migration(migrations.Migration):++ dependencies = [+ ("order", "0122_merge_20211220_1641"),+ ("payment", "0030_auto_20210908_1346"),+ ]++ operations = [+ migrations.RunPython(+ update_order_search_document_values, reverse_code=migrations.RunPython.noop+ ),+ ]diff --git a/saleor/product/migrations/0156_product_search_document.py b/saleor/product/migrations/0156_product_search_document.pynew file mode 100644index 0000000000..da4e693266--- /dev/null+++ b/saleor/product/migrations/0156_product_search_document.py@@ -0,0 +1,47 @@+# Generated by Django 3.2.6 on 2021-11-30 08:19++import django.contrib.postgres.indexes+from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("product", "0155_merge_20211208_1108"),+ ]++ operations = [+ migrations.AddField(+ model_name="product",+ name="search_document",+ field=models.TextField(blank=True, default=""),+ ),+ migrations.AddIndex(+ model_name="product",+ index=django.contrib.postgres.indexes.GinIndex(+ fields=["search_document"],+ name="product_search_gin",+ opclasses=["gin_trgm_ops"],+ ),+ ),+ migrations.RemoveIndex(+ model_name="product",+ name="product_pro_search__e78047_gin",+ ),+ migrations.RemoveField(+ model_name="product",+ name="search_vector",+ ),+ migrations.RunSQL(+ """+ DROP TRIGGER IF EXISTS title_vector_update+ ON product_product+ """+ ),+ migrations.RunSQL(+ """+ DROP TRIGGER IF EXISTS tsvectorupdate+ ON product_product+ """+ ),+ ]diff --git a/saleor/product/migrations/0157_update_product_search_document.py b/saleor/product/migrations/0157_update_product_search_document.pynew file mode 100644index 0000000000..bcc6c78c90--- /dev/null+++ b/saleor/product/migrations/0157_update_product_search_document.py@@ -0,0 +1,25 @@+# Generated by Django 3.2.6 on 2021-12-27 09:36++from django.db import migrations++from ...core.search_tasks import set_product_search_document_values+++def update_product_search_document_values(apps, _schema_editor):+ Product = apps.get_model("product", "Product")+ total_count = Product.objects.filter(search_document="").count()+ set_product_search_document_values.delay(total_count, 0)+++class Migration(migrations.Migration):++ dependencies = [+ ("product", "0156_product_search_document"),+ ]++ 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 617ebde653..a9547b57b8 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -391,7 +391,7 @@ class Product(SeoModel, ModelWithMetadata):slug = models.SlugField(max_length=255, unique=True, allow_unicode=True)description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)description_plaintext = TextField(blank=True)- search_vector = SearchVectorField(null=True, blank=True)+ search_document = models.TextField(blank=True, default="")category = models.ForeignKey(Category,@@ -426,7 +426,14 @@ class Product(SeoModel, ModelWithMetadata):permissions = ((ProductPermissions.MANAGE_PRODUCTS.codename, "Manage products."),)- indexes = [GinIndex(fields=["search_vector"])]+ indexes = [+ GinIndex(+ name="product_search_gin",+ # `opclasses` and `fields` should be the same length+ fields=["search_document"],+ opclasses=["gin_trgm_ops"],+ ),+ ]indexes.extend(ModelWithMetadata.Meta.indexes)def __iter__(self):diff --git a/saleor/product/search.py b/saleor/product/search.pynew file mode 100644index 0000000000..be35c2e8df--- /dev/null+++ b/saleor/product/search.py@@ -0,0 +1,122 @@+from typing import TYPE_CHECKING, Union++from django.db.models import Q, prefetch_related_objects++from ..attribute import AttributeInputType+from ..core.utils.editorjs import clean_editor_js+from .models import Product++if TYPE_CHECKING:+ from django.db.models import QuerySet++ from ..attribute.models import AssignedProductAttribute, AssignedVariantAttribute++ASSIGNED_ATTRIBUTE_TYPE = Union["AssignedProductAttribute", "AssignedVariantAttribute"]++PRODUCT_SEARCH_FIELDS = ["name", "description_plaintext"]+PRODUCT_FIELDS_TO_PREFETCH = [+ "variants__attributes__values",+ "variants__attributes__assignment__attribute",+ "attributes__values",+ "attributes__assignment__attribute",+]+++def update_products_search_document(products: "QuerySet"):+ products = products.prefetch_related(*PRODUCT_FIELDS_TO_PREFETCH)+ for product in products:+ product.search_document = prepare_product_search_document_value(+ product, already_prefetched=True+ )++ Product.objects.bulk_update(products, ["search_document"])+++def update_product_search_document(product: "Product"):+ product.search_document = prepare_product_search_document_value(product)+ product.save(update_fields=["search_document"])+++def prepare_product_search_document_value(+ product: "Product", *, already_prefetched=False+):+ 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(+ 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 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(+ variant.attributes.all()+ )+ if variant_attribute_data:+ variants_data += variant_attribute_data++ return variants_data.lower()+++def generate_attributes_search_document_value(+ assigned_attributes: "QuerySet",+):+ """Prepare `search_document` value for assigned attributes.++ Method should received assigned attributes with prefetched `values`+ and `assignment__attribute`.+ """+ attribute_data = ""+ for assigned_attribute in assigned_attributes:+ attribute = assigned_attribute.assignment.attribute++ input_type = attribute.input_type+ values = assigned_attribute.values.all()+ values_list = []+ if input_type in [AttributeInputType.DROPDOWN, AttributeInputType.MULTISELECT]:+ values_list = [value.name for value in values]+ elif input_type == AttributeInputType.RICH_TEXT:+ values_list = [+ clean_editor_js(value.rich_text, to_string=True) for value in values+ ]+ elif input_type == AttributeInputType.NUMERIC:+ unit = attribute.unit+ values_list = [value.name + unit for value in values]+ elif input_type in [AttributeInputType.DATE, AttributeInputType.DATE_TIME]:+ values_list = [value.date_time.isoformat() for value in values]++ if values_list:+ values_data = "\n".join(values_list)+ attribute_data += values_data + "\n"+ return attribute_data.lower()+++def search_products(qs, value):+ if value:+ lookup = Q()+ for val in value.split():+ lookup &= Q(search_document__ilike=val)+ qs = qs.filter(lookup)+ return qsdiff --git a/saleor/product/tests/test_product_search.py b/saleor/product/tests/test_product_search.pynew file mode 100644index 0000000000..8f220b1d43--- /dev/null+++ b/saleor/product/tests/test_product_search.py@@ -0,0 +1,178 @@+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,+)+++def test_update_product_search_document(product_type, category):+ # given+ name = "Test product"+ description = "Test description"+ product = Product.objects.create(+ name=name,+ slug="test-product-111",+ product_type=product_type,+ category=category,+ description_plaintext=description,+ )+ assert not product.search_document++ # when+ update_product_search_document(product)++ # then+ assert f"{name}\n{description}\n".lower() in product.search_document+++def test_update_products_search_document(product_list):+ # given+ for product in product_list:+ product.search_document = ""+ Product.objects.bulk_update(product_list, ["search_document"])++ # when+ update_products_search_document(Product.objects.all())++ # then+ for 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_valuediff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex f18cd3fe6e..17ca3165a3 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -102,6 +102,7 @@ from ..product.models import (ProductVariantTranslation,VariantMedia,)+from ..product.search import prepare_product_search_document_valuefrom ..product.tests.utils import create_imagefrom ..shipping.models import (ShippingMethod,@@ -1467,7 +1468,9 @@ def product_type_attribute_list() -> List[Attribute]:return list(Attribute.objects.bulk_create([- Attribute(slug="size", name="Size", type=AttributeType.PRODUCT_TYPE),+ Attribute(+ slug="height", name="Height", type=AttributeType.PRODUCT_TYPE+ ),Attribute(slug="weight", name="Weight", type=AttributeType.PRODUCT_TYPE),@@ -1732,6 +1735,7 @@ def product(product_type, category, warehouse, channel_USD):Stock.objects.create(warehouse=warehouse, product_variant=variant, quantity=10)associate_attribute_values_to_instance(variant, variant_attr, variant_attr_value)+return product@@ -1973,6 +1977,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"])return product@@ -2186,6 +2192,10 @@ def product_with_default_variant(currency=channel_USD.currency_code,)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"])+return product@@ -2587,6 +2597,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.objects.bulk_update(products, ["search_document"])return products