Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Optimize update_products_search_vector to work in batches (#9789)
Tomasz Szymański82b7b751b7ab
diff --git a/saleor/core/search_tasks.py b/saleor/core/search_tasks.pyindex 0158e5b8b5..34c20cc3cc 100644--- a/saleor/core/search_tasks.py+++ b/saleor/core/search_tasks.py@@ -15,7 +15,11 @@ from ..product.search import (task_logger = get_task_logger(__name__)-BATCH_SIZE = 1000+BATCH_SIZE = 500+# Based on local testing, 500 should be a good ballance between performance+# total time and memory usage. Should be tested after some time and adjusted by+# running the task on different thresholds and measure memory usage, total time+# and execution time of an single SQL statement.@app.taskdiff --git a/saleor/product/search.py b/saleor/product/search.pyindex 042601d2bb..86b90512d2 100644--- a/saleor/product/search.py+++ b/saleor/product/search.py@@ -24,15 +24,30 @@ PRODUCT_FIELDS_TO_PREFETCH = ["attributes__assignment__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 measureing the total time, memory usage+# and time of a single SQL statement.+def update_products_search_vector(products: "QuerySet"):- products = products.prefetch_related(*PRODUCT_FIELDS_TO_PREFETCH)- for product in products:- product.search_vector = prepare_product_search_vector_value(- product, already_prefetched=True+ last_id = 0+ while True:+ products_batch = list(+ products.order_by("id").filter(id__gt=last_id)[:PRODUCTS_BATCH_SIZE])+ if not products_batch:+ break+ last_id = products_batch[-1].id++ prefetch_related_objects(products_batch, *PRODUCT_FIELDS_TO_PREFETCH)+ for product in products_batch:+ product.search_vector = prepare_product_search_vector_value(+ product, already_prefetched=True+ )- Product.objects.bulk_update(products, ["search_vector", "updated_at"])+ Product.objects.bulk_update(products_batch, ["search_vector", "updated_at"])def update_product_search_vector(product: "Product"):