Skip to content

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

Improve the perfomance of update products search vector task (#15516)

Maciej Korycinskif6854b51135f
diff --git a/saleor/core/utils/editorjs.py b/saleor/core/utils/editorjs.py
index 24d2df5222..5eea977500 100644
--- a/saleor/core/utils/editorjs.py
+++ b/saleor/core/utils/editorjs.py
@@ -66,10 +66,10 @@ def clean_list_item(blocks, block, plain_text_list, to_string, index):
for item_index, item in enumerate(block["data"]["items"]):
if not item:
return
- new_text = clean_text_data(item)
if to_string:
- plain_text_list.append(strip_tags(new_text))
+ plain_text_list.append(strip_tags(item))
else:
+ new_text = clean_text_data_block(item)
blocks[index]["data"]["items"][item_index] = new_text
@@ -77,16 +77,16 @@ def clean_image_item(blocks, block, plain_text_list, to_string, index):
file_url = block["data"].get("file", {}).get("url")
caption = block["data"].get("caption")
if file_url:
- file_url = clean_text_data(file_url)
if to_string:
plain_text_list.append(strip_tags(file_url))
else:
+ file_url = clean_text_data_block(file_url)
blocks[index]["data"]["file"]["ulr"] = file_url
if caption:
- caption = clean_text_data(caption)
if to_string:
plain_text_list.append(strip_tags(caption))
else:
+ caption = clean_text_data_block(caption)
blocks[index]["data"]["caption"] = caption
@@ -95,25 +95,31 @@ def clean_embed_item(blocks, block, plain_text_list, to_string, index):
data = block["data"].get(field)
if not data:
return
- data = clean_text_data(data)
if to_string:
plain_text_list.append(strip_tags(data))
else:
+ data = clean_text_data_block(data)
blocks[index]["data"][field] = data
-def clean_other_items(blocks, block, plain_text_list, to_string, index):
+def clean_other_items(
+ blocks,
+ block,
+ plain_text_list,
+ to_string,
+ index,
+):
text = block["data"].get("text")
if not text:
return
- new_text = clean_text_data(text)
if to_string:
- plain_text_list.append(strip_tags(new_text))
+ plain_text_list.append(strip_tags(text))
else:
+ new_text = clean_text_data_block(text)
blocks[index]["data"]["text"] = new_text
-def clean_text_data(text: str) -> str:
+def clean_text_data_block(text: str) -> str:
"""Look for url in text, check if URL is allowed and return the cleaned URL.
By default, only the protocol ``javascript`` is denied.
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index ef4927ff30..720d23e876 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -455,7 +455,7 @@ def create_products_by_schema(placeholder_dir, create_images):
assign_products_to_collections(associations=types["product.collectionproduct"])
all_products_qs = Product.objects.all()
- update_products_search_vector(all_products_qs)
+ update_products_search_vector(all_products_qs.values_list("id", flat=True))
class SaleorProvider(BaseProvider):
diff --git a/saleor/product/search.py b/saleor/product/search.py
index c763cb675f..a86132144f 100644
--- a/saleor/product/search.py
+++ b/saleor/product/search.py
@@ -1,20 +1,16 @@
from collections import defaultdict
+from collections.abc import Iterable
from typing import TYPE_CHECKING, Union
from django.conf import settings
from django.contrib.postgres.search import SearchQuery, SearchRank
from django.db.models import F, Q, Value, prefetch_related_objects
-from django.db.models.expressions import Exists, OuterRef
from ..attribute import AttributeInputType
-from ..attribute.models import (
- AssignedProductAttributeValue,
- Attribute,
- AttributeProduct,
-)
+from ..attribute.models import Attribute
from ..core.postgres import FlatConcatSearchVector, NoValidationSearchVector
from ..core.utils.editorjs import clean_editor_js
-from .models import Product
+from ..product.models import Product
if TYPE_CHECKING:
from django.db.models import QuerySet
@@ -22,20 +18,20 @@ if TYPE_CHECKING:
PRODUCT_SEARCH_FIELDS = ["name", "description_plaintext"]
PRODUCT_FIELDS_TO_PREFETCH = [
"variants__attributes__values",
- "variants__attributes",
+ "variants__attributes__assignment__attribute",
"attributevalues__value",
"product_type__attributeproduct__attribute",
]
-PRODUCTS_BATCH_SIZE = 300
-# Setting threshold to 300 results in about 350MB of memory usage
-# when testing locally. Should be adjusted after some time by running
-# update task on a large dataset and measuring the total time, memory usage
-# and time of a single SQL statement.
+PRODUCTS_BATCH_SIZE = 100
+# Setting threshold to 100 results in about 766.98MB of memory usage
+# when testing locally with multiple attributes of different types assigned to product
+# and product variants.
def _prep_product_search_vector_index(products):
prefetch_related_objects(products, *PRODUCT_FIELDS_TO_PREFETCH)
+
for product in products:
product.search_vector = FlatConcatSearchVector(
*prepare_product_search_vector_value(product, already_prefetched=True)
@@ -47,17 +43,39 @@ def _prep_product_search_vector_index(products):
)
-def update_products_search_vector(products: "QuerySet", use_batches=True):
- if use_batches:
- last_id = 0
- while True:
- products_batch = list(products.filter(id__gt=last_id)[:PRODUCTS_BATCH_SIZE])
- if not products_batch:
- break
- last_id = products_batch[-1].id
- _prep_product_search_vector_index(products_batch)
- else:
- _prep_product_search_vector_index(products)
+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]):
+ product_ids = list(product_ids)
+ products = (
+ Product.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ .filter(pk__in=product_ids)
+ .order_by("pk")
+ )
+ for product_pks in queryset_in_batches(products):
+ products_batch = list(
+ Product.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME).filter(
+ id__in=product_pks
+ )
+ )
+ _prep_product_search_vector_index(products_batch)
def prepare_product_search_vector_value(
@@ -108,19 +126,14 @@ def generate_attributes_search_vector_value(
Method should receive assigned attributes with prefetched `values`
"""
- product_attributes = AttributeProduct.objects.filter(
- product_type_id=product.product_type_id
- )
- attributes = Attribute.objects.filter(
- Exists(product_attributes.filter(attribute_id=OuterRef("id")))
- ).order_by("attributeproduct__sort_order")[
- : settings.PRODUCT_MAX_INDEXED_ATTRIBUTES
- ]
+ product_attributes = product.product_type.attributeproduct.all()
- assigned_values = AssignedProductAttributeValue.objects.filter(
- product_id=product.pk
- )
- prefetch_related_objects(assigned_values, "value")
+ attributes = []
+ for product_attribute in product_attributes:
+ attributes.append(product_attribute.attribute) # type: ignore
+ attributes = attributes[: settings.PRODUCT_MAX_INDEXED_ATTRIBUTES]
+
+ assigned_values = product.attributevalues.all()
search_vectors = []
diff --git a/saleor/product/tasks.py b/saleor/product/tasks.py
index 9a3065a98c..1d0e3daf3d 100644
--- a/saleor/product/tasks.py
+++ b/saleor/product/tasks.py
@@ -21,7 +21,7 @@ from ..warehouse.management import deactivate_preorder_for_variant
from ..webhook.event_types import WebhookEventAsyncType
from ..webhook.utils import get_webhooks_for_event
from .models import Product, ProductChannelListing, ProductType, ProductVariant
-from .search import PRODUCTS_BATCH_SIZE, update_products_search_vector
+from .search import update_products_search_vector
from .utils.product import mark_products_in_channels_as_dirty
from .utils.variant_prices import update_discounted_prices_for_promotion
from .utils.variants import (
@@ -32,6 +32,8 @@ from .utils.variants import (
logger = logging.getLogger(__name__)
task_logger = get_task_logger(__name__)
+PRODUCTS_BATCH_SIZE = 300
+
VARIANTS_UPDATE_BATCH = 500
# Results in update time ~0.2s
DISCOUNTED_PRODUCT_BATCH = 2000
@@ -265,10 +267,13 @@ def _get_preorder_variants_to_clean():
expires=settings.BEAT_UPDATE_SEARCH_EXPIRE_AFTER_SEC,
)
def update_products_search_vector_task():
- products = Product.objects.filter(search_index_dirty=True).order_by()[
- :PRODUCTS_BATCH_SIZE
- ]
- update_products_search_vector(products, use_batches=False)
+ products = (
+ Product.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ .filter(search_index_dirty=True)
+ .order_by("updated_at")[:PRODUCTS_BATCH_SIZE]
+ .values_list("id", flat=True)
+ )
+ update_products_search_vector(products)
@app.task(queue=settings.COLLECTION_PRODUCT_UPDATED_QUEUE_NAME)
diff --git a/saleor/product/tests/test_product_search.py b/saleor/product/tests/test_product_search.py
index e4356266fd..a90f6f080c 100644
--- a/saleor/product/tests/test_product_search.py
+++ b/saleor/product/tests/test_product_search.py
@@ -9,7 +9,7 @@ def test_update_products_search_vector(product_list):
Product.objects.bulk_update(product_list, ["search_vector"])
# when
- update_products_search_vector(Product.objects.all())
+ update_products_search_vector(Product.objects.all().values_list("id", flat=True))
# then
for product in product_list:
diff --git a/saleor/product/tests/test_tasks.py b/saleor/product/tests/test_tasks.py
index c2bf54b993..6238e8a078 100644
--- a/saleor/product/tests/test_tasks.py
+++ b/saleor/product/tests/test_tasks.py
@@ -291,6 +291,22 @@ def test_update_products_search_vector_task(product):
assert product.search_index_dirty is False
[email protected]("dirty_products_number", [0, 1, 2, 3])
+def test_update_products_search_vector_task_with_static_number_of_queries(
+ product, product_list, dirty_products_number, django_assert_num_queries
+):
+ # given
+ product.search_index_dirty = True
+ product.save()
+ for i in range(dirty_products_number):
+ product_list[i].search_index_dirty = True
+ product_list[i].save(update_fields=["search_index_dirty"])
+
+ # when & # then
+ with django_assert_num_queries(15):
+ update_products_search_vector_task()
+
+
@pytest.mark.slow
@pytest.mark.limit_memory("50 MB")
def test_mem_usage_recalculate_discounted_price_for_products_task(