Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Batches and attribute search refactor (#18216)
Iga Karbowiakaa9daadbb963
diff --git a/saleor/attribute/search.py b/saleor/attribute/search.pynew file mode 100644index 0000000000..e8e6538159--- /dev/null+++ b/saleor/attribute/search.py@@ -0,0 +1,93 @@+from typing import Union++from django.db.models import QuerySet, Value++from ..attribute import AttributeInputType+from ..core.postgres import NoValidationSearchVector+from ..core.utils.editorjs import clean_editor_js+from .models import Attribute, AttributeValue+++def get_search_vectors_for_attribute_values(+ attribute: Attribute,+ values: Union[list, "QuerySet"],+ page_id_to_title_map: dict[int, str] | None = None,+ weight: str = "B",+) -> list[NoValidationSearchVector]:+ search_vectors = []++ input_type = attribute.input_type+ if input_type in [AttributeInputType.DROPDOWN, AttributeInputType.MULTISELECT]:+ search_vectors += [+ NoValidationSearchVector(Value(value.name), config="simple", weight=weight)+ for value in values+ ]+ elif input_type == AttributeInputType.RICH_TEXT:+ search_vectors += [+ NoValidationSearchVector(+ Value(clean_editor_js(value.rich_text, to_string=True)),+ config="simple",+ weight=weight,+ )+ for value in values+ ]+ elif input_type == AttributeInputType.PLAIN_TEXT:+ search_vectors += [+ NoValidationSearchVector(+ Value(value.plain_text), config="simple", weight=weight+ )+ for value in values+ ]+ elif input_type == AttributeInputType.NUMERIC:+ unit = attribute.unit+ search_vectors += [+ NoValidationSearchVector(+ Value(value.name + " " + unit if unit else value.name),+ config="simple",+ weight=weight,+ )+ for value in values+ ]+ elif input_type in [AttributeInputType.DATE, AttributeInputType.DATE_TIME]:+ search_vectors += [+ NoValidationSearchVector(+ Value(value.date_time.strftime("%Y-%m-%d %H:%M:%S")),+ config="simple",+ weight=weight,+ )+ for value in values+ ]+ elif input_type in [+ AttributeInputType.REFERENCE,+ AttributeInputType.SINGLE_REFERENCE,+ ]:+ # for now only AttributeEntityType.PAGE is supported+ search_vectors += [+ NoValidationSearchVector(+ Value(+ get_reference_attribute_search_value(+ value, page_id_to_title_map=page_id_to_title_map+ )+ ),+ config="simple",+ weight=weight,+ )+ for value in values+ if value.reference_page_id is not None+ ]+ return search_vectors+++def get_reference_attribute_search_value(+ attribute_value: AttributeValue, page_id_to_title_map: dict[int, str] | None = None+) -> str:+ """Get search value for reference attribute."""+ if attribute_value.reference_page_id:+ if page_id_to_title_map:+ return page_id_to_title_map.get(attribute_value.reference_page_id, "")+ return (+ attribute_value.reference_page.title+ if attribute_value.reference_page+ else ""+ )+ return ""diff --git a/saleor/core/utils/batches.py b/saleor/core/utils/batches.pynew file mode 100644index 0000000000..58cf96e530--- /dev/null+++ b/saleor/core/utils/batches.py@@ -0,0 +1,17 @@+from django.db.models import QuerySet+++def queryset_in_batches(queryset: QuerySet, batch_size: int):+ """Slice a queryset into batches."""+ start_pk = 0++ while True:+ qs = queryset.filter(pk__gt=start_pk).order_by("pk")[:batch_size]+ pks = list(qs.values_list("pk", flat=True))++ if not pks:+ break++ yield pks++ start_pk = pks[-1]diff --git a/saleor/csv/utils/export.py b/saleor/csv/utils/export.pyindex 69d7f69842..cf6d276269 100644--- a/saleor/csv/utils/export.py+++ b/saleor/csv/utils/export.py@@ -8,6 +8,7 @@ from django.conf import settingsfrom django.utils import timezonefrom ...core.db.connection import allow_writer+from ...core.utils.batches import queryset_in_batchesfrom ...discount.models import VoucherCodefrom ...giftcard.models import GiftCardfrom ...product.models import Product@@ -201,7 +202,7 @@ def export_products_in_batches(attributes = export_info.get("attributes")channels = export_info.get("channels")- for batch_pks in queryset_in_batches(queryset):+ for batch_pks in queryset_in_batches(queryset, BATCH_SIZE):product_batch = (Product.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME).filter(pk__in=batch_pks)@@ -228,7 +229,7 @@ def export_gift_cards_in_batches(temporary_file: Any,file_type: str,):- for batch_pks in queryset_in_batches(queryset):+ for batch_pks in queryset_in_batches(queryset, BATCH_SIZE):gift_card_batch = GiftCard.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME).filter(pk__in=batch_pks)@@ -245,7 +246,7 @@ def export_voucher_codes_in_batches(temporary_file: Any,file_type: str,):- for batch_pks in queryset_in_batches(queryset):+ for batch_pks in queryset_in_batches(queryset, BATCH_SIZE):voucher_codes_batch = VoucherCode.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME).filter(pk__in=batch_pks)@@ -255,25 +256,6 @@ def export_voucher_codes_in_batches(append_to_file(export_data, export_fields, temporary_file, file_type, delimiter)-def queryset_in_batches(queryset):- """Slice a queryset into batches.-- Input queryset should be sorted be pk.- """- start_pk = 0-- while True:- qs = queryset.order_by("pk").filter(pk__gt=start_pk)[:BATCH_SIZE]- pks = list(qs.values_list("pk", flat=True))-- if not pks:- break-- yield pks-- start_pk = pks[-1]--def append_to_file(export_data: list[dict[str, str | bool]],headers: list[str],diff --git a/saleor/graphql/attribute/mutations/attribute_value_update.py b/saleor/graphql/attribute/mutations/attribute_value_update.pyindex 4cd317f325..86fff7bbd9 100644--- a/saleor/graphql/attribute/mutations/attribute_value_update.py+++ b/saleor/graphql/attribute/mutations/attribute_value_update.py@@ -3,8 +3,10 @@ from django.db import transactionfrom django.db.models import Exists, OuterRef, Qfrom ....attribute import models as models+from ....core.utils.batches import queryset_in_batchesfrom ....permission.enums import ProductTypePermissionsfrom ....product import models as product_models+from ....product.lock_objects import product_qs_select_for_updatefrom ....webhook.event_types import WebhookEventAsyncTypefrom ...core import ResolveInfofrom ...core.context import ChannelContext@@ -16,26 +18,7 @@ from ..types import Attribute, AttributeValuefrom .attribute_update import AttributeValueUpdateInputfrom .attribute_value_create import AttributeValueCreate-PRODUCTS_BATCH_SIZE = 10000---def queryset_in_batches(queryset):- """Slice a queryset into batches.-- Input queryset should be sorted be pk.- """- start_pk = 0-- while True:- qs = queryset.filter(pk__gt=start_pk)[:PRODUCTS_BATCH_SIZE]- pks = list(qs.values_list("pk", flat=True))-- if not pks:- break-- yield pks-- start_pk = pks[-1]+BATCH_SIZE = 10000class AttributeValueUpdate(AttributeValueCreate, ModelWithExtRefMutation):@@ -94,35 +77,36 @@ class AttributeValueUpdate(AttributeValueCreate, ModelWithExtRefMutation):@classmethoddef post_save_action(cls, info: ResolveInfo, instance, cleaned_input):- with transaction.atomic():- variants = product_models.ProductVariant.objects.filter(- Exists(instance.variantassignments.filter(variant_id=OuterRef("id")))- )- # SELECT … FOR UPDATE needs to lock rows in a consistent order- # to avoid deadlocks between updates touching the same rows.+ cls.mark_search_index_dirty(instance)+ manager = get_plugin_manager_promise(info.context).get()+ cls.call_event(manager.attribute_value_updated, instance)+ cls.call_event(manager.attribute_updated, instance.attribute)- qs = (- product_models.Product.objects.select_for_update(of=("self",))- .filter(- Q(search_index_dirty=False)- & (- Q(- Exists(- instance.productvalueassignment.filter(- product_id=OuterRef("id")- )- )+ @classmethod+ def mark_search_index_dirty(cls, instance):+ variants = product_models.ProductVariant.objects.filter(+ Exists(instance.variantassignments.filter(variant_id=OuterRef("id")))+ )+ products = product_models.Product.objects.filter(+ Q(search_index_dirty=False)+ & (+ Q(+ Exists(+ instance.productvalueassignment.filter(+ product_id=OuterRef("id"))- | Q(Exists(variants.filter(product_id=OuterRef("id"))))))- .order_by("pk")+ | Q(Exists(variants.filter(product_id=OuterRef("id")))))- for batch_pks in queryset_in_batches(qs):+ ).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)-- manager = get_plugin_manager_promise(info.context).get()- cls.call_event(manager.attribute_value_updated, instance)- cls.call_event(manager.attribute_updated, instance.attribute)diff --git a/saleor/product/search.py b/saleor/product/search.pyindex 677462b289..be041c43f7 100644--- a/saleor/product/search.py+++ b/saleor/product/search.py@@ -1,15 +1,15 @@from collections import defaultdictfrom collections.abc import Iterable-from typing import TYPE_CHECKING, Union+from typing import TYPE_CHECKINGfrom django.conf import settingsfrom django.contrib.postgres.search import SearchQuery, SearchRankfrom django.db.models import F, Q, Value, prefetch_related_objects-from ..attribute import AttributeInputType-from ..attribute.models import AssignedProductAttributeValue, Attribute, AttributeValue+from ..attribute.models import AssignedProductAttributeValue, AttributeValue+from ..attribute.search import get_search_vectors_for_attribute_valuesfrom ..core.postgres import FlatConcatSearchVector, NoValidationSearchVector-from ..core.utils.editorjs import clean_editor_js+from ..core.utils.batches import queryset_in_batchesfrom ..page.models import Pagefrom ..product.models import Product@@ -50,30 +50,11 @@ def _prep_product_search_vector_index()-def queryset_in_batches(queryset):- """Slice a queryset into batches.-- Input queryset should be sorted be pk.- """- start_pk = 0-- while True:- qs = queryset.filter(pk__gt=start_pk)[:PRODUCTS_BATCH_SIZE]- pks = list(qs.values_list("pk", flat=True))-- if not pks:- break-- yield pks-- start_pk = pks[-1]--def update_products_search_vector(product_ids: Iterable[int]):db_conn = settings.DATABASE_CONNECTION_REPLICA_NAMEproduct_ids = list(product_ids)products = Product.objects.using(db_conn).filter(pk__in=product_ids).order_by("pk")- for product_pks in queryset_in_batches(products):+ for product_pks in queryset_in_batches(products, PRODUCTS_BATCH_SIZE):value_ids = (AssignedProductAttributeValue.objects.using(db_conn).filter(product_id__in=product_pks)@@ -166,8 +147,8 @@ def generate_attributes_search_vector_value(: settings.PRODUCT_MAX_INDEXED_ATTRIBUTE_VALUES]- search_vectors += get_search_vectors_for_values(- attribute, values, page_id_to_title_map=page_id_to_title_map+ 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@@ -186,92 +167,10 @@ def generate_attributes_search_vector_value_with_assignment(values = assigned_attribute.values.all()[: settings.PRODUCT_MAX_INDEXED_ATTRIBUTE_VALUES]- search_vectors += get_search_vectors_for_values(attribute, values)- return search_vectors---def get_search_vectors_for_values(- attribute: Attribute,- values: Union[list, "QuerySet"],- page_id_to_title_map: dict[int, str] | None = None,-) -> list[NoValidationSearchVector]:- search_vectors = []-- input_type = attribute.input_type- if input_type in [AttributeInputType.DROPDOWN, AttributeInputType.MULTISELECT]:- search_vectors += [- NoValidationSearchVector(Value(value.name), config="simple", weight="B")- for value in values- ]- elif input_type == AttributeInputType.RICH_TEXT:- search_vectors += [- NoValidationSearchVector(- Value(clean_editor_js(value.rich_text, to_string=True)),- config="simple",- weight="B",- )- for value in values- ]- elif input_type == AttributeInputType.PLAIN_TEXT:- search_vectors += [- NoValidationSearchVector(- Value(value.plain_text), config="simple", weight="B"- )- for value in values- ]- elif input_type == AttributeInputType.NUMERIC:- unit = attribute.unit- search_vectors += [- NoValidationSearchVector(- Value(value.name + " " + unit if unit else value.name),- config="simple",- weight="B",- )- for value in values- ]- elif input_type in [AttributeInputType.DATE, AttributeInputType.DATE_TIME]:- search_vectors += [- NoValidationSearchVector(- Value(value.date_time.strftime("%Y-%m-%d %H:%M:%S")),- config="simple",- weight="B",- )- for value in values- ]- elif input_type in [- AttributeInputType.REFERENCE,- AttributeInputType.SINGLE_REFERENCE,- ]:- # for now only AttributeEntityType.PAGE is supported- search_vectors += [- NoValidationSearchVector(- Value(- get_reference_attribute_search_value(- value, page_id_to_title_map=page_id_to_title_map- )- ),- config="simple",- weight="B",- )- for value in values- if value.reference_page_id is not None- ]- return search_vectors---def get_reference_attribute_search_value(- attribute_value: AttributeValue, page_id_to_title_map: dict[int, str] | None = None-) -> str:- """Get search value for reference attribute."""- if attribute_value.reference_page_id:- if page_id_to_title_map:- return page_id_to_title_map.get(attribute_value.reference_page_id, "")- return (- attribute_value.reference_page.title- if attribute_value.reference_page- else ""+ search_vectors += get_search_vectors_for_attribute_values(+ attribute, values, weight="B")- return ""+ return search_vectorsdef search_products(qs, value):