Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Prepare commands for setting search document values (#8760)
Iga Karbowiak3b2a3a081e9b
diff --git a/saleor/account/migrations/0057_user_search_document.py b/saleor/account/migrations/0057_user_search_document.pyindex 23afcbc053..e8e1a4e2e9 100644--- a/saleor/account/migrations/0057_user_search_document.py+++ b/saleor/account/migrations/0057_user_search_document.py@@ -3,53 +3,6 @@import django.contrib.postgres.indexesfrom django.db import migrations, models-BATCH_SIZE = 10000---def set_search_document(apps, schema_editor):- User = apps.get_model("account", "User")-- users = []- for user in User.objects.iterator():- user.search_document = prepare_search_document_value(user)- users.append(user)-- User.objects.bulk_update(users, ["search_document"], batch_size=BATCH_SIZE)---def prepare_search_document_value(user):- search_document = "\n".join(- [- getattr(user, field)- for field in ["email", "first_name", "last_name"]- if getattr(user, field)- ]- )- if search_document:- search_document += "\n"-- for address in user.addresses.all():- for field in [- "first_name",- "last_name",- "street_address_1",- "street_address_2",- "city",- "postal_code",- "country",- "phone",- ]:- if field == "country":- search_document += (- address.country.name + "\n" + address.country.code + "\n"- )- else:- search_document += str(getattr(address, field)) + "\n"-- search_document = search_document.lower()-- return search_document-class Migration(migrations.Migration):@@ -63,7 +16,6 @@ class Migration(migrations.Migration):name="search_document",field=models.TextField(blank=True, default=""),),- migrations.RunPython(set_search_document, migrations.RunPython.noop),migrations.RemoveIndex(model_name="user",name="user_search_gin",diff --git a/saleor/account/search.py b/saleor/account/search.pyindex a890c76db9..05b9bfdad3 100644--- a/saleor/account/search.py+++ b/saleor/account/search.py@@ -1,6 +1,6 @@from typing import TYPE_CHECKING-from django.db.models import Q+from django.db.models import Q, prefetch_related_objectsif TYPE_CHECKING:from .models import User@@ -19,7 +19,9 @@ ADDRESS_SEARCH_FIELDS = []-def prepare_user_search_document_value(user: "User", *, attach_addresses_data=True):+def prepare_user_search_document_value(+ user: "User", *, already_prefetched=False, attach_addresses_data=True+):"""Prepare `search_document` user value - attach all field used in searching.Parameter `attach_addresses_data` should be set to False only when user@@ -28,6 +30,11 @@ def prepare_user_search_document_value(user: "User", *, attach_addresses_data=Trsearch_document = generate_user_fields_search_document_value(user)if attach_addresses_data:+ if not already_prefetched:+ prefetch_related_objects(+ [user],+ "addresses",+ )for address in user.addresses.all():search_document += generate_address_search_document_value(address)diff --git a/saleor/celeryconf.py b/saleor/celeryconf.pyindex 62bff2675d..01122fc80b 100644--- a/saleor/celeryconf.py+++ b/saleor/celeryconf.py@@ -28,3 +28,4 @@ app = Celery("saleor")app.config_from_object("django.conf:settings", namespace="CELERY")app.autodiscover_tasks()app.autodiscover_tasks(lambda: discover_plugins_modules(settings.PLUGINS))+app.autodiscover_tasks(related_name="search_tasks")diff --git a/saleor/core/management/commands/set_order_search_document_values.py b/saleor/core/management/commands/set_order_search_document_values.pynew file mode 100644index 0000000000..2572645720--- /dev/null+++ b/saleor/core/management/commands/set_order_search_document_values.py@@ -0,0 +1,14 @@+from typing import Any++from django.core.management import BaseCommand++from ....order.models import Order+from ...search_tasks import set_order_search_document_values+++class Command(BaseCommand):+ help = "Used to set search document values for order."++ def handle(self, *args: Any, **options: Any):+ total_count = Order.objects.filter(search_document="").count()+ set_order_search_document_values.delay(total_count, 0)diff --git a/saleor/core/management/commands/set_user_search_document_values.py b/saleor/core/management/commands/set_user_search_document_values.pynew file mode 100644index 0000000000..df3c6d8b8d--- /dev/null+++ b/saleor/core/management/commands/set_user_search_document_values.py@@ -0,0 +1,14 @@+from typing import Any++from django.core.management import BaseCommand++from ....account.models import User+from ...search_tasks import set_user_search_document_values+++class Command(BaseCommand):+ help = "Used to set search document values for users."++ def handle(self, *args: Any, **options: Any):+ total_count = User.objects.filter(search_document="").count()+ set_user_search_document_values.delay(total_count, 0)diff --git a/saleor/core/search_tasks.py b/saleor/core/search_tasks.pynew file mode 100644index 0000000000..61816690ba--- /dev/null+++ b/saleor/core/search_tasks.py@@ -0,0 +1,77 @@+from celery.utils.log import get_task_logger++from ..account.models import User+from ..account.search import prepare_user_search_document_value+from ..celeryconf import app+from ..order.models import Order+from ..order.search import prepare_order_search_document_value++task_logger = get_task_logger(__name__)++BATCH_SIZE = 10000+++def set_user_search_document_values(total_count, updated_count):+ qs = User.objects.filter(search_document="").prefetch_related("addresses")[+ :BATCH_SIZE+ ]+ if not qs:+ task_logger.info("No users to update.")+ return+ users = []+ for user in qs:+ user.search_document = prepare_user_search_document_value(+ user, already_prefetched=True+ )+ users.append(user)+ User.objects.bulk_update(users, ["search_document"])++ updated_count += len(users)+ progress = round((updated_count / total_count) * 100, 2)++ task_logger.info(+ f"Updated {updated_count} from {total_count} users - {progress}% done."+ )++ if updated_count == total_count:+ task_logger.info("Setting user search document values finished.")+ return++ return set_user_search_document_values.delay(total_count, updated_count)+++def set_order_search_document_values(total_count, updated_count):+ qs = Order.objects.filter(search_document="").prefetch_related(+ "user",+ "billing_address",+ "shipping_address",+ "payments",+ "discounts",+ "lines",+ )[:BATCH_SIZE]+ if not qs:+ task_logger.info("No orders to update.")+ return++ orders = []+ for order in qs:+ order.search_document = prepare_order_search_document_value(+ order, already_prefetched=True+ )+ orders.append(order)+ Order.objects.bulk_update(orders, ["search_document"])++ updated_count += len(orders)+ progress = round((updated_count / total_count) * 100, 2)++ task_logger.info(+ f"Updated {updated_count} from {total_count} orders - {progress}% done."+ )++ if updated_count == total_count:+ task_logger.info("Setting order search document values finished.")+ return++ return set_order_search_document_values.delay(total_count, updated_count)diff --git a/saleor/order/migrations/0121_order_search_document.py b/saleor/order/migrations/0121_order_search_document.pyindex e84dea0ee3..44126b8a6b 100644--- a/saleor/order/migrations/0121_order_search_document.py+++ b/saleor/order/migrations/0121_order_search_document.py@@ -1,83 +1,7 @@# Generated by Django 3.2.6 on 2021-11-19 10:12import django.contrib.postgres.indexes-import graphenefrom django.db import migrations, models-BATCH_SIZE = 10000-ADDRESS_SEARCH_FIELDS = [- "first_name",- "last_name",- "street_address_1",- "street_address_2",- "city",- "postal_code",- "country",- "phone",-]---def set_search_document(apps, schema_editor):- Order = apps.get_model("order", "Order")-- orders = []- for order in Order.objects.iterator():- order.search_document = prepare_search_document_value(order)- orders.append(order)-- Order.objects.bulk_update(orders, ["search_document"], batch_size=BATCH_SIZE)---def prepare_search_document_value(order):- search_document = f"#{str(order.id)}\n"-- # attach user data- user_data = order.user_email + "\n"- if user := order.user:- user_data += "\n".join(- [- getattr(user, field)- for field in ["email", "first_name", "last_name"]- if getattr(user, field)- ]- )- user_data += "\n"- search_document += user_data-- # attach addressess data- for address_field in ["billing_address", "shipping_address"]:- if address := getattr(order, address_field):- for field in ADDRESS_SEARCH_FIELDS:- if field == "country":- search_document += (- address.country.name + "\n" + address.country.code + "\n"- )- else:- search_document += str(getattr(address, field)) + "\n"-- # attach payments data- payments_data = ""- for id, psp_reference in order.payments.values_list("id", "psp_reference"):- payments_data += graphene.Node.to_global_id("Payment", id) + "\n"- if psp_reference:- payments_data += psp_reference + "\n"-- # attach discounts data- for data in order.discounts.values_list("name", "translated_name"):- for value in data:- if value:- search_document += value + "\n"-- # attach order lines data- lines_data = "\n".join(- order.lines.exclude(product_sku__isnull=True).values_list(- "product_sku", flat=True- )- )- if lines_data:- search_document += lines_data + "\n"-- return search_document.lower()-class Migration(migrations.Migration):@@ -91,7 +15,6 @@ class Migration(migrations.Migration):name="search_document",field=models.TextField(blank=True, default=""),),- migrations.RunPython(set_search_document, migrations.RunPython.noop),migrations.RemoveIndex(model_name="order",name="order_order_user_em_bda05b_gin",diff --git a/saleor/order/search.py b/saleor/order/search.pyindex 742c621314..546fd01d50 100644--- a/saleor/order/search.py+++ b/saleor/order/search.py@@ -17,19 +17,18 @@ def update_order_search_document(order: "Order"):order.save(update_fields=["search_document"])-def prepare_order_search_document_value(order: "Order"):+def prepare_order_search_document_value(order: "Order", *, already_prefetched=False):+ if not already_prefetched:+ prefetch_related_objects(+ [order],+ "user",+ "billing_address",+ "shipping_address",+ "payments",+ "discounts",+ "lines",+ )search_document = f"#{str(order.id)}\n"-- prefetch_related_objects(- [order],- "user",- "billing_address",- "shipping_address",- "payments",- "discounts",- "lines",- )-user_data = order.user_email + "\n"if user := order.user:user_data += generate_user_fields_search_document_value(user)