Skip to content

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

Orders filtering optimization (#7306)

Filip Owczarekef71db924bca
diff --git a/saleor/account/migrations/0050_auto_20210506_1058.py b/saleor/account/migrations/0050_auto_20210506_1058.py
new file mode 100644
index 0000000000..d5bd70d4f8
--- /dev/null
+++ b/saleor/account/migrations/0050_auto_20210506_1058.py
@@ -0,0 +1,21 @@
+# Generated by Django 3.1.8 on 2021-05-06 10:58
+
+import django.contrib.postgres.indexes
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("account", "0049_user_language_code"),
+ ]
+
+ operations = [
+ migrations.AddIndex(
+ model_name="user",
+ index=django.contrib.postgres.indexes.GinIndex(
+ fields=["email", "first_name", "last_name"],
+ name="account_use_email_d707ff_gin",
+ ),
+ ),
+ ]
diff --git a/saleor/account/models.py b/saleor/account/models.py
index 65469ce536..28f2a95afa 100644
--- a/saleor/account/models.py
+++ b/saleor/account/models.py
@@ -8,6 +8,7 @@ from django.contrib.auth.models import (
Permission,
PermissionsMixin,
)
+from django.contrib.postgres.indexes import GinIndex
from django.db import models
from django.db.models import JSONField # type: ignore
from django.db.models import Q, QuerySet, Value
@@ -160,12 +161,17 @@ class User(PermissionsMixin, ModelWithMetadata, AbstractBaseUser):
objects = UserManager()
- class Meta(ModelWithMetadata.Meta):
+ class Meta:
ordering = ("email",)
permissions = (
(AccountPermissions.MANAGE_USERS.codename, "Manage customers."),
(AccountPermissions.MANAGE_STAFF.codename, "Manage staff."),
)
+ indexes = [
+ *ModelWithMetadata.Meta.indexes,
+ # Orders searching index
+ GinIndex(fields=["email", "first_name", "last_name"]),
+ ]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
diff --git a/saleor/discount/migrations/0025_auto_20210506_0831.py b/saleor/discount/migrations/0025_auto_20210506_0831.py
new file mode 100644
index 0000000000..051bf13eb6
--- /dev/null
+++ b/saleor/discount/migrations/0025_auto_20210506_0831.py
@@ -0,0 +1,20 @@
+# Generated by Django 3.1.8 on 2021-05-06 08:31
+
+import django.contrib.postgres.indexes
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("discount", "0024_orderdiscount"),
+ ]
+
+ operations = [
+ migrations.AddIndex(
+ model_name="orderdiscount",
+ index=django.contrib.postgres.indexes.GinIndex(
+ fields=["name", "translated_name"], name="discount_or_name_d16858_gin"
+ ),
+ ),
+ ]
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
index 0aa8e65f88..25af832313 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -2,6 +2,7 @@ from decimal import Decimal
from functools import partial
from django.conf import settings
+from django.contrib.postgres.indexes import GinIndex
from django.db import models
from django.db.models import F, Q
from django.utils import timezone
@@ -346,3 +347,7 @@ class OrderDiscount(models.Model):
name = models.CharField(max_length=255, null=True, blank=True)
translated_name = models.CharField(max_length=255, null=True, blank=True)
reason = models.TextField(blank=True, null=True)
+
+ class Meta:
+ # Orders searching index
+ indexes = [GinIndex(fields=["name", "translated_name"])]
diff --git a/saleor/graphql/order/filters.py b/saleor/graphql/order/filters.py
index 2e690635c3..90a6193410 100644
--- a/saleor/graphql/order/filters.py
+++ b/saleor/graphql/order/filters.py
@@ -1,15 +1,17 @@
import django_filters
-from django.db.models import Sum
+from django.db.models import Exists, OuterRef, Q, Sum
from graphene_django.filter import GlobalIDMultipleChoiceFilter
+from ...discount.models import OrderDiscount
from ...order.models import Order
+from ...payment.models import Payment, Transaction
from ..channel.types import Channel
from ..core.filters import ListObjectTypeFilter, MetadataFilterBase, ObjectTypeFilter
from ..core.types.common import DateRangeInput
from ..core.utils import from_global_id_or_error
from ..payment.enums import PaymentChargeStatusEnum
from ..utils import resolve_global_ids_to_primary_keys
-from ..utils.filters import filter_by_query_param, filter_range_field
+from ..utils.filters import filter_range_field
from .enums import OrderStatusFilter
@@ -26,6 +28,12 @@ def get_payment_id_from_query(value):
return None
+def get_order_id_from_query(value):
+ if value.startswith("#"):
+ value = value[1:]
+ return value if value.isnumeric() else None
+
+
def filter_order_by_payment(qs, payment_id):
if payment_id:
qs = qs.filter(payments__pk=payment_id)
@@ -51,13 +59,12 @@ def filter_status(qs, _, value):
def filter_customer(qs, _, value):
- customer_fields = [
- "user_email",
- "user__first_name",
- "user__last_name",
- "user__email",
- ]
- qs = filter_by_query_param(qs, value, customer_fields)
+ qs = qs.filter(
+ Q(user_email__trigram_similar=value)
+ | Q(user__email__trigram_similar=value)
+ | Q(user__first_name__trigram_similar=value)
+ | Q(user__last_name__trigram_similar=value)
+ )
return qs
@@ -66,21 +73,27 @@ def filter_created_range(qs, _, value):
def filter_order_search(qs, _, value):
- order_fields = [
- "pk",
- "discounts__name",
- "discounts__translated_name",
- "user_email",
- "user__first_name",
- "user__last_name",
- "payments__transactions__searchable_key",
- ]
- payment_id = get_payment_id_from_query(value)
- if payment_id:
+ if payment_id := get_payment_id_from_query(value):
return filter_order_by_payment(qs, payment_id)
- qs = filter_by_query_param(qs, value, order_fields)
- return qs
+ if order_id := get_order_id_from_query(value):
+ return qs.filter(pk=order_id)
+
+ transactions = Transaction.objects.filter(searchable_key=value).values("id")
+ payments = Payment.objects.filter(
+ Exists(transactions.filter(payment_id=OuterRef("id")))
+ ).values("id")
+ discounts = OrderDiscount.objects.filter(
+ Q(name__trigram_similar=value) | Q(translated_name__trigram_similar=value)
+ ).values("id")
+ return qs.filter(
+ Q(user_email__trigram_similar=value)
+ | Q(Exists(discounts.filter(order_id=OuterRef("id"))))
+ | Q(user__email__trigram_similar=value)
+ | Q(user__first_name__trigram_similar=value)
+ | Q(user__last_name__trigram_similar=value)
+ | Q(Exists(payments.filter(order_id=OuterRef("id"))))
+ )
def filter_channels(qs, _, values):
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index 79fbc95d22..e7323d75ae 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -5488,12 +5488,11 @@ def test_query_draft_orders_with_sort(
@pytest.mark.parametrize(
"orders_filter, count",
[
- ({"search": "test_discount"}, 2),
- ({"search": "test_discount1"}, 1),
- ({"search": "translated_discount1_name"}, 1),
- ({"search": "user"}, 2),
- ({"search": "[email protected]"}, 1),
- ({"search": "[email protected]"}, 1),
+ ({"search": "discount name"}, 2),
+ ({"search": "Some other"}, 1),
+ ({"search": "translated"}, 1),
+ ({"search": "user_email"}, 2),
+ ({"search": "[email protected]"}, 1),
({"search": "Leslie"}, 1),
({"search": "Wade"}, 1),
({"search": ""}, 3),
@@ -5514,17 +5513,17 @@ def test_orders_query_with_filter_search(
Order(
user=customer_user,
token=str(uuid.uuid4()),
- user_email="[email protected]",
+ user_email="[email protected]",
channel=channel_USD,
),
Order(
token=str(uuid.uuid4()),
- user_email="[email protected]",
+ user_email="[email protected]",
channel=channel_USD,
),
Order(
token=str(uuid.uuid4()),
- user_email="[email protected]",
+ user_email="[email protected]",
channel=channel_USD,
),
]
@@ -5534,17 +5533,17 @@ def test_orders_query_with_filter_search(
[
OrderDiscount(
order=orders[0],
- name="test_discount1",
+ name="Some discount name",
value=Decimal("1"),
amount_value=Decimal("1"),
- translated_name="translated_discount1_name",
+ translated_name="translated",
),
OrderDiscount(
order=orders[2],
- name="test_discount2",
+ name="Some other discount name",
value=Decimal("10"),
amount_value=Decimal("10"),
- translated_name="translated_discount2_name",
+ translated_name="PL_name",
),
]
)
@@ -5612,15 +5611,24 @@ def test_orders_query_with_filter_search_by_id(
assert content["data"]["orders"]["totalCount"] == 1
+def test_orders_query_with_filter_search_by_id_with_hash(
+ orders_query_with_filter, order, staff_api_client, permission_manage_orders
+):
+ variables = {"filter": {"search": f"#{order.pk}"}}
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["orders"]["totalCount"] == 1
+
+
@pytest.mark.parametrize(
"draft_orders_filter, count",
[
- ({"search": "test_discount"}, 2),
- ({"search": "test_discount1"}, 1),
- ({"search": "translated_discount1_name"}, 1),
- ({"search": "user"}, 2),
- ({"search": "[email protected]"}, 1),
- ({"search": "[email protected]"}, 1),
+ ({"search": "discount name"}, 2),
+ ({"search": "Some other"}, 1),
+ ({"search": "translated"}, 1),
+ ({"search": "user_email"}, 2),
+ ({"search": "[email protected]"}, 1),
({"search": "Leslie"}, 1),
({"search": "Wade"}, 1),
({"search": ""}, 3),
@@ -5640,19 +5648,19 @@ def test_draft_orders_query_with_filter_search(
Order(
user=customer_user,
token=str(uuid.uuid4()),
- user_email="[email protected]",
+ user_email="[email protected]",
status=OrderStatus.DRAFT,
channel=channel_USD,
),
Order(
token=str(uuid.uuid4()),
- user_email="[email protected]",
+ user_email="[email protected]",
status=OrderStatus.DRAFT,
channel=channel_USD,
),
Order(
token=str(uuid.uuid4()),
- user_email="[email protected]",
+ user_email="[email protected]",
status=OrderStatus.DRAFT,
channel=channel_USD,
),
@@ -5662,17 +5670,17 @@ def test_draft_orders_query_with_filter_search(
[
OrderDiscount(
order=orders[0],
- name="test_discount1",
+ name="Some discount name",
value=Decimal("1"),
amount_value=Decimal("1"),
- translated_name="translated_discount1_name",
+ translated_name="translated",
),
OrderDiscount(
order=orders[2],
- name="test_discount2",
+ name="Some other discount name",
value=Decimal("10"),
amount_value=Decimal("10"),
- translated_name="translated_discount2_name",
+ translated_name="PL_name",
),
]
)
@@ -5696,6 +5704,19 @@ def test_draft_orders_query_with_filter_search_by_id(
assert content["data"]["draftOrders"]["totalCount"] == 1
+def test_draft_orders_query_with_filter_search_by_id_with_hash(
+ draft_orders_query_with_filter,
+ draft_order,
+ staff_api_client,
+ permission_manage_orders,
+):
+ variables = {"filter": {"search": f"#{draft_order.pk}"}}
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(draft_orders_query_with_filter, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["draftOrders"]["totalCount"] == 1
+
+
QUERY_GET_VARIANTS_FROM_ORDER = """
{
me{
diff --git a/saleor/graphql/order/tests/test_pagination.py b/saleor/graphql/order/tests/test_pagination.py
index 6d8b53d8f7..1810761141 100644
--- a/saleor/graphql/order/tests/test_pagination.py
+++ b/saleor/graphql/order/tests/test_pagination.py
@@ -395,12 +395,11 @@ def test_draft_order_query_pagination_with_filter_created(
@pytest.mark.parametrize(
"orders_filter, expected_total_count, orders_order",
[
- ({"search": "test_discount"}, 2, [0.0, 0.0]),
- ({"search": "test_discount1"}, 1, [0.0]),
- ({"search": "translated_discount1_name"}, 1, [0.0]),
- ({"search": "user"}, 2, [0.0, 0.0]),
- ({"search": "[email protected]"}, 1, [0.0]),
- ({"search": "[email protected]"}, 1, [0.0]),
+ ({"search": "discount name"}, 2, [0.0, 0.0]),
+ ({"search": "Some other"}, 1, [0.0]),
+ ({"search": "translated"}, 1, [0.0]),
+ ({"search": "user_email"}, 2, [0.0, 0.0]),
+ ({"search": "[email protected]"}, 1, [0.0]),
({"search": "Leslie"}, 1, [0.0]),
({"search": "Wade"}, 1, [0.0]),
({"search": ""}, 6, [0.0, 0.0]),
@@ -421,17 +420,17 @@ def test_orders_query_pagination_with_filter_search(
Order(
user=customer_user,
token=str(uuid.uuid4()),
- user_email="[email protected]",
+ user_email="[email protected]",
channel=channel_USD,
),
Order(
token=str(uuid.uuid4()),
- user_email="[email protected]",
+ user_email="[email protected]",
channel=channel_USD,
),
Order(
token=str(uuid.uuid4()),
- user_email="[email protected]",
+ user_email="[email protected]",
channel=channel_USD,
),
]
@@ -440,17 +439,17 @@ def test_orders_query_pagination_with_filter_search(
[
OrderDiscount(
order=orders[0],
- name="test_discount1",
+ name="Some discount name",
value=Decimal("1"),
amount_value=Decimal("1"),
- translated_name="translated_discount1_name",
+ translated_name="translated",
),
OrderDiscount(
order=orders[2],
- name="test_discount2",
+ name="Some other discount name",
value=Decimal("10"),
amount_value=Decimal("10"),
- translated_name="translated_discount2_name",
+ translated_name="PL_name",
),
]
)
@@ -468,26 +467,14 @@ def test_orders_query_pagination_with_filter_search(
assert orders[i]["node"]["total"]["gross"]["amount"] == orders_order[i]
-def test_orders_query_pagination_with_filter_search_by_id(
- order, staff_api_client, permission_manage_orders
-):
- page_size = 2
- variables = {"first": page_size, "after": None, "filter": {"search": order.pk}}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
- response = staff_api_client.post_graphql(QUERY_ORDERS_WITH_PAGINATION, variables)
- content = get_graphql_content(response)
- assert content["data"]["orders"]["totalCount"] == 1
-
-
@pytest.mark.parametrize(
"draft_orders_filter, expected_total_count, orders_order",
[
- ({"search": "test_discount"}, 2, [0.0, 0.0]),
- ({"search": "test_discount1"}, 1, [0.0]),
- ({"search": "translated_discount1_name"}, 1, [0.0]),
- ({"search": "user"}, 2, [0.0, 0.0]),
- ({"search": "[email protected]"}, 1, [0.0]),
- ({"search": "[email protected]"}, 1, [0.0]),
+ ({"search": "discount name"}, 2, [0.0, 0.0]),
+ ({"search": "Some other"}, 1, [0.0]),
+ ({"search": "translated"}, 1, [0.0]),
+ ({"search": "user_email"}, 2, [0.0, 0.0]),
+ ({"search": "[email protected]"}, 1, [0.0]),
({"search": "Leslie"}, 1, [0.0]),
({"search": "Wade"}, 1, [0.0]),
({"search": ""}, 6, [0.0, 0.0]),
@@ -508,19 +495,19 @@ def test_draft_orders_query_pagination_with_filter_search(
Order(
user=customer_user,
token=str(uuid.uuid4()),
- user_email="[email protected]",
+ user_email="[email protected]",
status=OrderStatus.DRAFT,
channel=channel_USD,
),
Order(
token=str(uuid.uuid4()),
- user_email="[email protected]",
+ user_email="[email protected]",
status=OrderStatus.DRAFT,
channel=channel_USD,
),
Order(
token=str(uuid.uuid4()),
- user_email="[email protected]",
+ user_email="[email protected]",
status=OrderStatus.DRAFT,
channel=channel_USD,
),
@@ -530,17 +517,17 @@ def test_draft_orders_query_pagination_with_filter_search(
[
OrderDiscount(
order=orders[0],
- name="test_discount1",
+ name="Some discount name",
value=Decimal("1"),
amount_value=Decimal("1"),
- translated_name="translated_discount1_name",
+ translated_name="translated",
),
OrderDiscount(
order=orders[2],
- name="test_discount2",
+ name="Some other discount name",
value=Decimal("10"),
amount_value=Decimal("10"),
- translated_name="translated_discount2_name",
+ translated_name="PL_name",
),
]
)
@@ -559,6 +546,17 @@ def test_draft_orders_query_pagination_with_filter_search(
assert orders[i]["node"]["total"]["gross"]["amount"] == orders_order[i]
+def test_orders_query_pagination_with_filter_search_by_id(
+ order, staff_api_client, permission_manage_orders
+):
+ page_size = 2
+ variables = {"first": page_size, "after": None, "filter": {"search": order.pk}}
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(QUERY_ORDERS_WITH_PAGINATION, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["orders"]["totalCount"] == 1
+
+
def test_draft_orders_query_pagination_with_filter_search_by_id(
draft_order,
staff_api_client,
diff --git a/saleor/order/migrations/0104_auto_20210506_0835.py b/saleor/order/migrations/0104_auto_20210506_0835.py
new file mode 100644
index 0000000000..72750a0d3d
--- /dev/null
+++ b/saleor/order/migrations/0104_auto_20210506_0835.py
@@ -0,0 +1,20 @@
+# Generated by Django 3.1.8 on 2021-05-06 08:35
+
+import django.contrib.postgres.indexes
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0103_auto_20210401_1105"),
+ ]
+
+ operations = [
+ migrations.AddIndex(
+ model_name="order",
+ index=django.contrib.postgres.indexes.GinIndex(
+ fields=["user_email"], name="order_order_user_em_bda05b_gin"
+ ),
+ ),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 6310094442..ff013d15fd 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -5,6 +5,7 @@ from typing import Optional
from uuid import uuid4
from django.conf import settings
+from django.contrib.postgres.indexes import GinIndex
from django.core.validators import MinValueValidator
from django.db import models
from django.db.models import JSONField # type: ignore
@@ -224,9 +225,10 @@ class Order(ModelWithMetadata):
redirect_url = models.URLField(blank=True, null=True)
objects = OrderQueryset.as_manager()
- class Meta(ModelWithMetadata.Meta):
+ class Meta:
ordering = ("-pk",)
permissions = ((OrderPermissions.MANAGE_ORDERS.codename, "Manage orders."),)
+ indexes = [*ModelWithMetadata.Meta.indexes, GinIndex(fields=["user_email"])]
def save(self, *args, **kwargs):
if not self.token:
diff --git a/saleor/payment/migrations/0025_auto_20210506_0750.py b/saleor/payment/migrations/0025_auto_20210506_0750.py
new file mode 100644
index 0000000000..f4c762c978
--- /dev/null
+++ b/saleor/payment/migrations/0025_auto_20210506_0750.py
@@ -0,0 +1,28 @@
+# Generated by Django 3.1.8 on 2021-05-06 07:50
+
+import django.contrib.postgres.indexes
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("payment", "0024_auto_20210326_0837"),
+ ]
+
+ operations = [
+ migrations.AddIndex(
+ model_name="payment",
+ index=django.contrib.postgres.indexes.GinIndex(
+ fields=["order_id", "is_active", "charge_status"],
+ name="payment_pay_order_i_f22aa2_gin",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="transaction",
+ name="searchable_key",
+ field=models.CharField(
+ blank=True, db_index=True, max_length=512, null=True
+ ),
+ ),
+ ]
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index 629b2c142a..cc5d3cfcaf 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -2,6 +2,7 @@ from decimal import Decimal
from operator import attrgetter
from django.conf import settings
+from django.contrib.postgres.indexes import GinIndex
from django.core.serializers.json import DjangoJSONEncoder
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
@@ -88,6 +89,10 @@ class Payment(models.Model):
class Meta:
ordering = ("pk",)
+ indexes = [
+ # Orders filtering by status index
+ GinIndex(fields=["order_id", "is_active", "charge_status"]),
+ ]
def __repr__(self):
return "Payment(gateway=%s, is_active=%s, created=%s, charge_status=%s)" % (
@@ -216,7 +221,9 @@ class Transaction(models.Model):
customer_id = models.CharField(max_length=256, null=True)
gateway_response = JSONField(encoder=DjangoJSONEncoder)
already_processed = models.BooleanField(default=False)
- searchable_key = models.CharField(max_length=512, null=True, blank=True)
+ searchable_key = models.CharField(
+ max_length=512, null=True, blank=True, db_index=True
+ )
class Meta:
ordering = ("pk",)