Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Improve page search (#18287)
Iga Karbowiak2c9e8869e024
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9c46d105dd..04614f4462 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,5 +11,6 @@ All notable, unreleased changes to this project will be documented in this file.### Webhooks### Other changes+- Improved page search with search vectors. Pages can now be searched by slug, title, content, attribute values, and page type information.### Deprecationsdiff --git a/saleor/core/context.py b/saleor/core/context.pynew file mode 100644index 0000000000..d62496e6c6--- /dev/null+++ b/saleor/core/context.py@@ -0,0 +1,18 @@+from promise import Promise+++def with_promise_context(func):+ """Execute function within Promise context.++ Allow to use dataloaders inside the function.+ """++ def wrapper(*args, **kwargs):+ def promise_executor(_):+ return func(*args, **kwargs)++ # Create promise chain+ promise = Promise.resolve(None).then(promise_executor)+ return promise.get()++ return wrapperdiff --git a/saleor/graphql/attribute/bulk_mutations.py b/saleor/graphql/attribute/bulk_mutations.pyindex 4f788ff2e7..ce1d0e5ff9 100644--- a/saleor/graphql/attribute/bulk_mutations.py+++ b/saleor/graphql/attribute/bulk_mutations.py@@ -6,6 +6,9 @@ from ...attribute import modelsfrom ...attribute.lock_objects import attribute_value_qs_select_for_updatefrom ...permission.enums import PageTypePermissionsfrom ...product import models as product_models+from ...product.utils.search_helpers import (+ mark_products_search_vector_as_dirty_in_batches,+)from ...webhook.event_types import WebhookEventAsyncTypefrom ...webhook.utils import get_webhooks_for_eventfrom ..core import ResolveInfo@@ -46,9 +49,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=ids)- product_models.Product.objects.filter(id__in=product_ids).update(- search_index_dirty=True- )+ mark_products_search_vector_as_dirty_in_batches(product_ids)return response@classmethod@@ -120,9 +121,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=ids)- product_models.Product.objects.filter(id__in=product_ids).update(- search_index_dirty=True- )+ mark_products_search_vector_as_dirty_in_batches(product_ids)return response@classmethoddiff --git a/saleor/graphql/attribute/mutations/attribute_bulk_update.py b/saleor/graphql/attribute/mutations/attribute_bulk_update.pyindex 7731547ed0..64f79a3859 100644--- a/saleor/graphql/attribute/mutations/attribute_bulk_update.py+++ b/saleor/graphql/attribute/mutations/attribute_bulk_update.py@@ -18,7 +18,11 @@ from ....attribute.lock_objects import (attribute_value_qs_select_for_update,)from ....core.tracing import traced_atomic_transaction+from ....page.utils import mark_pages_search_vector_as_dirty_in_batchesfrom ....permission.enums import PageTypePermissions, ProductTypePermissions+from ....product.utils.search_helpers import (+ mark_products_search_vector_as_dirty_in_batches,+)from ....webhook.utils import get_webhooks_for_eventfrom ...core import ResolveInfofrom ...core.context import ChannelContext@@ -44,6 +48,10 @@ from ..types import Attributefrom .attribute_bulk_create import DEPRECATED_ATTR_FIELDS, clean_valuesfrom .attribute_update import AttributeUpdateInputfrom .mixins import AttributeMixin+from .utils import (+ get_page_ids_to_search_index_update_for_attribute_values,+ get_product_ids_to_search_index_update_for_attribute_values,+)@dataclass@@ -688,6 +696,15 @@ class AttributeBulkUpdate(BaseMutation):delete_product_reference_types_lookup |= delete_product_refdelete_page_reference_types_lookup |= delete_page_ref+ product_ids_to_update = (+ get_product_ids_to_search_index_update_for_attribute_values(+ values_to_remove+ )+ )+ page_ids_to_update = get_page_ids_to_search_index_update_for_attribute_values(+ values_to_remove+ )+with transaction.atomic():models.Attribute.objects.bulk_update(attributes_to_update,@@ -719,7 +736,13 @@ class AttributeBulkUpdate(BaseMutation):)updated_attributes.extend(attributes_to_update)- return updated_attributes, values_to_remove, values_to_create+ return (+ updated_attributes,+ values_to_remove,+ values_to_create,+ product_ids_to_update,+ page_ids_to_update,+ )@classmethoddef _prepare_reference_types_for_saving(@@ -852,12 +875,18 @@ class AttributeBulkUpdate(BaseMutation):return AttributeBulkUpdate(count=0, results=results)# save all objects- attributes, values_to_remove, values_to_create = cls.save(- instances_data_with_errors_list- )+ (+ attributes,+ values_to_remove,+ values_to_create,+ product_ids_to_search_update,+ page_ids_to_search_update,+ ) = cls.save(instances_data_with_errors_list)# prepare and return dataresults = get_results(instances_data_with_errors_list)cls.post_save_actions(info, attributes, values_to_remove, values_to_create)+ mark_products_search_vector_as_dirty_in_batches(product_ids_to_search_update)+ mark_pages_search_vector_as_dirty_in_batches(page_ids_to_search_update)return AttributeBulkUpdate(count=len(attributes), results=results)diff --git a/saleor/graphql/attribute/mutations/attribute_delete.py b/saleor/graphql/attribute/mutations/attribute_delete.pyindex 881af1cb73..1f9af40baa 100644--- a/saleor/graphql/attribute/mutations/attribute_delete.py+++ b/saleor/graphql/attribute/mutations/attribute_delete.py@@ -1,9 +1,16 @@import graphenefrom django.db import transaction+from django.db.models import Exists, OuterReffrom ....attribute import models as modelsfrom ....attribute.lock_objects import attribute_value_qs_select_for_update+from ....page import models as page_models+from ....page.utils import mark_pages_search_vector_as_dirty_in_batchesfrom ....permission.enums import ProductTypePermissions+from ....product import models as product_models+from ....product.utils.search_helpers import (+ mark_products_search_vector_as_dirty_in_batches,+)from ....webhook.event_types import WebhookEventAsyncTypefrom ...core import ResolveInfofrom ...core.context import ChannelContext@@ -53,8 +60,9 @@ class AttributeDelete(ModelDeleteMutation, ModelWithExtRefMutation):):"""Perform a mutation that deletes a model instance."""instance = cls.get_instance(info, external_reference=external_reference, id=id)+ product_ids = cls.get_product_ids_to_search_index_update(instance)+ page_ids = cls.get_page_ids_to_search_index_update(instance)- cls.clean_instance(info, instance)db_id = instance.idwith transaction.atomic():# Lock the attribute values to prevent concurrent modifications@@ -68,4 +76,31 @@ class AttributeDelete(ModelDeleteMutation, ModelWithExtRefMutation):# ID so that the success response contains ID of the deleted object.instance.id = db_idcls.post_save_action(info, instance, None)+ mark_products_search_vector_as_dirty_in_batches(product_ids)+ mark_pages_search_vector_as_dirty_in_batches(page_ids)return cls.success_response(instance)++ @classmethod+ def get_product_ids_to_search_index_update(+ cls, instance: models.Attribute+ ) -> list[int]:+ product_types = product_models.ProductType.objects.filter(+ Exists(instance.attributevariant.filter(product_type_id=OuterRef("id")))+ | Exists(instance.attributeproduct.filter(product_type_id=OuterRef("id")))+ )+ product_ids = product_models.Product.objects.filter(+ Exists(product_types.filter(id=OuterRef("product_type_id")))+ ).values_list("id", flat=True)+ return list(product_ids)++ @classmethod+ def get_page_ids_to_search_index_update(+ cls, instance: models.Attribute+ ) -> list[int]:+ page_types = page_models.PageType.objects.filter(+ Exists(instance.attributepage.filter(page_type_id=OuterRef("id")))+ )+ page_ids = page_models.Page.objects.filter(+ Exists(page_types.filter(id=OuterRef("page_type_id")))+ ).values_list("id", flat=True)+ return list(page_ids)diff --git a/saleor/graphql/attribute/mutations/attribute_update.py b/saleor/graphql/attribute/mutations/attribute_update.pyindex 646f7675f2..cf872d5b71 100644--- a/saleor/graphql/attribute/mutations/attribute_update.py+++ b/saleor/graphql/attribute/mutations/attribute_update.py@@ -3,7 +3,11 @@ from django.core.exceptions import ValidationErrorfrom ....attribute import models as modelsfrom ....attribute.error_codes import AttributeErrorCode+from ....page.utils import mark_pages_search_vector_as_dirty_in_batchesfrom ....permission.enums import ProductTypePermissions+from ....product.utils.search_helpers import (+ mark_products_search_vector_as_dirty_in_batches,+)from ....webhook.event_types import WebhookEventAsyncTypefrom ...core import ResolveInfofrom ...core.context import ChannelContext@@ -18,6 +22,10 @@ from ..descriptions import AttributeDescriptions, AttributeValueDescriptionsfrom ..types import Attributefrom .attribute_create import AttributeValueInputfrom .mixins import REFERENCE_TYPES_LIMIT, AttributeMixin+from .utils import (+ get_page_ids_to_search_index_update_for_attribute_values,+ get_product_ids_to_search_index_update_for_attribute_values,+)class AttributeValueUpdateInput(AttributeValueInput):@@ -157,7 +165,13 @@ class AttributeUpdate(AttributeMixin, ModelWithExtRefMutation):cleaned_input = cls.clean_input(info, instance, input)cls.clean_attribute(instance, cleaned_input)cls.clean_values(cleaned_input, instance)- cls.clean_remove_values(cleaned_input, instance)+ remove_values = cls.clean_remove_values(cleaned_input, instance)+ product_ids = get_product_ids_to_search_index_update_for_attribute_values(+ remove_values+ )+ page_ids = get_page_ids_to_search_index_update_for_attribute_values(+ remove_values+ )# Construct the attributeinstance = cls.construct_instance(instance, cleaned_input)@@ -167,6 +181,9 @@ class AttributeUpdate(AttributeMixin, ModelWithExtRefMutation):instance.save()cls._save_m2m(info, instance, cleaned_input)cls.post_save_action(info, instance, cleaned_input)+ if remove_values:+ mark_products_search_vector_as_dirty_in_batches(product_ids)+ mark_pages_search_vector_as_dirty_in_batches(page_ids)# Return the attribute that was createdreturn AttributeUpdate(attribute=ChannelContext(instance, None))diff --git a/saleor/graphql/attribute/mutations/attribute_value_delete.py b/saleor/graphql/attribute/mutations/attribute_value_delete.pyindex a62df49c21..c35e4ed250 100644--- a/saleor/graphql/attribute/mutations/attribute_value_delete.py+++ b/saleor/graphql/attribute/mutations/attribute_value_delete.py@@ -1,9 +1,13 @@+from typing import cast+import graphene-from django.db.models import Exists, OuterRef, Qfrom ....attribute import models as models+from ....page.utils import mark_pages_search_vector_as_dirty_in_batchesfrom ....permission.enums import ProductTypePermissions-from ....product import models as product_models+from ....product.utils.search_helpers import (+ mark_products_search_vector_as_dirty_in_batches,+)from ....webhook.event_types import WebhookEventAsyncTypefrom ...core import ResolveInfofrom ...core.context import ChannelContext@@ -12,6 +16,10 @@ from ...core.types import AttributeErrorfrom ...core.utils import WebhookEventInfofrom ...plugins.dataloaders import get_plugin_manager_promisefrom ..types import Attribute, AttributeValue+from .utils import (+ get_page_ids_to_search_index_update_for_attribute_values,+ get_product_ids_to_search_index_update_for_attribute_values,+)class AttributeValueDelete(ModelDeleteMutation, ModelWithExtRefMutation):@@ -47,31 +55,23 @@ class AttributeValueDelete(ModelDeleteMutation, ModelWithExtRefMutation):cls, _root, info: ResolveInfo, /, *, external_reference=None, id=None):instance = cls.get_instance(info, external_reference=external_reference, id=id)- product_ids = cls.get_product_ids_to_update(instance)+ instance = cast(models.AttributeValue, instance)+ product_ids = get_product_ids_to_search_index_update_for_attribute_values(+ [instance]+ )+ page_ids = get_page_ids_to_search_index_update_for_attribute_values([instance])response = super().perform_mutation(_root, info, external_reference=external_reference, id=id)- product_models.Product.objects.filter(id__in=product_ids).update(- search_index_dirty=True- )+ mark_products_search_vector_as_dirty_in_batches(product_ids)+ mark_pages_search_vector_as_dirty_in_batches(page_ids)manager = get_plugin_manager_promise(info.context).get()cls.call_event(manager.attribute_value_deleted, instance)cls.call_event(manager.attribute_updated, instance.attribute)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.productvalueassignment.filter(product_id=OuterRef("id"))))- | Q(Exists(variants.filter(product_id=OuterRef("id"))))- ).values_list("id", flat=True)- return list(product_ids)-- @classmethod- def success_response(cls, instance):+ def success_response(cls, instance: models.AttributeValue):response = super().success_response(instance)response.attribute = ChannelContext(instance.attribute, None)response.attributeValue = ChannelContext(instance, None)diff --git a/saleor/graphql/attribute/mutations/attribute_value_update.py b/saleor/graphql/attribute/mutations/attribute_value_update.pyindex 86fff7bbd9..744d0e54d8 100644--- a/saleor/graphql/attribute/mutations/attribute_value_update.py+++ b/saleor/graphql/attribute/mutations/attribute_value_update.py@@ -1,12 +1,14 @@import graphene-from django.db import transactionfrom django.db.models import Exists, OuterRef, Qfrom ....attribute import models as models-from ....core.utils.batches import queryset_in_batches+from ....page import models as page_models+from ....page.utils import mark_pages_search_vector_as_dirty_in_batchesfrom ....permission.enums import ProductTypePermissionsfrom ....product import models as product_models-from ....product.lock_objects import product_qs_select_for_update+from ....product.utils.search_helpers import (+ mark_products_search_vector_as_dirty_in_batches,+)from ....webhook.event_types import WebhookEventAsyncTypefrom ...core import ResolveInfofrom ...core.context import ChannelContext@@ -18,8 +20,6 @@ from ..types import Attribute, AttributeValuefrom .attribute_update import AttributeValueUpdateInputfrom .attribute_value_create import AttributeValueCreate-BATCH_SIZE = 10000-class AttributeValueUpdate(AttributeValueCreate, ModelWithExtRefMutation):attribute = graphene.Field(Attribute, description="The updated attribute.")@@ -84,6 +84,11 @@ class AttributeValueUpdate(AttributeValueCreate, ModelWithExtRefMutation):@classmethoddef mark_search_index_dirty(cls, instance):+ cls._mark_products_search_index_dirty(instance)+ cls._mark_pages_search_index_dirty(instance)++ @classmethod+ def _mark_products_search_index_dirty(cls, instance):variants = product_models.ProductVariant.objects.filter(Exists(instance.variantassignments.filter(variant_id=OuterRef("id"))))@@ -100,13 +105,15 @@ class AttributeValueUpdate(AttributeValueCreate, ModelWithExtRefMutation):| Q(Exists(variants.filter(product_id=OuterRef("id")))))).order_by("pk")- for batch_pks in queryset_in_batches(products, BATCH_SIZE):- with transaction.atomic():- # SELECT … FOR UPDATE needs to lock rows in a consistent order- # to avoid deadlocks between updates touching the same rows.- _products = list(- product_qs_select_for_update().filter(pk__in=batch_pks)- )- product_models.Product.objects.filter(pk__in=batch_pks).update(- search_index_dirty=True- )+ mark_products_search_vector_as_dirty_in_batches(+ list(products.values_list("id", flat=True))+ )++ @classmethod+ def _mark_pages_search_index_dirty(cls, instance):+ pages = page_models.Page.objects.filter(+ Exists(instance.pagevalueassignment.filter(page_id=OuterRef("id")))+ ).order_by("pk")+ mark_pages_search_vector_as_dirty_in_batches(+ list(pages.values_list("id", flat=True))+ )diff --git a/saleor/graphql/attribute/mutations/utils.py b/saleor/graphql/attribute/mutations/utils.pynew file mode 100644index 0000000000..6711918e4b--- /dev/null+++ b/saleor/graphql/attribute/mutations/utils.py@@ -0,0 +1,52 @@+from django.db.models import Exists, OuterRef++from ....attribute import models+from ....page import models as page_models+from ....product import models as product_models+++def get_product_ids_to_search_index_update_for_attribute_values(+ values: list[models.AttributeValue],+) -> list[int]:+ """Get product IDs that need search index updates when attribute values are changed.++ Finds all products that has the given attribute values assigned or their variants+ have the given attribute values assigned.+ """+ if not values:+ return []+ assigned_variant_values = models.AssignedVariantAttributeValue.objects.filter(+ value_id__in=[v.id for v in values]+ )+ assigned_attributes = models.AssignedVariantAttribute.objects.filter(+ Exists(assigned_variant_values.filter(assignment_id=OuterRef("id")))+ )+ variants = product_models.ProductVariant.objects.filter(+ Exists(assigned_attributes.filter(variant_id=OuterRef("id")))+ )+ assigned_product_values = models.AssignedProductAttributeValue.objects.filter(+ value_id__in=[v.id for v in values]+ )+ product_ids = product_models.Product.objects.filter(+ Exists(assigned_product_values.filter(product_id=OuterRef("id")))+ | Exists(variants.filter(product_id=OuterRef("id")))+ ).values_list("id", flat=True)+ return list(product_ids)+++def get_page_ids_to_search_index_update_for_attribute_values(+ values: list[models.AttributeValue],+) -> list[int]:+ """Get page IDs that need search index updates when attribute values are changed.++ Finds all pages that has the given attribute values assigned.+ """+ if not values:+ return []+ assigned_values = models.AssignedPageAttributeValue.objects.filter(+ value_id__in=[v.id for v in values]+ )+ page_ids = page_models.Page.objects.filter(+ Exists(assigned_values.filter(page_id=OuterRef("id")))+ ).values_list("id", flat=True)+ return list(page_ids)diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_update.pyindex a33be9ba81..f5f5585134 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_update.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_update.py@@ -4,6 +4,10 @@ import graphenefrom .....attribute.error_codes import AttributeBulkUpdateErrorCodefrom .....attribute.models import Attribute+from .....attribute.tests.model_helpers import (+ get_product_attribute_values,+ get_product_attributes,+)from ....core.enums import ErrorPolicyEnumfrom ....tests.utils import get_graphql_content@@ -503,6 +507,74 @@ def test_attribute_bulk_update_removes_invalid_value()+def test_attribute_bulk_update_removes_value_mark_product_search_index_dirty(+ staff_api_client, product, permission_manage_product_types_and_attributes+):+ # given+ attribute = get_product_attributes(product).first()+ value = get_product_attribute_values(product, attribute).first()+ assert product.search_index_dirty is False++ value_global_id = graphene.Node.to_global_id("AttributeValue", value.id)+ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", attribute.id),+ "fields": {"removeValues": [value_global_id]},+ }+ ]++ # when+ staff_api_client.user.user_permissions.add(+ permission_manage_product_types_and_attributes+ )+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]++ # then+ assert data["count"] == 1+ assert not data["results"][0]["errors"]+ product.refresh_from_db()+ assert product.search_index_dirty is True+++def test_attribute_bulk_update_removes_value_mark_page_search_index_dirty(+ staff_api_client, page, permission_manage_page_types_and_attributes+):+ # given+ value = page.attributevalues.first().value+ attribute = value.attribute+ assert page.search_index_dirty is False++ value_global_id = graphene.Node.to_global_id("AttributeValue", value.id)+ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", attribute.id),+ "fields": {"removeValues": [value_global_id]},+ }+ ]++ # when+ staff_api_client.user.user_permissions.add(+ permission_manage_page_types_and_attributes+ )+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]++ # then+ assert data["count"] == 1+ assert not data["results"][0]["errors"]+ page.refresh_from_db()+ assert page.search_index_dirty is True++def test_attribute_bulk_update_add_new_value(staff_api_client,color_attribute,diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_delete.py b/saleor/graphql/attribute/tests/mutations/test_attribute_delete.pyindex d80ae56580..acb250feff 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_delete.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_delete.py@@ -6,6 +6,9 @@ import pytestfrom django.utils.functional import SimpleLazyObjectfrom freezegun import freeze_time+from .....attribute.tests.model_helpers import (+ get_product_attributes,+)from .....core.utils.json_serializer import CustomJsonEncoderfrom .....webhook.event_types import WebhookEventAsyncTypefrom .....webhook.payloads import generate_meta, generate_requestor@@ -130,6 +133,51 @@ def test_delete_file_attribute(attribute.refresh_from_db()+def test_delete_attribute_update_search_index_dirty_in_product(+ staff_api_client,+ product,+ permission_manage_product_types_and_attributes,+):+ # given+ first_attribute = get_product_attributes(product).first()+ node_id = graphene.Node.to_global_id("Attribute", first_attribute.id)+ variables = {"id": node_id}++ # when+ staff_api_client.post_graphql(+ ATTRIBUTE_DELETE_MUTATION,+ variables,+ permissions=[permission_manage_product_types_and_attributes],+ )+ product.refresh_from_db(fields=["search_index_dirty"])++ # then+ assert product.search_index_dirty is True+++def test_delete_attribute_update_search_index_dirty_in_page(+ staff_api_client,+ page,+ page_type,+ permission_manage_product_types_and_attributes,+):+ # given+ attribute = page_type.page_attributes.first()+ variables = {"id": graphene.Node.to_global_id("Attribute", attribute.id)}+ assert page.search_index_dirty is False++ # when+ staff_api_client.post_graphql(+ ATTRIBUTE_DELETE_MUTATION,+ variables,+ permissions=[permission_manage_product_types_and_attributes],+ )++ # then+ page.refresh_from_db(fields=["search_index_dirty"])+ assert page.search_index_dirty is True++ATTRIBUTE_DELETE_BY_EXTERNAL_REFERENCE_MUTATION = """mutation deleteAttribute($id: ID, $externalReference: String) {attributeDelete(id: $id, externalReference: $externalReference) {diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_update.pyindex 3c32f7388a..7d687983b6 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_update.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_update.py@@ -9,6 +9,10 @@ from freezegun import freeze_timefrom .....attribute import AttributeEntityType, AttributeInputTypefrom .....attribute.error_codes import AttributeErrorCodefrom .....attribute.models import Attribute, AttributeValue+from .....attribute.tests.model_helpers import (+ get_product_attribute_values,+ get_product_attributes,+)from .....core.utils.json_serializer import CustomJsonEncoderfrom .....webhook.event_types import WebhookEventAsyncTypefrom .....webhook.payloads import generate_meta, generate_requestor@@ -1142,3 +1146,135 @@ def test_update_attribute_with_reference_types_product_types_provided_for_page_rassert len(errors) == 1assert errors[0]["field"] == "referenceTypes"assert errors[0]["code"] == AttributeErrorCode.INVALID.name+++def test_update_attribute_remove_value_marks_product_search_index_dirty(+ staff_api_client, product, permission_manage_product_types_and_attributes+):+ # given+ query = UPDATE_ATTRIBUTE_MUTATION+ attribute = get_product_attributes(product).first()+ value = get_product_attribute_values(product, attribute).first()++ assert product.search_index_dirty is False++ node_id = graphene.Node.to_global_id("Attribute", attribute.id)+ value_id = graphene.Node.to_global_id("AttributeValue", value.id)+ variables = {+ "id": node_id,+ "input": {+ "removeValues": [value_id],+ "addValues": [],+ },+ }++ # 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"]["attributeUpdate"]+ assert not data["errors"]++ product.refresh_from_db()+ assert product.search_index_dirty is True+++def test_update_attribute_add_value_does_not_mark_product_search_index_dirty(+ staff_api_client, product, permission_manage_product_types_and_attributes+):+ # given+ attribute = get_product_attributes(product).first()+ assert product.search_index_dirty is False++ node_id = graphene.Node.to_global_id("Attribute", attribute.id)+ variables = {+ "id": node_id,+ "input": {+ "addValues": [{"name": "New value"}],+ },+ }++ # when+ response = staff_api_client.post_graphql(+ UPDATE_ATTRIBUTE_MUTATION,+ variables,+ permissions=[permission_manage_product_types_and_attributes],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["attributeUpdate"]+ assert not data["errors"]++ product.refresh_from_db()+ assert product.search_index_dirty is False+++def test_update_attribute_remove_value_marks_page_search_index_dirty(+ staff_api_client, page, permission_manage_product_types_and_attributes+):+ # given+ value = page.attributevalues.first().value+ attribute = value.attribute++ assert page.search_index_dirty is False++ node_id = graphene.Node.to_global_id("Attribute", attribute.id)+ value_id = graphene.Node.to_global_id("AttributeValue", value.id)+ variables = {+ "id": node_id,+ "input": {+ "removeValues": [value_id],+ "addValues": [],+ },+ }++ # when+ response = staff_api_client.post_graphql(+ UPDATE_ATTRIBUTE_MUTATION,+ variables,+ permissions=[permission_manage_product_types_and_attributes],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["attributeUpdate"]+ assert not data["errors"]++ page.refresh_from_db()+ assert page.search_index_dirty is True+++def test_update_attribute_add_value_does_not_mark_page_search_index_dirty(+ staff_api_client, page, permission_manage_product_types_and_attributes+):+ # given+ attribute = page.attributevalues.first().value.attribute++ assert page.search_index_dirty is False++ node_id = graphene.Node.to_global_id("Attribute", attribute.id)+ variables = {+ "id": node_id,+ "input": {+ "addValues": [{"name": "New value"}],+ },+ }++ # when+ response = staff_api_client.post_graphql(+ UPDATE_ATTRIBUTE_MUTATION,+ variables,+ permissions=[permission_manage_product_types_and_attributes],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["attributeUpdate"]+ assert not data["errors"]++ page.refresh_from_db()+ assert page.search_index_dirty is Falsediff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py b/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.pyindex 9848ae8ea9..863375eb2d 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py@@ -72,6 +72,28 @@ def test_delete_attribute_value_update_search_index_dirty_in_product(assert product.search_index_dirty is True+def test_delete_attribute_value_update_search_index_dirty_in_page(+ staff_api_client,+ page,+ permission_manage_product_types_and_attributes,+):+ # given+ attribute_value = page.attributevalues.first()+ query = ATTRIBUTE_VALUE_DELETE_MUTATION+ node_id = graphene.Node.to_global_id("AttributeValue", attribute_value.value_id)+ variables = {"id": node_id}+ assert page.search_index_dirty is False++ # when+ staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )++ # then+ page.refresh_from_db(fields=["search_index_dirty"])+ assert page.search_index_dirty is True++@freeze_time("2022-05-12 12:00:00")@mock.patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.pyindex a78f199c79..ff325363ac 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py@@ -115,6 +115,30 @@ def test_update_attribute_value_update_search_index_dirty_in_product(assert product.search_index_dirty is True+def test_update_attribute_value_update_search_index_dirty_in_page(+ staff_api_client,+ page,+ permission_manage_product_types_and_attributes,+):+ # given+ query = UPDATE_ATTRIBUTE_VALUE_MUTATION++ attribute_value = page.attributevalues.first()++ node_id = graphene.Node.to_global_id("AttributeValue", attribute_value.value_id)+ name = "Crimson name"+ variables = {"input": {"name": name}, "id": node_id}++ # when+ staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )++ # then+ page.refresh_from_db(fields=["search_index_dirty"])+ assert page.search_index_dirty is True++@freeze_time("2022-05-12 12:00:00")@mock.patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")diff --git a/saleor/graphql/page/bulk_mutations.py b/saleor/graphql/page/bulk_mutations.pyindex 0651459c7d..9c9b8e171c 100644--- a/saleor/graphql/page/bulk_mutations.py+++ b/saleor/graphql/page/bulk_mutations.py@@ -9,8 +9,10 @@ from ...attribute.lock_objects import attribute_value_qs_select_for_updatefrom ...core.tracing import traced_atomic_transactionfrom ...page import modelsfrom ...permission.enums import PagePermissions, PageTypePermissions-from ...product.lock_objects import product_qs_select_for_updatefrom ...product.models import Product+from ...product.utils.search_helpers import (+ mark_products_search_vector_as_dirty_in_batches,+)from ...webhook.event_types import WebhookEventAsyncTypefrom ...webhook.utils import get_webhooks_for_eventfrom ..core import ResolveInfo@@ -50,22 +52,19 @@ class PageBulkDelete(ModelBulkDeleteMutation):@classmethoddef update_products_search_index(cls, instance_pks):# Mark products that use these page instances as references as dirty- with transaction.atomic():- locked_ids = (- product_qs_select_for_update()- .filter(- Exists(- attribute_models.AssignedProductAttributeValue.objects.filter(- product_id=OuterRef("id"),- value__in=attribute_models.AttributeValue.objects.filter(- reference_page__in=instance_pks- ),- )+ products_ids = list(+ Product.objects.filter(+ Exists(+ attribute_models.AssignedProductAttributeValue.objects.filter(+ product_id=OuterRef("id"),+ value__in=attribute_models.AttributeValue.objects.filter(+ reference_page__in=instance_pks+ ),))- .values_list("id", flat=True)- )- Product.objects.filter(id__in=locked_ids).update(search_index_dirty=True)+ ).values_list("id", flat=True)+ )+ mark_products_search_vector_as_dirty_in_batches(products_ids)@classmethoddef delete_assigned_attribute_values(cls, instance_pks):@@ -150,22 +149,19 @@ class PageTypeBulkDelete(ModelBulkDeleteMutation):page_ids = models.Page.objects.filter(page_type__in=instance_pks).values_list("id", flat=True)- with transaction.atomic():- locked_ids = (- product_qs_select_for_update()- .filter(- Exists(- attribute_models.AssignedProductAttributeValue.objects.filter(- product_id=OuterRef("id"),- value__in=attribute_models.AttributeValue.objects.filter(- reference_page_id__in=page_ids- ),- )+ product_ids = list(+ Product.objects.filter(+ Exists(+ attribute_models.AssignedProductAttributeValue.objects.filter(+ product_id=OuterRef("id"),+ value__in=attribute_models.AttributeValue.objects.filter(+ reference_page_id__in=page_ids+ ),))- .values_list("id", flat=True)- )- Product.objects.filter(id__in=locked_ids).update(search_index_dirty=True)+ ).values_list("id", flat=True)+ )+ mark_products_search_vector_as_dirty_in_batches(product_ids)@classmethoddef bulk_action(cls, info: ResolveInfo, queryset, /):diff --git a/saleor/graphql/page/filters.py b/saleor/graphql/page/filters.pyindex 98e4480ad2..03fac68baa 100644--- a/saleor/graphql/page/filters.py+++ b/saleor/graphql/page/filters.py@@ -27,7 +27,6 @@ from ..attribute.shared_filters import (get_attribute_values_by_slug_or_name_value,validate_attribute_value_input,)-from ..core.context import ChannelQsContextfrom ..core.doc_category import DOC_CATEGORY_PAGESfrom ..core.filters import (FilterInputObjectType,@@ -58,17 +57,6 @@ from ..utils.filters import (from .types import Page, PageType-def search_pages(channel_qs: ChannelQsContext, value):- if not value:- return channel_qs- channel_qs.qs = channel_qs.qs.filter(- Q(title__trigram_similar=value)- | Q(slug__trigram_similar=value)- | Q(content__icontains=value)- )- return channel_qs--def filter_page_page_types(qs, _, value):if not value:return qsdiff --git a/saleor/graphql/page/mutations/page_attribute_assign.py b/saleor/graphql/page/mutations/page_attribute_assign.pyindex da085dd311..e7b251bdd1 100644--- a/saleor/graphql/page/mutations/page_attribute_assign.py+++ b/saleor/graphql/page/mutations/page_attribute_assign.py@@ -6,6 +6,7 @@ from django.core.exceptions import ValidationErrorfrom ....attribute import AttributeType, modelsfrom ....page import models as page_modelsfrom ....page.error_codes import PageErrorCode+from ....page.utils import mark_pages_search_vector_as_dirty_in_batchesfrom ....permission.enums import PageTypePermissionsfrom ...attribute.types import Attributefrom ...core import ResolveInfo@@ -103,4 +104,14 @@ class PageAttributeAssign(BaseMutation):page_type.page_attributes.add(*attr_pks)+ # Mark related page search indexes as dirty. Currently, unassigning attributes+ # from a page type does not remove their values from existing pages.+ # As a result, if the attribute is reassigned, its value should be included+ # in the page search vector.+ page_ids = list(+ page_models.Page.objects.filter(page_type=page_type).values_list(+ "pk", flat=True+ )+ )+ mark_pages_search_vector_as_dirty_in_batches(page_ids)return cls(page_type=page_type)diff --git a/saleor/graphql/page/mutations/page_attribute_unassign.py b/saleor/graphql/page/mutations/page_attribute_unassign.pyindex 3931fa4033..3952809809 100644--- a/saleor/graphql/page/mutations/page_attribute_unassign.py+++ b/saleor/graphql/page/mutations/page_attribute_unassign.py@@ -1,5 +1,7 @@import graphene+from ....page import models+from ....page.utils import mark_pages_search_vector_as_dirty_in_batchesfrom ....permission.enums import PageTypePermissionsfrom ...attribute.types import Attributefrom ...core import ResolveInfo@@ -46,4 +48,9 @@ class PageAttributeUnassign(BaseMutation):page_type.page_attributes.remove(*attr_pks)+ page_ids = list(+ models.Page.objects.filter(page_type=page_type).values_list("pk", flat=True)+ )+ mark_pages_search_vector_as_dirty_in_batches(page_ids)+return cls(page_type=page_type)diff --git a/saleor/graphql/page/mutations/page_delete.py b/saleor/graphql/page/mutations/page_delete.pyindex ed8f413988..438561fc1f 100644--- a/saleor/graphql/page/mutations/page_delete.py+++ b/saleor/graphql/page/mutations/page_delete.py@@ -1,5 +1,4 @@import graphene-from django.db import transactionfrom django.db.models.expressions import Exists, OuterReffrom ....attribute import AttributeInputType@@ -7,8 +6,10 @@ from ....attribute import models as attribute_modelsfrom ....core.tracing import traced_atomic_transactionfrom ....page import modelsfrom ....permission.enums import PagePermissions-from ....product.lock_objects import product_qs_select_for_updatefrom ....product.models import Product+from ....product.utils.search_helpers import (+ mark_products_search_vector_as_dirty_in_batches,+)from ...core import ResolveInfofrom ...core.context import ChannelContextfrom ...core.mutations import ModelDeleteMutation@@ -46,22 +47,19 @@ class PageDelete(ModelDeleteMutation):@classmethoddef update_products_search_index(cls, instance):# Mark products that use this instance as reference as dirty- with transaction.atomic():- locked_ids = (- product_qs_select_for_update()- .filter(- Exists(- attribute_models.AssignedProductAttributeValue.objects.filter(- value__in=attribute_models.AttributeValue.objects.filter(- reference_page=instance- ),- product_id=OuterRef("id"),- )+ product_ids = list(+ Product.objects.filter(+ Exists(+ attribute_models.AssignedProductAttributeValue.objects.filter(+ value__in=attribute_models.AttributeValue.objects.filter(+ reference_page=instance+ ),+ product_id=OuterRef("id"),))- .values_list("id", flat=True)- )- Product.objects.filter(id__in=locked_ids).update(search_index_dirty=True)+ ).values_list("id", flat=True)+ )+ mark_products_search_vector_as_dirty_in_batches(product_ids)@staticmethoddef delete_assigned_attribute_values(instance):diff --git a/saleor/graphql/page/mutations/page_type_delete.py b/saleor/graphql/page/mutations/page_type_delete.pyindex 643385d251..53659f1f6d 100644--- a/saleor/graphql/page/mutations/page_type_delete.py+++ b/saleor/graphql/page/mutations/page_type_delete.py@@ -1,5 +1,4 @@import graphene-from django.db import transactionfrom django.db.models.expressions import Exists, OuterReffrom ....attribute import AttributeInputType@@ -7,8 +6,10 @@ from ....attribute import models as attribute_modelsfrom ....core.tracing import traced_atomic_transactionfrom ....page import modelsfrom ....permission.enums import PageTypePermissions-from ....product.lock_objects import product_qs_select_for_updatefrom ....product.models import Product+from ....product.utils.search_helpers import (+ mark_products_search_vector_as_dirty_in_batches,+)from ...core import ResolveInfofrom ...core.mutations import ModelDeleteMutationfrom ...core.types import PageError@@ -44,22 +45,19 @@ class PageTypeDelete(ModelDeleteMutation):page_ids = models.Page.objects.filter(page_type=instance).values_list("id", flat=True)- with transaction.atomic():- locked_ids = (- product_qs_select_for_update()- .filter(- Exists(- attribute_models.AssignedProductAttributeValue.objects.filter(- product_id=OuterRef("id"),- value__in=attribute_models.AttributeValue.objects.filter(- reference_page_id__in=page_ids- ),- )+ product_ids = list(+ Product.objects.filter(+ Exists(+ attribute_models.AssignedProductAttributeValue.objects.filter(+ product_id=OuterRef("id"),+ value__in=attribute_models.AttributeValue.objects.filter(+ reference_page_id__in=page_ids+ ),))- .values_list("id", flat=True)- )- Product.objects.filter(id__in=locked_ids).update(search_index_dirty=True)+ ).values_list("id", flat=True)+ )+ mark_products_search_vector_as_dirty_in_batches(product_ids)@staticmethoddef delete_assigned_attribute_values(instance_pk):diff --git a/saleor/graphql/page/mutations/page_type_update.py b/saleor/graphql/page/mutations/page_type_update.pyindex 0a73413e57..8714b309fa 100644--- a/saleor/graphql/page/mutations/page_type_update.py+++ b/saleor/graphql/page/mutations/page_type_update.py@@ -5,6 +5,7 @@ from django.core.exceptions import ValidationErrorfrom ....page import modelsfrom ....page.error_codes import PageErrorCode+from ....page.utils import mark_pages_search_vector_as_dirty_in_batchesfrom ....permission.enums import PageTypePermissionsfrom ...core import ResolveInfofrom ...core.doc_category import DOC_CATEGORY_PAGES@@ -20,7 +21,7 @@ from .page_type_create import PageTypeCreateInput, PageTypeMixinclass PageTypeUpdateInput(PageTypeCreateInput):remove_attributes = NonNullList(graphene.ID,- description="List of attribute IDs to be assigned to the page type.",+ description="List of attribute IDs to be unassigned from the page type.",)class Meta:@@ -86,3 +87,17 @@ class PageTypeUpdate(PageTypeMixin, DeprecatedModelMutation):def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):manager = get_plugin_manager_promise(info.context).get()cls.call_event(manager.page_type_updated, instance)+ # Mark pages for search index update if page type structure or identification changed+ should_update_search_index = (+ cleaned_input.get("remove_attributes")+ or "name" in cleaned_input+ or "slug" in cleaned_input+ )++ if should_update_search_index:+ page_ids = list(+ models.Page.objects.filter(page_type=instance).values_list(+ "pk", flat=True+ )+ )+ mark_pages_search_vector_as_dirty_in_batches(page_ids)diff --git a/saleor/graphql/page/mutations/page_update.py b/saleor/graphql/page/mutations/page_update.pyindex f4d8387688..2bff99aea4 100644--- a/saleor/graphql/page/mutations/page_update.py+++ b/saleor/graphql/page/mutations/page_update.py@@ -1,13 +1,14 @@import graphene-from django.db import transactionfrom django.db.models import Exists, OuterReffrom ....attribute import models as attribute_modelsfrom ....core.utils.update_mutation_manager import InstanceTrackerfrom ....page import modelsfrom ....permission.enums import PagePermissions-from ....product.lock_objects import product_qs_select_for_updatefrom ....product.models import Product+from ....product.utils.search_helpers import (+ mark_products_search_vector_as_dirty_in_batches,+)from ...attribute.utils.attribute_assignment import AttributeAssignmentMixinfrom ...core import ResolveInfofrom ...core.context import ChannelContext@@ -31,9 +32,7 @@ class PageUpdate(PageCreate):permissions = (PagePermissions.MANAGE_PAGES,)error_type_class = PageErrorerror_type_field = "page_errors"- instance_tracker_fields = [- "title",- ]+ instance_tracker_fields = ["title", "slug", "content"]@classmethoddef clean_attributes(cls, attributes: list[dict], page_type: models.PageType):@@ -51,34 +50,35 @@ class PageUpdate(PageCreate):cleaned_input,instance_tracker: InstanceTracker | None = None,):- super(PageCreate, cls).save(info, instance, cleaned_input)+ modified_instance_fields = (+ instance_tracker.get_modified_fields() if instance_tracker else []+ )+ if modified_instance_fields or cleaned_input.get("attributes"):+ instance.search_index_dirty = True+ instance.save()+manager = get_plugin_manager_promise(info.context).get()cls.call_event(manager.page_updated, instance)- if instance_tracker is not None:- modified_instance_fields = instance_tracker.get_modified_fields()- if "title" in modified_instance_fields:- cls.update_products_search_index(instance)+ if "title" in modified_instance_fields:+ cls.update_products_search_index(instance)@classmethoddef update_products_search_index(cls, instance):# Mark products that use this instance as reference as dirty- with transaction.atomic():- locked_ids = (- product_qs_select_for_update()- .filter(- Exists(- attribute_models.AssignedProductAttributeValue.objects.filter(- value__in=attribute_models.AttributeValue.objects.filter(- reference_page=instance- ),- product_id=OuterRef("id"),- )+ product_ids = list(+ Product.objects.filter(+ Exists(+ attribute_models.AssignedProductAttributeValue.objects.filter(+ value__in=attribute_models.AttributeValue.objects.filter(+ reference_page=instance+ ),+ product_id=OuterRef("id"),))- .values_list("id", flat=True)- )- Product.objects.filter(id__in=locked_ids).update(search_index_dirty=True)+ ).values_list("id", flat=True)+ )+ mark_products_search_vector_as_dirty_in_batches(product_ids)@classmethoddef success_response(cls, instance):diff --git a/saleor/graphql/page/schema.py b/saleor/graphql/page/schema.pyindex 534064e970..9daa924b65 100644--- a/saleor/graphql/page/schema.py+++ b/saleor/graphql/page/schema.py@@ -1,9 +1,10 @@import graphene+from ...page.search import search_pagesfrom ..channel.dataloaders.by_self import ChannelBySlugLoaderfrom ..core import ResolveInfofrom ..core.connection import create_connection_slice, filter_connection_queryset-from ..core.context import ChannelContext+from ..core.context import ChannelContext, ChannelQsContextfrom ..core.descriptions import ADDED_IN_321, ADDED_IN_322, DEPRECATED_IN_3X_INPUTfrom ..core.doc_category import DOC_CATEGORY_PAGESfrom ..core.enums import LanguageCodeEnum@@ -11,7 +12,7 @@ from ..core.fields import BaseField, FilterConnectionFieldfrom ..core.utils import from_global_id_or_errorfrom ..translations.mutations import PageTranslatefrom .bulk_mutations import PageBulkDelete, PageBulkPublish, PageTypeBulkDelete-from .filters import PageFilterInput, PageTypeFilterInput, PageWhereInput, search_pages+from .filters import PageFilterInput, PageTypeFilterInput, PageWhereInputfrom .mutations import (PageAttributeAssign,PageAttributeUnassign,@@ -118,7 +119,9 @@ class PageQueries(graphene.ObjectType):qs = resolve_pages(info, channel_slug=channel, channel=channel_instance)search = kwargs.get("search") or kwargs.get("filter", {}).get("search")if search:- qs = search_pages(qs, search)+ qs = ChannelQsContext(+ qs=search_pages(qs.qs, search), channel_slug=qs.channel_slug+ )qs = filter_connection_queryset(qs, kwargs, allow_replica=info.context.allow_replicadiff --git a/saleor/graphql/page/tests/mutations/test_page_attribute_assign.py b/saleor/graphql/page/tests/mutations/test_page_attribute_assign.pyindex cc4397057f..2dda371d6a 100644--- a/saleor/graphql/page/tests/mutations/test_page_attribute_assign.py+++ b/saleor/graphql/page/tests/mutations/test_page_attribute_assign.py@@ -35,6 +35,7 @@ def test_assign_attributes_to_page_type_by_staff(staff_api_client,permission_manage_page_types_and_attributes,page_type,+ page,author_page_attribute,):# given@@ -42,6 +43,7 @@ def test_assign_attributes_to_page_type_by_staff(staff_user.user_permissions.add(permission_manage_page_types_and_attributes)page_type_attr_count = page_type.page_attributes.count()+ assert page.search_index_dirty is Falseauthor_page_attr_id = graphene.Node.to_global_id("Attribute", author_page_attribute.pk@@ -65,12 +67,15 @@ def test_assign_attributes_to_page_type_by_staff(assert author_page_attr_id in {attr["id"] for attr in data["pageType"]["attributes"]}+ page.refresh_from_db()+ assert page.search_index_dirty is Truedef test_assign_attributes_to_page_type_by_app(app_api_client,permission_manage_page_types_and_attributes,page_type,+ page,author_page_attribute,):# given@@ -78,6 +83,7 @@ def test_assign_attributes_to_page_type_by_app(app.permissions.add(permission_manage_page_types_and_attributes)page_type_attr_count = page_type.page_attributes.count()+ assert page.search_index_dirty is Falseauthor_page_attr_id = graphene.Node.to_global_id("Attribute", author_page_attribute.pk@@ -101,6 +107,8 @@ def test_assign_attributes_to_page_type_by_app(assert author_page_attr_id in {attr["id"] for attr in data["pageType"]["attributes"]}+ page.refresh_from_db()+ assert page.search_index_dirty is Truedef test_assign_attributes_to_page_type_by_staff_no_perm(diff --git a/saleor/graphql/page/tests/mutations/test_page_attribute_unassign.py b/saleor/graphql/page/tests/mutations/test_page_attribute_unassign.pyindex 012258165e..317d9489b0 100644--- a/saleor/graphql/page/tests/mutations/test_page_attribute_unassign.py+++ b/saleor/graphql/page/tests/mutations/test_page_attribute_unassign.py@@ -27,7 +27,7 @@ PAGE_UNASSIGN_ATTR_QUERY = """def test_unassign_attributes_from_page_type_by_staff(- staff_api_client, page_type, permission_manage_page_types_and_attributes+ staff_api_client, page_type, page, permission_manage_page_types_and_attributes):# givenstaff_user = staff_api_client.user@@ -36,6 +36,7 @@ def test_unassign_attributes_from_page_type_by_staff(attr_count = page_type.page_attributes.count()attr_to_unassign = page_type.page_attributes.first()attr_to_unassign_id = graphene.Node.to_global_id("Attribute", attr_to_unassign.pk)+ assert page.search_index_dirty is Falsevariables = {"pageTypeId": graphene.Node.to_global_id("PageType", page_type.pk),@@ -55,6 +56,8 @@ def test_unassign_attributes_from_page_type_by_staff(assert attr_to_unassign_id not in {attr["id"] for attr in data["pageType"]["attributes"]}+ page.refresh_from_db()+ assert page.search_index_dirty is Truedef test_unassign_attributes_from_page_type_by_staff_no_perm(@@ -77,11 +80,12 @@ def test_unassign_attributes_from_page_type_by_staff_no_perm(def test_unassign_attributes_from_page_type_by_app(- app_api_client, page_type, permission_manage_page_types_and_attributes+ app_api_client, page_type, page, permission_manage_page_types_and_attributes):# givenapp = app_api_client.appapp.permissions.add(permission_manage_page_types_and_attributes)+ assert page.search_index_dirty is Falseattr_count = page_type.page_attributes.count()attr_to_unassign = page_type.page_attributes.first()@@ -105,6 +109,8 @@ def test_unassign_attributes_from_page_type_by_app(assert attr_to_unassign_id not in {attr["id"] for attr in data["pageType"]["attributes"]}+ page.refresh_from_db()+ assert page.search_index_dirty is Truedef test_unassign_attributes_from_page_type_by_app_no_perm(app_api_client, page_type):diff --git a/saleor/graphql/page/tests/mutations/test_page_type_update.py b/saleor/graphql/page/tests/mutations/test_page_type_update.pyindex 85a36767e5..f5a0f5d4a0 100644--- a/saleor/graphql/page/tests/mutations/test_page_type_update.py+++ b/saleor/graphql/page/tests/mutations/test_page_type_update.py@@ -39,6 +39,7 @@ PAGE_TYPE_UPDATE_MUTATION = """def test_page_type_update_as_staff(staff_api_client,page_type,+ page,permission_manage_page_types_and_attributes,author_page_attribute,size_page_attribute,@@ -47,6 +48,7 @@ def test_page_type_update_as_staff(# givenstaff_user = staff_api_client.userstaff_user.user_permissions.add(permission_manage_page_types_and_attributes)+ assert page.search_index_dirty is Falseslug = "new-slug"name = "new-name"@@ -82,6 +84,8 @@ def test_page_type_update_as_staff(tag_page_attribute.slug,author_page_attribute.slug,}+ page.refresh_from_db()+ assert page.search_index_dirty is True@freeze_time("2022-05-12 12:00:00")@@ -93,6 +97,7 @@ def test_page_type_update_trigger_webhook(any_webhook,staff_api_client,page_type,+ page,permission_manage_page_types_and_attributes,author_page_attribute,size_page_attribute,@@ -105,6 +110,7 @@ def test_page_type_update_trigger_webhook(staff_user = staff_api_client.userstaff_user.user_permissions.add(permission_manage_page_types_and_attributes)+ assert page.search_index_dirty is Falseslug = "new-slug"@@ -144,6 +150,8 @@ def test_page_type_update_trigger_webhook(SimpleLazyObject(lambda: staff_user),allow_replica=False,)+ page.refresh_from_db()+ assert page.search_index_dirty is Truedef test_page_type_update_as_staff_no_perm(staff_api_client, page_type):@@ -163,6 +171,7 @@ def test_page_type_update_as_staff_no_perm(staff_api_client, page_type):def test_page_type_update_as_app(staff_api_client,page_type,+ page,permission_manage_page_types_and_attributes,author_page_attribute,size_page_attribute,@@ -171,6 +180,7 @@ def test_page_type_update_as_app(# givenstaff_user = staff_api_client.userstaff_user.user_permissions.add(permission_manage_page_types_and_attributes)+ assert page.search_index_dirty is Falseslug = "new-slug"name = "new-name"@@ -206,6 +216,8 @@ def test_page_type_update_as_app(tag_page_attribute.slug,author_page_attribute.slug,}+ page.refresh_from_db()+ assert page.search_index_dirty is Truedef test_page_type_update_as_app_no_perm(app_api_client, page_type):@@ -422,3 +434,125 @@ def test_page_type_update_multiple_errors(assert errors[0]["code"] == PageErrorCode.DUPLICATED_INPUT_ITEM.nameassert errors[0]["field"] == "attributes"assert errors[0]["attributes"] == [author_page_attr_id]+++def test_page_type_update_only_name(+ staff_api_client,+ page_type,+ page,+ permission_manage_page_types_and_attributes,+):+ # given+ staff_user = staff_api_client.user+ staff_user.user_permissions.add(permission_manage_page_types_and_attributes)+ assert page.search_index_dirty is False++ name = "new-name"++ variables = {+ "id": graphene.Node.to_global_id("PageType", page_type.pk),+ "input": {+ "name": name,+ },+ }++ # when+ response = staff_api_client.post_graphql(PAGE_TYPE_UPDATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["pageTypeUpdate"]+ errors = data["errors"]+ page_type_data = data["pageType"]++ page_type.refresh_from_db()+ assert not errors+ assert page_type_data["name"] == name+ page.refresh_from_db()+ assert page.search_index_dirty is True+++def test_page_type_update_only_add_attributes(+ staff_api_client,+ page_type,+ page,+ permission_manage_page_types_and_attributes,+ author_page_attribute,+ size_page_attribute,+ tag_page_attribute,+):+ # given+ staff_user = staff_api_client.user+ staff_user.user_permissions.add(permission_manage_page_types_and_attributes)+ assert page.search_index_dirty is False++ variables = {+ "id": graphene.Node.to_global_id("PageType", page_type.pk),+ "input": {+ "addAttributes": [+ graphene.Node.to_global_id("Attribute", author_page_attribute.pk)+ ],+ },+ }++ # when+ response = staff_api_client.post_graphql(PAGE_TYPE_UPDATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["pageTypeUpdate"]+ errors = data["errors"]+ page_type_data = data["pageType"]++ page_type.refresh_from_db()+ assert not errors+ assert page_type_data["name"] == page_type.name+ assert page_type_data["slug"] == page_type.slug+ assert {attr["slug"] for attr in page_type_data["attributes"]} == {+ tag_page_attribute.slug,+ size_page_attribute.slug,+ author_page_attribute.slug,+ }+ # only adding attributes should not mark pages for search index update+ page.refresh_from_db()+ assert page.search_index_dirty is False+++def test_page_type_update_only_remove_attributes(+ staff_api_client,+ page_type,+ page,+ permission_manage_page_types_and_attributes,+ size_page_attribute,+ tag_page_attribute,+):+ # given+ staff_user = staff_api_client.user+ staff_user.user_permissions.add(permission_manage_page_types_and_attributes)+ assert page.search_index_dirty is False++ variables = {+ "id": graphene.Node.to_global_id("PageType", page_type.pk),+ "input": {+ "removeAttributes": [+ graphene.Node.to_global_id("Attribute", size_page_attribute.pk)+ ],+ },+ }++ # when+ response = staff_api_client.post_graphql(PAGE_TYPE_UPDATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["pageTypeUpdate"]+ errors = data["errors"]+ page_type_data = data["pageType"]++ page_type.refresh_from_db()+ assert not errors+ assert {attr["slug"] for attr in page_type_data["attributes"]} == {+ tag_page_attribute.slug,+ }+ page.refresh_from_db()+ assert page.search_index_dirty is Truediff --git a/saleor/graphql/page/tests/mutations/test_page_update.py b/saleor/graphql/page/tests/mutations/test_page_update.pyindex e53b33b7e5..a8c16d9d54 100644--- a/saleor/graphql/page/tests/mutations/test_page_update.py+++ b/saleor/graphql/page/tests/mutations/test_page_update.py@@ -154,6 +154,7 @@ def test_update_page(staff_api_client, permission_manage_pages, page):page_title = page.titlenew_slug = "new-slug"assert new_slug != page.slug+ assert page.search_index_dirty is Falsepage_id = graphene.Node.to_global_id("Page", page.id)@@ -231,6 +232,9 @@ def test_update_page(staff_api_client, permission_manage_pages, page):assert expected_size_assigned_attribute in assigned_attributesassert expected_tag_assigned_attribute in assigned_attributes+ page.refresh_from_db()+ assert page.search_index_dirty is True+@mock.patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")@@ -299,6 +303,7 @@ def test_update_page_only_title(staff_api_client, permission_manage_pages, page)page_title = page.titlenew_slug = "new-slug"assert new_slug != page.slug+ assert page.search_index_dirty is Falsepage_id = graphene.Node.to_global_id("Page", page.id)@@ -364,6 +369,9 @@ def test_update_page_only_title(staff_api_client, permission_manage_pages, page)assert expected_size_assigned_attribute in assigned_attributesassert expected_tag_assigned_attribute in assigned_attributes+ page.refresh_from_db()+ assert page.search_index_dirty is True+def test_update_page_with_file_attribute_value(staff_api_client, permission_manage_pages, page, page_file_attribute@@ -376,6 +384,7 @@ def test_update_page_with_file_attribute_value(page_file_attribute_id = graphene.Node.to_global_id("Attribute", page_file_attribute.pk)+ assert page.search_index_dirty is Falsepage_id = graphene.Node.to_global_id("Page", page.id)file_name = "test.txt"@@ -424,6 +433,10 @@ def test_update_page_with_file_attribute_value(}assert expected_assigned_attribute in assigned_attributes+ # ensure updating only attributes mark the page search index as dirty+ page.refresh_from_db()+ assert page.search_index_dirty is True+def test_update_page_with_file_attribute_new_value_is_not_created(staff_api_client, permission_manage_pages, page, page_file_attribute@@ -1496,10 +1509,12 @@ def test_public_page_sets_publication_date(def test_update_page_publication_date(staff_api_client, permission_manage_pages, page_type):+ # givendata = {"slug": "test-url","title": "Test page","page_type": page_type,+ "search_index_dirty": False,}page = Page.objects.create(**data)published_at = datetime.datetime.now(tz=datetime.UTC).replace(@@ -1508,11 +1523,15 @@ def test_update_page_publication_date(page_id = graphene.Node.to_global_id("Page", page.id)variables = {"id": page_id,- "input": {"isPublished": True, "slug": page.slug, "publishedAt": published_at},+ "input": {"isPublished": True, "publishedAt": published_at},}++ # whenresponse = staff_api_client.post_graphql(UPDATE_PAGE_MUTATION, variables, permissions=[permission_manage_pages])++ # thencontent = get_graphql_content(response)data = content["data"]["pageUpdate"]@@ -1520,6 +1539,10 @@ def test_update_page_publication_date(assert data["page"]["isPublished"] is Trueassert data["page"]["publishedAt"] == published_at.isoformat()+ # ensure that updating publish dates do not affect search_index_dirty flag+ page.refresh_from_db()+ assert page.search_index_dirty is False+@pytest.mark.parametrize("slug_value", [None, ""])def test_update_page_blank_slug_value(diff --git a/saleor/graphql/page/tests/queries/test_pages.py b/saleor/graphql/page/tests/queries/test_pages.pyindex 21c83d72b9..df3b108280 100644--- a/saleor/graphql/page/tests/queries/test_pages.py+++ b/saleor/graphql/page/tests/queries/test_pages.py@@ -21,103 +21,6 @@ QUERY_PAGES_WITH_FILTER = """"""- ("page_filter", "count"),- [- ({"search": "Page1"}, 2),- ({"search": "about"}, 1),- ({"search": "test"}, 1),- ({"search": "slug"}, 3),- ({"search": "Page"}, 2),- ],-)-def test_pages_query_with_filter(- page_filter, count, staff_api_client, permission_manage_pages, page_type-):- query = QUERY_PAGES_WITH_FILTER- Page.objects.create(- title="Page1",- slug="slug_page_1",- content=dummy_editorjs("Content for page 1"),- page_type=page_type,- )- Page.objects.create(- title="Page2",- slug="slug_page_2",- content=dummy_editorjs("Content for page 2"),- page_type=page_type,- )- Page.objects.create(- title="About",- slug="slug_about",- content=dummy_editorjs("About test content"),- page_type=page_type,- )- variables = {"filter": page_filter}- staff_api_client.user.user_permissions.add(permission_manage_pages)- response = staff_api_client.post_graphql(query, variables)- content = get_graphql_content(response)- assert content["data"]["pages"]["totalCount"] == count---QUERY_PAGES_WITH_SEARCH = """- query ($search: String) {- pages(first: 5, search:$search) {- totalCount- edges {- node {- id- }- }- }- }-"""--- ("search", "count"),- [- ("Page1", 2),- ("about", 1),- ("test", 1),- ("slug", 3),- ("Page", 2),- ],-)-def test_pages_query_with_search(- search, count, staff_api_client, permission_manage_pages, page_type-):- # given- query = QUERY_PAGES_WITH_SEARCH- Page.objects.create(- title="Page1",- slug="slug_page_1",- content=dummy_editorjs("Content for page 1"),- page_type=page_type,- )- Page.objects.create(- title="Page2",- slug="slug_page_2",- content=dummy_editorjs("Content for page 2"),- page_type=page_type,- )- Page.objects.create(- title="About",- slug="slug_about",- content=dummy_editorjs("About test content"),- page_type=page_type,- )- variables = {"search": search}- staff_api_client.user.user_permissions.add(permission_manage_pages)-- # when- response = staff_api_client.post_graphql(query, variables)-- # then- content = get_graphql_content(response)- assert content["data"]["pages"]["totalCount"] == count--def test_pages_query_with_filter_by_page_type(staff_api_client, permission_manage_pages, page_type_list):diff --git a/saleor/graphql/page/tests/queries/test_pages_search.py b/saleor/graphql/page/tests/queries/test_pages_search.pynew file mode 100644index 0000000000..84b48f662b--- /dev/null+++ b/saleor/graphql/page/tests/queries/test_pages_search.py@@ -0,0 +1,342 @@+import pytest++from .....attribute.utils import associate_attribute_values_to_instance+from .....page.models import Page+from .....page.search import update_pages_search_vector+from .....tests.utils import dummy_editorjs+from ....tests.utils import get_graphql_content++QUERY_PAGES_WITH_SEARCH = """+ query ($search: String) {+ pages(first: 5, search:$search) {+ totalCount+ edges {+ node {+ id+ }+ }+ }+ }+"""+++ ("search", "count"),+ [+ ("Author1", 1),+ ("about", 1),+ ("Author", 2),+ ],+)+def test_pages_query_with_search_by_title(+ search, count, staff_api_client, permission_manage_pages, page_type+):+ # given+ query = QUERY_PAGES_WITH_SEARCH+ pages = Page.objects.bulk_create(+ [+ Page(+ title="Author1",+ slug="slug_author_1",+ content=dummy_editorjs("Content for page 1"),+ page_type=page_type,+ ),+ Page(+ title="Author2",+ slug="slug_author_2",+ content=dummy_editorjs("Content for page 2"),+ page_type=page_type,+ ),+ Page(+ title="About",+ slug="slug_about",+ content=dummy_editorjs("About test content"),+ page_type=page_type,+ ),+ ]+ )+ update_pages_search_vector(pages)+ variables = {"search": search}+ staff_api_client.user.user_permissions.add(permission_manage_pages)++ # when+ response = staff_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["pages"]["totalCount"] == count+++ ("search", "count"),+ [+ ("slug_author_1", 1),+ ("1", 1),+ ("slug_author", 2),+ ],+)+def test_pages_query_with_search_by_slug(+ search, count, staff_api_client, permission_manage_pages, page_type+):+ # given+ query = QUERY_PAGES_WITH_SEARCH+ pages = Page.objects.bulk_create(+ [+ Page(+ title="Author1",+ slug="slug_author_1",+ content=dummy_editorjs("Content for page 1"),+ page_type=page_type,+ ),+ Page(+ title="Author2",+ slug="slug_author_2",+ content=dummy_editorjs("Content for page 2"),+ page_type=page_type,+ ),+ Page(+ title="About",+ slug="slug_about",+ content=dummy_editorjs("About test content"),+ page_type=page_type,+ ),+ ]+ )+ update_pages_search_vector(pages)+ variables = {"search": search}+ staff_api_client.user.user_permissions.add(permission_manage_pages)++ # when+ response = staff_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["pages"]["totalCount"] == count+++ ("search", "count"),+ [+ ("content", 3),+ ("Description", 1),+ ],+)+def test_pages_query_with_search_by_content(+ search, count, staff_api_client, permission_manage_pages, page_type+):+ # given+ query = QUERY_PAGES_WITH_SEARCH+ pages = Page.objects.bulk_create(+ [+ Page(+ title="Author1",+ slug="slug_author_1",+ content=dummy_editorjs("Content for page 1. Description."),+ page_type=page_type,+ ),+ Page(+ title="Author2",+ slug="slug_author_2",+ content=dummy_editorjs("Content for page 2"),+ page_type=page_type,+ ),+ Page(+ title="About",+ slug="slug_about",+ content=dummy_editorjs("About test content"),+ page_type=page_type,+ ),+ ]+ )+ update_pages_search_vector(pages)+ variables = {"search": search}+ staff_api_client.user.user_permissions.add(permission_manage_pages)++ # when+ response = staff_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["pages"]["totalCount"] == count+++ ("search", "count"),+ [+ ("page-type", 2),+ ("page type", 3),+ ("test-page-type", 1),+ ("Example", 2),+ ],+)+def test_pages_query_with_search_by_page_type(+ search,+ count,+ staff_api_client,+ permission_manage_pages,+ page_type_list,+):+ # given+ query = QUERY_PAGES_WITH_SEARCH+ pages = Page.objects.bulk_create(+ [+ Page(+ title="Author1",+ slug="slug_author_1",+ content=dummy_editorjs("Content for page 1. Description."),+ page_type=page_type_list[0],+ ),+ Page(+ title="Author2",+ slug="slug_author_2",+ content=dummy_editorjs("Content for page 2"),+ page_type=page_type_list[1],+ ),+ Page(+ title="About",+ slug="slug_about",+ content=dummy_editorjs("About test content"),+ page_type=page_type_list[2],+ ),+ ]+ )+ update_pages_search_vector(pages)+ variables = {"search": search}+ staff_api_client.user.user_permissions.add(permission_manage_pages)++ # when+ response = staff_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["pages"]["totalCount"] == count+++ ("search", "count"),+ [+ ("10", 2), # size value+ ("help", 1), # tag value+ ],+)+def test_pages_query_with_search_by_attributes(+ search,+ count,+ staff_api_client,+ permission_manage_pages,+ page_type_list,+ size_page_attribute,+ tag_page_attribute,+):+ # given+ query = QUERY_PAGES_WITH_SEARCH+ pages = Page.objects.bulk_create(+ [+ Page(+ title="Author1",+ slug="slug_author_1",+ content=dummy_editorjs("Content for page 1. Description."),+ page_type=page_type_list[0],+ ),+ Page(+ title="Author2",+ slug="slug_author_2",+ content=dummy_editorjs("Content for page 2"),+ page_type=page_type_list[1],+ ),+ Page(+ title="About",+ slug="slug_about",+ content=dummy_editorjs("About test content"),+ page_type=page_type_list[2],+ ),+ ]+ )+ for page_type in page_type_list:+ page_type.page_attributes.add(size_page_attribute, tag_page_attribute)++ page_1, _page_2, page_3 = pages+ size_value = size_page_attribute.values.first()+ tag_value = tag_page_attribute.values.last()++ associate_attribute_values_to_instance(+ page_1, {size_page_attribute.id: [size_value]}+ )+ associate_attribute_values_to_instance(+ page_3,+ {size_page_attribute.id: [size_value], tag_page_attribute.id: [tag_value]},+ )++ update_pages_search_vector(pages)+ variables = {"search": search}+ staff_api_client.user.user_permissions.add(permission_manage_pages)++ # when+ response = staff_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["pages"]["totalCount"] == count+++QUERY_PAGES_WITH_FILTER = """+ query ($filter: PageFilterInput) {+ pages(first: 5, filter:$filter) {+ totalCount+ edges {+ node {+ id+ }+ }+ }+ }+"""+++ ("page_filter", "count"),+ [+ ({"search": "Author1"}, 1),+ ({"search": "about"}, 1),+ ({"search": "test"}, 3),+ ({"search": "slug"}, 3),+ ({"search": "Author"}, 2),+ ],+)+def test_pages_query_with_filter(+ page_filter, count, staff_api_client, permission_manage_pages, page_type+):+ # given+ query = QUERY_PAGES_WITH_FILTER+ pages = Page.objects.bulk_create(+ [+ Page(+ title="Author1",+ slug="slug_author_1",+ content=dummy_editorjs("Content for page 1"),+ page_type=page_type,+ ),+ Page(+ title="Author2",+ slug="slug_author_2",+ content=dummy_editorjs("Content for page 2"),+ page_type=page_type,+ ),+ Page(+ title="About",+ slug="slug_about",+ content=dummy_editorjs("About test content"),+ page_type=page_type,+ ),+ ]+ )+ update_pages_search_vector(pages)+ variables = {"filter": page_filter}+ staff_api_client.user.user_permissions.add(permission_manage_pages)++ # when+ response = staff_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["pages"]["totalCount"] == countdiff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.pyindex 330398afa2..ce66e53134 100644--- a/saleor/graphql/product/mutations/attributes.py+++ b/saleor/graphql/product/mutations/attributes.py@@ -10,6 +10,9 @@ from ....core.tracing import traced_atomic_transactionfrom ....permission.enums import ProductPermissions, ProductTypePermissionsfrom ....product import modelsfrom ....product.error_codes import ProductErrorCode+from ....product.utils.search_helpers import (+ mark_products_search_vector_as_dirty_in_batches,+)from ...attribute.mutations import (BaseReorderAttributesMutation,BaseReorderAttributeValuesMutation,@@ -353,7 +356,12 @@ class ProductAttributeUnassign(BaseMutation):cls.save_field_values(product_type, "product_attributes", attribute_pks)cls.save_field_values(product_type, "variant_attributes", attribute_pks)- product_type.products.all().update(search_index_dirty=True)+ product_ids = list(+ models.Product.objects.filter(product_type=product_type).values_list(+ "id", flat=True+ )+ )+ mark_products_search_vector_as_dirty_in_batches(product_ids)return cls(product_type=product_type)diff --git a/saleor/graphql/product/mutations/product_type/product_type_update.py b/saleor/graphql/product/mutations/product_type/product_type_update.pyindex f8d23e16b1..df173a6648 100644--- a/saleor/graphql/product/mutations/product_type/product_type_update.py+++ b/saleor/graphql/product/mutations/product_type/product_type_update.py@@ -3,6 +3,9 @@ import graphenefrom .....permission.enums import ProductTypePermissionsfrom .....product import modelsfrom .....product.tasks import update_variants_names+from .....product.utils.search_helpers import (+ mark_products_search_vector_as_dirty_in_batches,+)from ....core import ResolveInfofrom ....core.types import ProductErrorfrom ...types import ProductType@@ -43,6 +46,9 @@ class ProductTypeUpdate(ProductTypeCreate):"product_attributes" in cleaned_inputor "variant_attributes" in cleaned_input):- models.Product.objects.filter(product_type=instance).update(- search_index_dirty=True+ product_ids = list(+ models.Product.objects.filter(product_type=instance).values_list(+ "id", flat=True+ ))+ mark_products_search_vector_as_dirty_in_batches(product_ids)diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 592d171eac..48ff61ebb0 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -24400,7 +24400,7 @@ input PageTypeUpdateInput @doc(category: "Pages") {"""List of attribute IDs to be assigned to the page type."""addAttributes: [ID!]- """List of attribute IDs to be assigned to the page type."""+ """List of attribute IDs to be unassigned from the page type."""removeAttributes: [ID!]}diff --git a/saleor/page/lock_objects.py b/saleor/page/lock_objects.pynew file mode 100644index 0000000000..524b7cd821--- /dev/null+++ b/saleor/page/lock_objects.py@@ -0,0 +1,7 @@+from django.db.models import QuerySet++from .models import Page+++def page_qs_select_for_update() -> QuerySet[Page]:+ return Page.objects.order_by("pk").select_for_update(of=(["self"]))diff --git a/saleor/page/migrations/0032_page_search_index_dirty_page_search_vector_and_more.py b/saleor/page/migrations/0032_page_search_index_dirty_page_search_vector_and_more.pynew file mode 100644index 0000000000..f9c40cf50e--- /dev/null+++ b/saleor/page/migrations/0032_page_search_index_dirty_page_search_vector_and_more.py@@ -0,0 +1,26 @@+# Generated by Django 5.2.5 on 2025-09-18 08:47++import django.contrib.postgres.indexes+import django.contrib.postgres.search+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("page", "0031_alter_page_metadata_alter_page_private_metadata_and_more"),+ ]++ operations = [+ migrations.AddField(+ model_name="page",+ name="search_index_dirty",+ field=models.BooleanField(db_default=True, default=True),+ ),+ migrations.AddField(+ model_name="page",+ name="search_vector",+ field=django.contrib.postgres.search.SearchVectorField(+ blank=True, null=True+ ),+ ),+ ]diff --git a/saleor/page/migrations/0033_page_page_tsearch.py b/saleor/page/migrations/0033_page_page_tsearch.pynew file mode 100644index 0000000000..e5b50543bc--- /dev/null+++ b/saleor/page/migrations/0033_page_page_tsearch.py@@ -0,0 +1,22 @@+# Generated by Django 5.2.5 on 2025-09-18 09:47++import django.contrib.postgres.indexes+from django.contrib.postgres.operations import AddIndexConcurrently+from django.db import migrations+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("page", "0032_page_search_index_dirty_page_search_vector_and_more"),+ ]++ operations = [+ AddIndexConcurrently(+ model_name="page",+ index=django.contrib.postgres.indexes.GinIndex(+ fields=["search_vector"], name="page_tsearch"+ ),+ ),+ ]diff --git a/saleor/page/migrations/0034_remove_page_page_page_title_964714_gin.py b/saleor/page/migrations/0034_remove_page_page_page_title_964714_gin.pynew file mode 100644index 0000000000..ddacdc445b--- /dev/null+++ b/saleor/page/migrations/0034_remove_page_page_page_title_964714_gin.py@@ -0,0 +1,19 @@+# Generated by Django 5.2.5 on 2025-10-08 11:13++from django.contrib.postgres.operations import RemoveIndexConcurrently+from django.db import migrations+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("page", "0033_page_page_tsearch"),+ ]++ operations = [+ RemoveIndexConcurrently(+ model_name="page",+ name="page_page_title_964714_gin",+ ),+ ]diff --git a/saleor/page/migrations/0035_page_page_slug_btree_idx.py b/saleor/page/migrations/0035_page_page_slug_btree_idx.pynew file mode 100644index 0000000000..7af72ebfb6--- /dev/null+++ b/saleor/page/migrations/0035_page_page_slug_btree_idx.py@@ -0,0 +1,20 @@+# Generated by Django 5.2.5 on 2025-10-08 11:14++from django.contrib.postgres.indexes import BTreeIndex+from django.contrib.postgres.operations import AddIndexConcurrently+from django.db import migrations+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("page", "0034_remove_page_page_page_title_964714_gin"),+ ]++ operations = [+ AddIndexConcurrently(+ model_name="page",+ index=BTreeIndex(fields=["slug"], name="page_slug_btree_idx"),+ ),+ ]diff --git a/saleor/page/models.py b/saleor/page/models.pyindex 3dd3dfbee3..adf56a23ee 100644--- a/saleor/page/models.py+++ b/saleor/page/models.py@@ -1,6 +1,7 @@from typing import TYPE_CHECKING, Union-from django.contrib.postgres.indexes import GinIndex+from django.contrib.postgres.indexes import BTreeIndex, GinIndex+from django.contrib.postgres.search import SearchVectorFieldfrom django.db import modelsfrom ..core.db.fields import SanitizedJSONField@@ -32,13 +33,22 @@ class Page(ModelWithMetadata, SeoModel, PublishableModel):)content = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)created_at = models.DateTimeField(auto_now_add=True, db_index=True)+ search_vector = SearchVectorField(blank=True, null=True)+ search_index_dirty = models.BooleanField(default=True, db_default=True)objects = PageManager() # type: ignore[misc]class Meta(ModelWithMetadata.Meta):ordering = ("slug",)permissions = ((PagePermissions.MANAGE_PAGES.codename, "Manage pages."),)- indexes = [*ModelWithMetadata.Meta.indexes, GinIndex(fields=["title", "slug"])]+ indexes = [+ *ModelWithMetadata.Meta.indexes,+ GinIndex(+ name="page_tsearch",+ fields=["search_vector"],+ ),+ BTreeIndex(fields=["slug"], name="page_slug_btree_idx"),+ ]def __str__(self):return self.titlediff --git a/saleor/page/search.py b/saleor/page/search.pynew file mode 100644index 0000000000..8a764c292a--- /dev/null+++ b/saleor/page/search.py@@ -0,0 +1,222 @@+from collections import defaultdict+from typing import NamedTuple++from django.conf import settings+from django.contrib.postgres.search import SearchQuery, SearchRank+from django.db import transaction+from django.db.models import F, Q, QuerySet, Value++from ..attribute.models import Attribute, AttributeValue+from ..attribute.search import get_search_vectors_for_attribute_values+from ..core.context import with_promise_context+from ..core.db.connection import allow_writer+from ..core.postgres import FlatConcatSearchVector, NoValidationSearchVector+from ..core.utils.editorjs import clean_editor_js+from ..graphql.attribute.dataloaders.assigned_attributes import (+ AttributesByPageIdAndLimitLoader,+ AttributeValuesByPageIdAndAttributeIdAndLimitLoader,+)+from ..graphql.core.context import SaleorContext+from ..graphql.page.dataloaders import PageTypeByIdLoader+from .lock_objects import page_qs_select_for_update+from .models import Page, PageType+++class AttributeValueData(NamedTuple):+ values: list[AttributeValue]+ attribute: Attribute | None+++@allow_writer()+@with_promise_context+def update_pages_search_vector(+ pages: list[Page],+ page_id_to_title_map: dict[int, str] | None = None,+) -> None:+ """Update search vector for the given pages."""+ page_type_map, page_id_to_values_map, page_id_to_title_map = _load_page_data(pages)++ # Update search vector for each page+ for page in pages:+ page_type = page_type_map[page.page_type_id]+ values_data = page_id_to_values_map[page.id]+ page.search_vector = FlatConcatSearchVector(+ *prepare_page_search_vector_value(+ page, page_type, values_data, page_id_to_title_map+ )+ )+ page.search_index_dirty = False++ # Save updates+ with transaction.atomic():+ _locked_pages = (+ page_qs_select_for_update()+ .filter(id__in=[page.id for page in pages])+ .values_list("id", flat=True)+ )+ Page.objects.bulk_update(pages, ["search_vector", "search_index_dirty"])+++def _load_page_data(+ pages: list[Page],+) -> tuple[dict[int, PageType], dict[int, list[AttributeValueData]], dict[int, str]]:+ """Load all required data for pages using dataloaders."""+ context = SaleorContext()+ page_ids = [page.id for page in pages]++ # Load page types+ page_types = (+ PageTypeByIdLoader(context)+ .load_many([page.page_type_id for page in pages])+ .get()+ )+ page_type_map = {pt.id: pt for pt in page_types if pt}++ # Load attributes and attribute values+ page_id_to_values_map, page_id_to_title_map = _load_attribute_data(+ context, page_ids+ )++ return page_type_map, page_id_to_values_map, page_id_to_title_map+++def _load_attribute_data(+ context: SaleorContext, page_ids: list[int]+) -> tuple[dict[int, list[AttributeValueData]], dict[int, str]]:+ @with_promise_context+ def load_all_data():+ # Load attributes+ attributes_promise = AttributesByPageIdAndLimitLoader(context).load_many(+ [(page_id, settings.PAGE_MAX_INDEXED_ATTRIBUTES) for page_id in page_ids]+ )++ def with_attributes(attributes):+ # Build attribute map and queries+ attribute_map = {+ attr.id: attr for page_attrs in attributes for attr in page_attrs+ }++ page_id_attribute_id_with_limit = [+ (page_id, attribute.id, settings.PAGE_MAX_INDEXED_ATTRIBUTE_VALUES)+ for page_id, attrs in zip(page_ids, attributes, strict=True)+ for attribute in attrs[: settings.PAGE_MAX_INDEXED_ATTRIBUTES]+ ]++ # Load attribute values+ attribute_values_promise = (+ AttributeValuesByPageIdAndAttributeIdAndLimitLoader(context).load_many(+ page_id_attribute_id_with_limit+ )+ )++ return attribute_values_promise.then(+ lambda attribute_values: (+ attribute_map,+ page_id_attribute_id_with_limit,+ attribute_values,+ )+ )++ return attributes_promise.then(with_attributes)++ # Execute within Promise context+ attribute_map, page_id_attribute_id_with_limit, attribute_values = load_all_data()++ # Build page to values mapping+ page_id_to_values_map = defaultdict(list)+ value_ids = []+ for values, (page_id, attr_id, _) in zip(+ attribute_values, page_id_attribute_id_with_limit, strict=True+ ):+ attribute = attribute_map.get(attr_id)+ page_id_to_values_map[page_id].append(AttributeValueData(values, attribute))+ value_ids.extend([value.id for value in values])++ page_id_to_title_map = _get_page_to_title_map(value_ids)+ return page_id_to_values_map, page_id_to_title_map+++def _get_page_to_title_map(value_ids: list[int]):+ db_conn = settings.DATABASE_CONNECTION_REPLICA_NAME+ value_to_page_id = (+ AttributeValue.objects.using(db_conn)+ .filter(id__in=value_ids, reference_page_id__isnull=False)+ .values_list("id", "reference_page_id")+ )+ page_id_to_title_map = dict(+ Page.objects.using(db_conn)+ .filter(id__in=[page_id for _, page_id in value_to_page_id])+ .values_list("id", "title")+ )+ return page_id_to_title_map+++def prepare_page_search_vector_value(+ page: Page,+ page_type: PageType,+ values_data: list[AttributeValueData],+ page_id_to_title_map: dict[int, str],+) -> list[NoValidationSearchVector]:+ """Prepare the search vector value for a page."""+ search_vectors = [+ NoValidationSearchVector(Value(page.title), config="simple", weight="A"),+ NoValidationSearchVector(Value(page.slug), config="simple", weight="A"),+ ]+ if content := page.content:+ search_vectors += [+ NoValidationSearchVector(+ Value(clean_editor_js(content, to_string=True)),+ config="simple",+ weight="A",+ )+ ]++ # add page type data+ search_vectors.extend(+ [+ NoValidationSearchVector(+ Value(page_type.name), config="simple", weight="B"+ ),+ NoValidationSearchVector(+ Value(page_type.slug), config="simple", weight="B"+ ),+ ]+ )+ search_vectors.extend(+ generate_attributes_search_vector_value(+ values_data, page_id_to_title_map=page_id_to_title_map+ )+ )+ return search_vectors+++def generate_attributes_search_vector_value(+ values_data: list[AttributeValueData],+ *,+ page_id_to_title_map: dict[int, str] | None = None,+) -> list[NoValidationSearchVector]:+ """Prepare `search_vector` value for assigned attributes.++ Method should receive assigned attributes with prefetched `values`+ """+ search_vectors = []++ for value_data in values_data:+ attribute = value_data.attribute+ values = value_data.values+ if not values or not attribute:+ continue+ search_vectors += get_search_vectors_for_attribute_values(+ attribute, values, page_id_to_title_map=page_id_to_title_map, weight="B"+ )+ return search_vectors+++def search_pages(qs: QuerySet[Page], value: str) -> QuerySet[Page]:+ if value:+ query = SearchQuery(value, search_type="websearch", config="simple")+ lookup = Q(search_vector=query)+ qs = qs.filter(lookup).annotate(+ search_rank=SearchRank(F("search_vector"), query)+ )+ return qsdiff --git a/saleor/page/tasks.py b/saleor/page/tasks.pynew file mode 100644index 0000000000..a370264013--- /dev/null+++ b/saleor/page/tasks.py@@ -0,0 +1,38 @@+from django.conf import settings+from django.db import transaction++from ..celeryconf import app+from ..core.db.connection import allow_writer+from .lock_objects import page_qs_select_for_update+from .models import Page+from .search import update_pages_search_vector++# Results in update time ~1s, consumes ~25 MB+UPDATE_SEARCH_BATCH_SIZE = 200+++@allow_writer()+def mark_pages_search_vector_as_dirty(page_ids: list[int]):+ """Mark pages as needing search index updates."""+ if not page_ids:+ return+ with transaction.atomic():+ ids = page_qs_select_for_update().filter(pk__in=page_ids).values("id")+ Page.objects.filter(id__in=ids).update(search_index_dirty=True)+++ queue=settings.UPDATE_SEARCH_VECTOR_INDEX_QUEUE_NAME,+ expires=settings.BEAT_UPDATE_SEARCH_EXPIRE_AFTER_SEC,+)+def update_pages_search_vector_task():+ pages = list(+ Page.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME).filter(+ search_index_dirty=True+ )[:UPDATE_SEARCH_BATCH_SIZE]+ )+ if not pages:+ return++ update_pages_search_vector(pages)diff --git a/saleor/page/tests/fixtures/page.py b/saleor/page/tests/fixtures/page.pyindex 22a39b7235..8bc8f81cc9 100644--- a/saleor/page/tests/fixtures/page.py+++ b/saleor/page/tests/fixtures/page.py@@ -3,6 +3,7 @@ import pytestfrom ....attribute.utils import associate_attribute_values_to_instancefrom ....tests.utils import dummy_editorjsfrom ...models import Page+from ...search import update_pages_search_vector@pytest.fixture@@ -13,6 +14,7 @@ def page(db, page_type, size_page_attribute):"content": dummy_editorjs("Test content."),"is_published": True,"page_type": page_type,+ "search_index_dirty": False,}page = Page.objects.create(**data)@@ -21,6 +23,7 @@ def page(db, page_type, size_page_attribute):associate_attribute_values_to_instance(page, {size_page_attribute.pk: [page_attr_value]})+ update_pages_search_vector([page])return pagediff --git a/saleor/page/tests/fixtures/page_type.py b/saleor/page/tests/fixtures/page_type.pyindex 2a316f5aa9..a16b42d716 100644--- a/saleor/page/tests/fixtures/page_type.py+++ b/saleor/page/tests/fixtures/page_type.py@@ -37,7 +37,7 @@ def page_type_list(db, tag_page_attribute):page_type.page_attributes.add(tag_page_attribute)Page.objects.create(title=f"Test page {i}",- slug=f"test-url-{i}",+ slug=f"test-page-{i}",is_published=True,page_type=page_type,)diff --git a/saleor/page/tests/test_search.py b/saleor/page/tests/test_search.pynew file mode 100644index 0000000000..17b0b96e07--- /dev/null+++ b/saleor/page/tests/test_search.py@@ -0,0 +1,115 @@+import pytest++from ...attribute.models import AttributeValue+from ...attribute.utils import associate_attribute_values_to_instance+from ..models import Page+from ..search import (+ update_pages_search_vector,+)+++def test_update_pages_search_vector_multiple_pages(page_list):+ """Test updating search vector for multiple pages."""+ # given+ assert all(page.search_index_dirty for page in page_list)++ # when+ update_pages_search_vector(page_list)++ # then+ for page in page_list:+ page.refresh_from_db()+ assert page.search_vector is not None+ assert page.search_index_dirty is False+++def test_update_pages_search_vector_empty_list(db):+ """Test updating search vector with empty page IDs list."""+ # given+ pages = []++ # when/then - should not raise any errors+ update_pages_search_vector(pages)+++def page_list_with_attributes(+ page_type_list,+ size_page_attribute,+ tag_page_attribute,+ page_type_product_reference_attribute,+ product_list,+):+ for page_type in page_type_list:+ page_type.page_attributes.add(+ page_type_product_reference_attribute,+ size_page_attribute,+ tag_page_attribute,+ )++ product_1, product_2, product_3 = product_list+ attribute_values = AttributeValue.objects.bulk_create(+ [+ AttributeValue(+ attribute=page_type_product_reference_attribute,+ name=f"Product {product_1.pk}",+ slug=f"product-{product_1.pk}",+ reference_product=product_1,+ ),+ AttributeValue(+ attribute=page_type_product_reference_attribute,+ name=f"Product {product_2.pk}",+ slug=f"product-{product_2.pk}",+ reference_product=product_2,+ ),+ AttributeValue(+ attribute=page_type_product_reference_attribute,+ name=f"Product {product_3.pk}",+ slug=f"product-{product_3.pk}",+ reference_product=product_3,+ ),+ ]+ )++ page_list = list(Page.objects.all())+ size_attribute_value = size_page_attribute.values.first()+ tag_attribute_value = tag_page_attribute.values.first()+ for i, page in enumerate(page_list):+ associate_attribute_values_to_instance(+ page,+ {+ page_type_product_reference_attribute.pk: [attribute_values[i]],+ size_page_attribute.pk: [size_attribute_value],+ tag_page_attribute.pk: [tag_attribute_value],+ },+ )+ return page_list+++def test_update_pages_search_vector_constant_queries(+ page_list_with_attributes, django_assert_num_queries+):+ """Ensure that data loaders are working correctly and number of db queries is constant."""+ # given+ page_list = page_list_with_attributes++ # when & then+ # Expected query breakdown (10 total):+ # 1. Load page types (1 query)+ # 2. Load page data for select_for_update (1 query)+ # 3. Load page-attribute relationships (1 query)+ # 4. Load attributes (1 query)+ # 5. Load attribute value assignments - batched (1 query)+ # 6. Load attribute values - batched (1 query)+ # 7. Load reference page titles (1 query)+ # 8. Transaction savepoint (1 query)+ # 9. Bulk update (1 query)+ # 10. Release savepoint (1 query)++ expected_queries = 10+ with django_assert_num_queries(expected_queries): # Expected number of queries+ update_pages_search_vector(page_list[: len(page_list) - 1])+ with django_assert_num_queries(+ expected_queries+ ): # Same number of queries for more pages+ update_pages_search_vector(page_list)diff --git a/saleor/page/tests/test_tasks.py b/saleor/page/tests/test_tasks.pynew file mode 100644index 0000000000..e0fc0430e1--- /dev/null+++ b/saleor/page/tests/test_tasks.py@@ -0,0 +1,48 @@+from unittest.mock import patch++from ..models import Page+from ..tasks import mark_pages_search_vector_as_dirty, update_pages_search_vector_task+++@patch("saleor.page.tasks.update_pages_search_vector")+def test_update_pages_search_vector(update_pages_search_vector_mock, page_list):+ """Test updating search vector with batch size of 1."""+ # given+ assert all(page.search_index_dirty for page in page_list)++ # when+ update_pages_search_vector_task()++ # then+ assert update_pages_search_vector_mock.called+++@patch("saleor.page.tasks.update_pages_search_vector")+def test_update_pages_search_vector_nothing_to_update(+ update_pages_search_vector_mock, page_list+):+ """Test updating search vector with batch size of 1."""+ # given+ Page.objects.all().update(search_index_dirty=False)++ # when+ update_pages_search_vector_task()++ # then+ assert not update_pages_search_vector_mock.called+++def test_mark_pages_search_vector_as_dirty(page_list):+ # given+ page_ids = [page.id for page in page_list]+ Page.objects.all().update(search_index_dirty=False)++ # when+ mark_pages_search_vector_as_dirty(page_ids)++ # then+ assert all(+ Page.objects.filter(id__in=page_ids).values_list(+ "search_index_dirty", flat=True+ )+ )diff --git a/saleor/page/tests/test_utils.py b/saleor/page/tests/test_utils.pynew file mode 100644index 0000000000..3414bbbab4--- /dev/null+++ b/saleor/page/tests/test_utils.py@@ -0,0 +1,21 @@+from unittest.mock import patch++from ..models import Page+from ..utils import mark_pages_search_vector_as_dirty_in_batches+++@patch("saleor.page.utils.MARK_SEARCH_VECTOR_DIRTY_BATCH_SIZE", 1)+def test_mark_pages_search_vector_as_dirty_in_batches(page_list):+ # given+ page_ids = [page.id for page in page_list]+ Page.objects.all().update(search_index_dirty=False)++ # when+ mark_pages_search_vector_as_dirty_in_batches(page_ids)++ # then+ assert all(+ Page.objects.filter(id__in=page_ids).values_list(+ "search_index_dirty", flat=True+ )+ )diff --git a/saleor/page/utils.py b/saleor/page/utils.pynew file mode 100644index 0000000000..c5ebfef1ab--- /dev/null+++ b/saleor/page/utils.py@@ -0,0 +1,11 @@+from .tasks import mark_pages_search_vector_as_dirty++# Results in update time ~0.2s, consumes ~30 MB+MARK_SEARCH_VECTOR_DIRTY_BATCH_SIZE = 1000+++def mark_pages_search_vector_as_dirty_in_batches(page_ids: list[int]):+ """Mark pages as needing search index updates."""+ for i in range(0, len(page_ids), MARK_SEARCH_VECTOR_DIRTY_BATCH_SIZE):+ batch_ids = page_ids[i : i + MARK_SEARCH_VECTOR_DIRTY_BATCH_SIZE]+ mark_pages_search_vector_as_dirty.delay(batch_ids)diff --git a/saleor/product/tasks.py b/saleor/product/tasks.pyindex 3e56e691d0..7a9deffb3c 100644--- a/saleor/product/tasks.py+++ b/saleor/product/tasks.py@@ -20,6 +20,7 @@ from ..plugins.manager import get_plugins_managerfrom ..warehouse.management import deactivate_preorder_for_variantfrom ..webhook.event_types import WebhookEventAsyncTypefrom ..webhook.utils import get_webhooks_for_event+from .lock_objects import product_qs_select_for_updatefrom .models import Product, ProductChannelListing, ProductType, ProductVariantfrom .search import update_products_search_vectorfrom .utils.product import mark_products_in_channels_as_dirty@@ -292,6 +293,17 @@ def _get_preorder_variants_to_clean():)+@allow_writer()+def mark_products_search_vector_as_dirty(product_ids: list[int]):+ """Mark products as needing search index updates."""+ if not product_ids:+ return+ with transaction.atomic():+ ids = product_qs_select_for_update().filter(pk__in=product_ids).values("id")+ Product.objects.filter(id__in=ids).update(search_index_dirty=True)++@app.task(queue=settings.UPDATE_SEARCH_VECTOR_INDEX_QUEUE_NAME,expires=settings.BEAT_UPDATE_SEARCH_EXPIRE_AFTER_SEC,diff --git a/saleor/product/tests/test_tasks.py b/saleor/product/tests/test_tasks.pyindex f8e1f761e8..a1b0e39e4e 100644--- a/saleor/product/tests/test_tasks.py+++ b/saleor/product/tests/test_tasks.py@@ -12,6 +12,7 @@ from ...discount.models import Promotion, PromotionRulefrom ..models import Product, ProductChannelListing, ProductVariantChannelListingfrom ..tasks import (_get_preorder_variants_to_clean,+ mark_products_search_vector_as_dirty,recalculate_discounted_price_for_products_task,update_products_search_vector_task,update_variant_relations_for_active_promotion_rules_task,@@ -318,3 +319,19 @@ def test_mem_usage_recalculate_discounted_price_for_products_task(lots_of_products_with_variants,):recalculate_discounted_price_for_products_task()+++def test_mark_products_search_vector_as_dirty(product_list):+ # given+ product_ids = [product.id for product in product_list]+ Product.objects.all().update(search_index_dirty=False)++ # when+ mark_products_search_vector_as_dirty(product_ids)++ # then+ assert all(+ Product.objects.filter(id__in=product_ids).values_list(+ "search_index_dirty", flat=True+ )+ )diff --git a/saleor/product/utils/search_helpers.py b/saleor/product/utils/search_helpers.pynew file mode 100644index 0000000000..bb5d21c0ae--- /dev/null+++ b/saleor/product/utils/search_helpers.py@@ -0,0 +1,11 @@+from ..tasks import mark_products_search_vector_as_dirty++# Results in update time ~0.2s, consumes ~30 MB+MARK_SEARCH_VECTOR_DIRTY_BATCH_SIZE = 1000+++def mark_products_search_vector_as_dirty_in_batches(product_ids: list[int]):+ """Mark products as needing search index updates."""+ for i in range(0, len(product_ids), MARK_SEARCH_VECTOR_DIRTY_BATCH_SIZE):+ batch_ids = product_ids[i : i + MARK_SEARCH_VECTOR_DIRTY_BATCH_SIZE]+ mark_products_search_vector_as_dirty.delay(batch_ids)diff --git a/saleor/settings.py b/saleor/settings.pyindex e73c9b64c2..e6c44ecb6b 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -698,6 +698,11 @@ CELERY_BEAT_SCHEDULE = {"schedule": datetime.timedelta(seconds=BEAT_UPDATE_SEARCH_SEC),"options": {"expires": BEAT_UPDATE_SEARCH_EXPIRE_AFTER_SEC},},+ "update-pages-search-vectors": {+ "task": "saleor.page.tasks.update_pages_search_vector_task",+ "schedule": datetime.timedelta(seconds=BEAT_UPDATE_SEARCH_SEC),+ "options": {"expires": BEAT_UPDATE_SEARCH_EXPIRE_AFTER_SEC},+ },"expire-orders": {"task": "saleor.order.tasks.expire_orders_task","schedule": BEAT_EXPIRE_ORDERS_AFTER_TIMEDELTA,@@ -951,6 +956,9 @@ PRODUCT_MAX_INDEXED_ATTRIBUTES = 1000PRODUCT_MAX_INDEXED_ATTRIBUTE_VALUES = 100PRODUCT_MAX_INDEXED_VARIANTS = 1000+# Maximum related objects that can be indexed in a page+PAGE_MAX_INDEXED_ATTRIBUTES = 1000+PAGE_MAX_INDEXED_ATTRIBUTE_VALUES = 100# Patch SubscriberExecutionContext class from `graphql-core-legacy` package# to fix bug causing not returning errors for subscription queries.