Skip to content

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

Implement full-text search for Orders (#9937)

Patryk Zawadzki61aa89f06a62
diff --git a/.pylintrc b/.pylintrc
index 7255c2cc8c..d4bdd97961 100644
--- a/.pylintrc
+++ b/.pylintrc
@@ -3,7 +3,7 @@ load-plugins=pylint.extensions.bad_builtin, pylint.extensions.mccabe, pylint_cel
django-settings-module=saleor.settings
[MESSAGES CONTROL]
-disable=C0103, C0111, C0330, C0412, C1001, E1004, E1101, I0011, R0903, W0232, W0621
+disable=C0103, C0111, I0011, R0903, W0621, W0622, W0707
[DESIGN]
max-complexity=5
diff --git a/saleor/account/search.py b/saleor/account/search.py
index 05b9bfdad3..b76b72efb5 100644
--- a/saleor/account/search.py
+++ b/saleor/account/search.py
@@ -1,9 +1,10 @@
from typing import TYPE_CHECKING
-from django.db.models import Q, prefetch_related_objects
+from django.contrib.postgres.search import SearchVector
+from django.db.models import Q, Value, prefetch_related_objects
if TYPE_CHECKING:
- from .models import User
+ from .models import Address, User
USER_SEARCH_FIELDS = ["email", "first_name", "last_name"]
@@ -50,7 +51,7 @@ def generate_user_fields_search_document_value(user: "User"):
return value.lower()
-def generate_address_search_document_value(address):
+def generate_address_search_document_value(address: "Address"):
fields_values = [
str(getattr(address, field))
if field != "country"
@@ -60,6 +61,34 @@ def generate_address_search_document_value(address):
return ("\n".join(fields_values) + "\n").lower()
+def generate_address_search_vector_value(
+ address: "Address", weight: str = "A"
+) -> SearchVector:
+ search_vector = SearchVector(
+ Value(address.first_name),
+ Value(address.last_name),
+ Value(address.street_address_1),
+ Value(address.country.name),
+ Value(address.country.code),
+ weight=weight,
+ )
+ if address.company_name:
+ search_vector += SearchVector(Value(address.company_name), weight=weight)
+ if address.country_area:
+ search_vector += SearchVector(Value(address.country_area), weight=weight)
+ if address.city:
+ search_vector += SearchVector(Value(address.city), weight=weight)
+ if address.city_area:
+ search_vector += SearchVector(Value(address.city_area), weight=weight)
+ if address.street_address_2:
+ search_vector += SearchVector(Value(address.street_address_2), weight=weight)
+ if address.postal_code:
+ search_vector += SearchVector(Value(address.postal_code), weight=weight)
+ if address.phone:
+ search_vector += SearchVector(Value(address.phone.as_e164), weight=weight)
+ return search_vector
+
+
def search_users(qs, value):
if value:
lookup = Q()
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 4ee0ce6921..a5d424dd74 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -18,7 +18,7 @@ from django.db import transaction
from prices import Money, TaxedMoney
from ..account.error_codes import AccountErrorCode
-from ..account.models import Address, User
+from ..account.models import User
from ..account.utils import store_user_address
from ..checkout import calculations
from ..checkout.error_codes import CheckoutErrorCode
@@ -27,7 +27,7 @@ from ..core.taxes import TaxError, zero_taxed_money
from ..core.tracing import traced_atomic_transaction
from ..core.utils.url import validate_storefront_url
from ..discount import DiscountInfo, DiscountValueType, OrderDiscountType, VoucherType
-from ..discount.models import NotApplicable, Voucher
+from ..discount.models import NotApplicable
from ..discount.utils import (
add_voucher_usage_by_customer,
get_sale_id_applied_as_a_discount,
@@ -43,7 +43,7 @@ from ..order.actions import mark_order_as_paid, order_created
from ..order.fetch import OrderInfo, OrderLineInfo
from ..order.models import Order, OrderLine
from ..order.notifications import send_order_confirmation
-from ..order.search import prepare_order_search_document_value
+from ..order.search import prepare_order_search_vector_value
from ..order.utils import update_order_authorize_data, update_order_charge_data
from ..payment import PaymentError, TransactionKind, gateway
from ..payment.models import Payment, Transaction
@@ -60,13 +60,15 @@ from .checkout_cleaner import (
clean_checkout_shipping,
)
from .fetch import CheckoutInfo, CheckoutLineInfo
-from .models import Checkout
from .utils import get_voucher_for_checkout_info
if TYPE_CHECKING:
+ from ..account.models import Address
from ..app.models import App
+ from ..discount.models import Voucher
from ..plugins.manager import PluginsManager
from ..site.models import SiteSettings
+ from .models import Checkout
def _process_voucher_data_for_order(checkout_info: "CheckoutInfo") -> dict:
@@ -539,7 +541,7 @@ def _create_order(
order.private_metadata = checkout.private_metadata
update_order_charge_data(order, with_save=False)
update_order_authorize_data(order, with_save=False)
- order.search_document = prepare_order_search_document_value(order)
+ order.search_vector = prepare_order_search_vector_value(order)
order.save()
order_info = OrderInfo(
@@ -1068,7 +1070,7 @@ def _create_order_from_checkout(
update_order_authorize_data(order, with_save=False)
# order search
- order.search_document = prepare_order_search_document_value(order)
+ order.search_vector = prepare_order_search_vector_value(order)
order.save()
# post create actions
diff --git a/saleor/core/search_tasks.py b/saleor/core/search_tasks.py
index 34c20cc3cc..b1464d66fe 100644
--- a/saleor/core/search_tasks.py
+++ b/saleor/core/search_tasks.py
@@ -6,7 +6,7 @@ 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
+from ..order.search import prepare_order_search_vector_value
from ..product.models import Product
from ..product.search import (
PRODUCT_FIELDS_TO_PREFETCH,
@@ -52,7 +52,7 @@ def set_user_search_document_values(updated_count: int = 0) -> None:
@app.task
def set_order_search_document_values(updated_count: int = 0) -> None:
orders = list(
- Order.objects.filter(search_document="")
+ Order.objects.filter(search_vector=None)
.prefetch_related(
"user",
"billing_address",
@@ -68,9 +68,7 @@ def set_order_search_document_values(updated_count: int = 0) -> None:
task_logger.info("No orders to update.")
return
- updated_count += set_search_document_values(
- orders, prepare_order_search_document_value
- )
+ updated_count += set_search_vector_values(orders, prepare_order_search_vector_value)
task_logger.info("Updated %d orders", updated_count)
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 53427ab943..27316855b0 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -61,7 +61,7 @@ from ...giftcard.models import GiftCard, GiftCardTag
from ...menu.models import Menu, MenuItem
from ...order import OrderStatus
from ...order.models import Fulfillment, Order, OrderLine
-from ...order.search import prepare_order_search_document_value
+from ...order.search import prepare_order_search_vector_value
from ...order.utils import update_order_status
from ...page.models import Page, PageType
from ...payment import gateway
@@ -838,7 +838,7 @@ def create_fake_order(discounts, max_order_lines=5, create_preorder_lines=False)
for line in order.lines.all():
weight += line.variant.get_weight()
order.weight = weight
- order.search_document = prepare_order_search_document_value(order)
+ order.search_vector = prepare_order_search_vector_value(order)
order.save()
create_fake_payment(order=order)
diff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.py
index aea50f0a16..f6fe9dc0d7 100644
--- a/saleor/graphql/checkout/tests/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py
@@ -293,7 +293,7 @@ def test_checkout_complete(
assert order.shipping_address == address
assert order.shipping_method == checkout.shipping_method
assert order.payments.exists()
- assert order.search_document
+ assert order.search_vector
order_payment = order.payments.first()
assert order_payment == payment
assert payment.transactions.count() == 1
diff --git a/saleor/graphql/checkout/tests/test_order_create_from_checkout.py b/saleor/graphql/checkout/tests/test_order_create_from_checkout.py
index 8c2777d3b5..d5f91647a8 100644
--- a/saleor/graphql/checkout/tests/test_order_create_from_checkout.py
+++ b/saleor/graphql/checkout/tests/test_order_create_from_checkout.py
@@ -145,7 +145,7 @@ def test_order_from_checkout(
assert checkout_line_variant == order_line.variant
assert order.shipping_address == address
assert order.shipping_method == checkout.shipping_method
- assert order.search_document
+ assert order.search_vector
gift_card.refresh_from_db()
assert gift_card.current_balance == zero_money(gift_card.currency)
diff --git a/saleor/graphql/core/connection.py b/saleor/graphql/core/connection.py
index 90293e6460..e0f6a9f015 100644
--- a/saleor/graphql/core/connection.py
+++ b/saleor/graphql/core/connection.py
@@ -1,6 +1,6 @@
import json
from decimal import Decimal, InvalidOperation
-from typing import Any, Dict, Iterable, List, Optional, Tuple, Union, cast
+from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union, cast
import graphene
from django.conf import settings
@@ -54,21 +54,24 @@ def get_field_value(instance: DjangoModel, field_name: str):
def _prepare_filter_by_rank_expression(
cursor: List[str],
sorting_direction: str,
+ coerce_id: Callable[[str], Any],
) -> Q:
+ if len(cursor) != 2:
+ raise GraphQLError("Received cursor is invalid.")
try:
rank = Decimal(cursor[0])
- int(cursor[1])
- except (InvalidOperation, ValueError, TypeError, KeyError):
- raise ValueError("Invalid cursor for sorting by rank.")
+ id = coerce_id(cursor[1])
+ except (InvalidOperation, ValueError, TypeError):
+ raise GraphQLError("Received cursor is invalid.")
# Because rank is float number, it gets mangled by PostgreSQL's query parser
# making equal comparisons impossible. Instead we compare rank against small
# range of values, constructed using epsilon.
if sorting_direction == "gt":
- return Q(
- search_rank__range=(rank - EPSILON, rank + EPSILON), id__lt=cursor[1]
- ) | Q(search_rank__gt=rank + EPSILON)
- return Q(search_rank__range=(rank - EPSILON, rank + EPSILON), id__gt=cursor[1]) | Q(
+ return Q(search_rank__range=(rank - EPSILON, rank + EPSILON), id__lt=id) | Q(
+ search_rank__gt=rank + EPSILON
+ )
+ return Q(search_rank__range=(rank - EPSILON, rank + EPSILON), id__gt=id) | Q(
search_rank__lt=rank - EPSILON
)
@@ -98,7 +101,10 @@ def _prepare_filter_expression(
def _prepare_filter(
- cursor: List[str], sorting_fields: List[str], sorting_direction: str
+ cursor: List[str],
+ sorting_fields: List[str],
+ sorting_direction: str,
+ coerce_id: Callable[[str], Any],
) -> Q:
"""Create filter arguments based on sorting fields.
@@ -116,7 +122,7 @@ def _prepare_filter(
"""
if sorting_fields == ["search_rank", "id"]:
# Fast path for filtering by rank
- return _prepare_filter_by_rank_expression(cursor, sorting_direction)
+ return _prepare_filter_by_rank_expression(cursor, sorting_direction, coerce_id)
filter_kwargs = Q()
for index, field_name in enumerate(sorting_fields):
if cursor[index] is None and sorting_direction == "gt":
@@ -177,12 +183,12 @@ def _get_page_info(matching_records, cursor, first, last):
records_left = False
if requested_count is not None:
records_left = len(matching_records) > requested_count
- has_pages_before = True if cursor else False
+ has_other_pages = bool(cursor)
if first:
page_info["has_next_page"] = records_left
- page_info["has_previous_page"] = has_pages_before
+ page_info["has_previous_page"] = has_other_pages
elif last:
- page_info["has_next_page"] = has_pages_before
+ page_info["has_next_page"] = has_other_pages
page_info["has_previous_page"] = records_left
return page_info
@@ -228,6 +234,10 @@ def _get_edges_for_connection(edge_type, qs, args, sorting_fields):
return edges, page_info
+def _get_id_coercion(qs: QuerySet) -> Callable[[str], Any]:
+ return qs.model.id.field.to_python if hasattr(qs.model, "id") else int
+
+
def connection_from_queryset_slice(
qs: QuerySet,
args: ConnectionArguments = None,
@@ -258,7 +268,14 @@ def connection_from_queryset_slice(
if cursor and len(cursor) != len(sorting_fields):
raise GraphQLError("Received cursor is invalid.")
filter_kwargs = (
- _prepare_filter(cursor, sorting_fields, sorting_direction) if cursor else Q()
+ _prepare_filter(
+ cursor,
+ sorting_fields,
+ sorting_direction,
+ _get_id_coercion(qs),
+ )
+ if cursor
+ else Q()
)
try:
filtered_qs = qs.filter(filter_kwargs)
diff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.py
index da9482f320..6660b2497c 100644
--- a/saleor/graphql/order/mutations/draft_order_complete.py
+++ b/saleor/graphql/order/mutations/draft_order_complete.py
@@ -10,7 +10,7 @@ from ....order import OrderStatus, models
from ....order.actions import order_created
from ....order.error_codes import OrderErrorCode
from ....order.fetch import OrderInfo, OrderLineInfo
-from ....order.search import prepare_order_search_document_value
+from ....order.search import prepare_order_search_vector_value
from ....order.utils import get_order_country
from ....warehouse.management import allocate_preorders, allocate_stocks
from ....warehouse.reservations import is_reservation_enabled
@@ -81,7 +81,7 @@ class DraftOrderComplete(BaseMutation):
order.shipping_address.delete()
order.shipping_address = None
- order.search_document = prepare_order_search_document_value(order)
+ order.search_vector = prepare_order_search_vector_value(order)
order.save()
channel = order.channel
diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.py
index 92c7f0173d..6e0dd316ec 100644
--- a/saleor/graphql/order/mutations/draft_order_create.py
+++ b/saleor/graphql/order/mutations/draft_order_create.py
@@ -12,7 +12,7 @@ from ....core.tracing import traced_atomic_transaction
from ....core.utils.url import validate_storefront_url
from ....order import OrderOrigin, OrderStatus, events, models
from ....order.error_codes import OrderErrorCode
-from ....order.search import update_order_search_document
+from ....order.search import update_order_search_vector
from ....order.utils import add_variant_to_order, recalculate_order, update_order_prices
from ...account.i18n import I18nMixin
from ...account.types import AddressInput
@@ -329,4 +329,4 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
# Post-process the results
recalculate_order(instance)
- update_order_search_document(instance)
+ update_order_search_vector(instance)
diff --git a/saleor/graphql/order/mutations/order_discount_delete.py b/saleor/graphql/order/mutations/order_discount_delete.py
index d96a812d60..eadc5f32d5 100644
--- a/saleor/graphql/order/mutations/order_discount_delete.py
+++ b/saleor/graphql/order/mutations/order_discount_delete.py
@@ -3,7 +3,7 @@ import graphene
from ....core.permissions import OrderPermissions
from ....core.tracing import traced_atomic_transaction
from ....order import events
-from ....order.search import update_order_search_document
+from ....order.search import update_order_search_vector
from ....order.utils import remove_order_discount_from_order
from ...core.types import OrderError
from ..types import Order
@@ -44,6 +44,6 @@ class OrderDiscountDelete(OrderDiscountCommon):
order.refresh_from_db()
cls.recalculate_order(order)
- update_order_search_document(order)
+ update_order_search_vector(order)
return OrderDiscountDelete(order=order)
diff --git a/saleor/graphql/order/mutations/order_line_delete.py b/saleor/graphql/order/mutations/order_line_delete.py
index 1fdee87736..09fcd8e5e8 100644
--- a/saleor/graphql/order/mutations/order_line_delete.py
+++ b/saleor/graphql/order/mutations/order_line_delete.py
@@ -6,7 +6,7 @@ from ....core.taxes import zero_taxed_money
from ....core.tracing import traced_atomic_transaction
from ....order import events
from ....order.fetch import OrderLineInfo
-from ....order.search import update_order_search_document
+from ....order.search import update_order_search_vector
from ....order.utils import delete_order_line, recalculate_order
from ...core.mutations import BaseMutation
from ...core.types import OrderError
@@ -79,7 +79,7 @@ class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):
)
recalculate_order(order)
- update_order_search_document(order)
+ update_order_search_vector(order)
func = get_webhook_handler_by_order_status(order.status, info)
transaction.on_commit(lambda: func(order))
return OrderLineDelete(order=order, order_line=line)
diff --git a/saleor/graphql/order/mutations/order_lines_create.py b/saleor/graphql/order/mutations/order_lines_create.py
index 6dbbc39325..33acf350d3 100644
--- a/saleor/graphql/order/mutations/order_lines_create.py
+++ b/saleor/graphql/order/mutations/order_lines_create.py
@@ -9,7 +9,7 @@ from ....core.taxes import TaxError
from ....core.tracing import traced_atomic_transaction
from ....order import events
from ....order.error_codes import OrderErrorCode
-from ....order.search import update_order_search_document
+from ....order.search import update_order_search_vector
from ....order.utils import add_variant_to_order, recalculate_order
from ...core.mutations import BaseMutation
from ...core.types import NonNullList, OrderError
@@ -136,7 +136,7 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
lines = [line for _, line in added_lines]
recalculate_order(order)
- update_order_search_document(order)
+ update_order_search_vector(order)
func = get_webhook_handler_by_order_status(order.status, info)
transaction.on_commit(lambda: func(order))
diff --git a/saleor/graphql/order/mutations/order_mark_as_paid.py b/saleor/graphql/order/mutations/order_mark_as_paid.py
index a60657fc47..2afb8a9e7c 100644
--- a/saleor/graphql/order/mutations/order_mark_as_paid.py
+++ b/saleor/graphql/order/mutations/order_mark_as_paid.py
@@ -4,7 +4,7 @@ from django.core.exceptions import ValidationError
from ....core.permissions import OrderPermissions
from ....order.actions import clean_mark_order_as_paid, mark_order_as_paid
from ....order.error_codes import OrderErrorCode
-from ....order.search import update_order_search_document
+from ....order.search import update_order_search_vector
from ...core.mutations import BaseMutation
from ...core.types import OrderError
from ..types import Order
@@ -47,6 +47,6 @@ class OrderMarkAsPaid(BaseMutation):
order, user, app, info.context.plugins, transaction_reference
)
- update_order_search_document(order)
+ update_order_search_vector(order)
return OrderMarkAsPaid(order=order)
diff --git a/saleor/graphql/order/mutations/order_update.py b/saleor/graphql/order/mutations/order_update.py
index f634e085e4..cbd31111fd 100644
--- a/saleor/graphql/order/mutations/order_update.py
+++ b/saleor/graphql/order/mutations/order_update.py
@@ -7,7 +7,7 @@ from ....core.permissions import OrderPermissions
from ....core.tracing import traced_atomic_transaction
from ....order import OrderStatus, models
from ....order.error_codes import OrderErrorCode
-from ....order.search import prepare_order_search_document_value
+from ....order.search import prepare_order_search_vector_value
from ....order.utils import update_order_prices
from ...account.types import AddressInput
from ...core.types import OrderError
@@ -70,7 +70,7 @@ class OrderUpdate(DraftOrderCreate):
if instance.user_email:
user = User.objects.filter(email=instance.user_email).first()
instance.user = user
- instance.search_document = prepare_order_search_document_value(instance)
+ instance.search_vector = prepare_order_search_vector_value(instance)
instance.save()
update_order_prices(
instance,
diff --git a/saleor/graphql/order/schema.py b/saleor/graphql/order/schema.py
index 173d9dbc4e..3740b3c0c6 100644
--- a/saleor/graphql/order/schema.py
+++ b/saleor/graphql/order/schema.py
@@ -1,4 +1,7 @@
+from typing import List, Optional
+
import graphene
+from graphql import GraphQLError
from ...core.permissions import OrderPermissions
from ..core.connection import create_connection_slice, filter_connection_queryset
@@ -46,10 +49,18 @@ from .resolvers import (
resolve_orders,
resolve_orders_total,
)
-from .sorters import OrderSortingInput
+from .sorters import OrderSortField, OrderSortingInput
from .types import Order, OrderCountableConnection, OrderEventCountableConnection
+def search_string_in_kwargs(kwargs: dict) -> bool:
+ return bool(kwargs.get("filter", {}).get("search", "").strip())
+
+
+def sort_field_from_kwargs(kwargs: dict) -> Optional[List[str]]:
+ return kwargs.get("sort_by", {}).get("field") or None
+
+
class OrderFilterInput(FilterInputObjectType):
class Meta:
filterset_class = OrderFilter
@@ -128,12 +139,38 @@ class OrderQueries(graphene.ObjectType):
@staticmethod
def resolve_orders(_root, info, *, channel=None, **kwargs):
+ if sort_field_from_kwargs(kwargs) == OrderSortField.RANK:
+ # sort by RANK can be used only with search filter
+ if not search_string_in_kwargs(kwargs):
+ raise GraphQLError(
+ "Sorting by RANK is available only when using a search filter."
+ )
+ if search_string_in_kwargs(kwargs) and not sort_field_from_kwargs(kwargs):
+ # default to sorting by RANK if search is used
+ # and no explicit sorting is requested
+ product_type = info.schema.get_type("OrderSortingInput")
+ kwargs["sort_by"] = product_type.create_container(
+ {"direction": "-", "field": ["search_rank", "id"]}
+ )
qs = resolve_orders(info, channel)
qs = filter_connection_queryset(qs, kwargs)
return create_connection_slice(qs, info, kwargs, OrderCountableConnection)
@staticmethod
def resolve_draft_orders(_root, info, **kwargs):
+ if sort_field_from_kwargs(kwargs) == OrderSortField.RANK:
+ # sort by RANK can be used only with search filter
+ if not search_string_in_kwargs(kwargs):
+ raise GraphQLError(
+ "Sorting by RANK is available only when using a search filter."
+ )
+ if search_string_in_kwargs(kwargs) and not sort_field_from_kwargs(kwargs):
+ # default to sorting by RANK if search is used
+ # and no explicit sorting is requested
+ product_type = info.schema.get_type("OrderSortingInput")
+ kwargs["sort_by"] = product_type.create_container(
+ {"direction": "-", "field": ["search_rank", "id"]}
+ )
qs = resolve_draft_orders(info)
qs = filter_connection_queryset(qs, kwargs)
return create_connection_slice(qs, info, kwargs, OrderCountableConnection)
diff --git a/saleor/graphql/order/sorters.py b/saleor/graphql/order/sorters.py
index 2aa0cd16f0..fc99e3bac1 100644
--- a/saleor/graphql/order/sorters.py
+++ b/saleor/graphql/order/sorters.py
@@ -8,6 +8,7 @@ from ..core.types import SortInputObjectType
class OrderSortField(graphene.Enum):
NUMBER = ["number"]
+ RANK = ["search_rank", "id"]
CREATION_DATE = ["created_at", "status", "pk"]
CREATED_AT = ["created_at", "status", "pk"]
LAST_MODIFIED_AT = ["updated_at", "status", "pk"]
@@ -17,8 +18,10 @@ class OrderSortField(graphene.Enum):
@property
def description(self):
- # pylint: disable=no-member
descriptions = {
+ OrderSortField.RANK.name: (
+ "rank. Note: This option is available only with the `search` filter."
+ ),
OrderSortField.CREATION_DATE.name: (
f"creation date. {DEPRECATED_IN_3X_INPUT}"
),
diff --git a/saleor/graphql/order/tests/deprecated/test_discount_order.py b/saleor/graphql/order/tests/deprecated/test_discount_order.py
index 66bf801987..040ce179df 100644
--- a/saleor/graphql/order/tests/deprecated/test_discount_order.py
+++ b/saleor/graphql/order/tests/deprecated/test_discount_order.py
@@ -73,9 +73,7 @@ def test_delete_order_discount_from_order_with_old_id(
event = order.events.get()
assert event.type == OrderEvents.ORDER_DISCOUNT_DELETED
- assert order.search_document
- assert name not in order.search_document
- assert translated_name not in order.search_document
+ assert order.search_vector
ORDER_DISCOUNT_UPDATE = """
diff --git a/saleor/graphql/order/tests/test_discount_order.py b/saleor/graphql/order/tests/test_discount_order.py
index 2efb935da1..e241f4bb11 100644
--- a/saleor/graphql/order/tests/test_discount_order.py
+++ b/saleor/graphql/order/tests/test_discount_order.py
@@ -448,9 +448,7 @@ def test_delete_order_discount_from_order(
event = order.events.get()
assert event.type == OrderEvents.ORDER_DISCOUNT_DELETED
- assert order.search_document
- assert name not in order.search_document
- assert translated_name not in order.search_document
+ assert order.search_vector
def test_delete_order_discount_order_is_not_draft(
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index 61cc3f1446..c4370f7887 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -32,8 +32,8 @@ from ....order.events import order_replacement_created
from ....order.models import Order, OrderEvent, OrderLine, get_order_number
from ....order.notifications import get_default_order_payload
from ....order.search import (
- prepare_order_search_document_value,
- update_order_search_document,
+ prepare_order_search_vector_value,
+ update_order_search_vector,
)
from ....order.utils import update_order_authorize_data, update_order_charge_data
from ....payment import ChargeStatus, PaymentError, TransactionAction, TransactionStatus
@@ -2291,7 +2291,7 @@ def test_draft_order_create(
assert order.shipping_method == shipping_method
assert order.billing_address
assert order.shipping_address
- assert order.search_document
+ assert order.search_vector
# Ensure the correct event was created
created_draft_event = OrderEvent.objects.get(
@@ -3242,7 +3242,7 @@ def test_draft_order_update(
order.refresh_from_db()
assert order.voucher
assert order.customer_note == customer_note
- assert order.search_document
+ assert order.search_vector
def test_draft_order_update_with_non_draft_order(
@@ -3823,7 +3823,7 @@ def test_draft_order_complete(
order.refresh_from_db()
assert data["status"] == order.status.upper()
assert data["origin"] == OrderOrigin.DRAFT.upper()
- assert order.search_document
+ assert order.search_vector
for line in order.lines.all():
allocation = line.allocations.get()
@@ -4592,9 +4592,6 @@ def test_order_lines_create(
assert data["errors"][0]["variants"] == [variant_id]
product_variant_out_of_stock_webhook_mock.assert_not_called()
- order.refresh_from_db()
- assert variant.sku.lower() in order.search_document
-
@pytest.mark.parametrize("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")
@@ -5401,10 +5398,6 @@ def test_order_line_remove_with_back_in_stock_webhook(
) == 3
back_in_stock_webhook_mock.assert_called_once_with(Stock.objects.first())
- order.refresh_from_db()
- assert order.search_document
- assert line.product_sku not in order.search_document
-
@pytest.mark.parametrize("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")
@@ -5515,9 +5508,6 @@ def test_order_update(
assert order.user_email == email
assert order.user is None
assert order.status == OrderStatus.UNFULFILLED
- assert graphql_address_data["firstName"].lower() in order.search_document
- assert graphql_address_data["lastName"].lower() in order.search_document
- assert email.lower() in order.search_document
order_updated_webhook_mock.assert_called_once_with(order)
@@ -6098,7 +6088,6 @@ def test_order_mark_as_paid_with_external_reference(
assert event_reference == transaction_reference
order_payments = order.payments.filter(psp_reference=transaction_reference)
assert order_payments.count() == 1
- assert transaction_reference in order.search_document
def test_order_mark_as_paid(
@@ -8476,7 +8465,6 @@ def test_query_draft_orders_with_sort(
({"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),
@@ -8561,8 +8549,8 @@ def test_orders_query_with_filter_search(
tax_rate=Decimal("0.23"),
)
for order in orders:
- order.search_document = prepare_order_search_document_value(order)
- Order.objects.bulk_update(orders, ["search_document"])
+ order.search_vector = prepare_order_search_vector_value(order)
+ Order.objects.bulk_update(orders, ["search_vector"])
variables = {"filter": orders_filter}
staff_api_client.user.user_permissions.add(permission_manage_orders)
@@ -8603,8 +8591,8 @@ def test_orders_query_with_filter_search_by_global_payment_id(
payment = Payment.objects.create(order=order_with_payment)
global_id = graphene.Node.to_global_id("Payment", payment.pk)
for order in orders:
- order.search_document = prepare_order_search_document_value(order)
- Order.objects.bulk_update(orders, ["search_document"])
+ order.search_vector = prepare_order_search_vector_value(order)
+ Order.objects.bulk_update(orders, ["search_vector"])
variables = {"filter": {"search": global_id}}
staff_api_client.user.user_permissions.add(permission_manage_orders)
@@ -8615,11 +8603,11 @@ def test_orders_query_with_filter_search_by_global_payment_id(
def test_orders_query_with_filter_search_by_number(
orders_query_with_filter,
- order_with_search_document_value,
+ order_with_search_vector_value,
staff_api_client,
permission_manage_orders,
):
- order = order_with_search_document_value
+ order = order_with_search_vector_value
variables = {"filter": {"search": order.number}}
staff_api_client.user.user_permissions.add(permission_manage_orders)
response = staff_api_client.post_graphql(orders_query_with_filter, variables)
@@ -8629,11 +8617,11 @@ def test_orders_query_with_filter_search_by_number(
def test_orders_query_with_filter_search_by_number_with_hash(
orders_query_with_filter,
- order_with_search_document_value,
+ order_with_search_vector_value,
staff_api_client,
permission_manage_orders,
):
- order = order_with_search_document_value
+ order = order_with_search_vector_value
variables = {"filter": {"search": f"#{order.number}"}}
staff_api_client.user.user_permissions.add(permission_manage_orders)
response = staff_api_client.post_graphql(orders_query_with_filter, variables)
@@ -8672,7 +8660,7 @@ def test_order_query_with_filter_search_by_product_sku_order_line(
"""
order = order_line.order
order.refresh_from_db()
- update_order_search_document(order)
+ update_order_search_vector(order)
variables = {"filter": {"search": order_line.product_sku}}
response = staff_api_client.post_graphql(
@@ -8888,7 +8876,7 @@ def test_order_query_with_filter_search_by_product_sku_multi_order_lines(
]
)
order.refresh_from_db()
- update_order_search_document(order)
+ update_order_search_vector(order)
variables = {"filter": {"search": lines[0].product_sku}}
response = staff_api_client.post_graphql(
@@ -8904,7 +8892,6 @@ def test_order_query_with_filter_search_by_product_sku_multi_order_lines(
({"search": "discount name"}, 2),
({"search": "Some other"}, 1),
({"search": "translated"}, 1),
- ({"search": "user_email"}, 2),
({"search": "[email protected]"}, 1),
({"search": "Leslie"}, 1),
({"search": "leslie wade"}, 1),
@@ -8960,8 +8947,9 @@ def test_draft_orders_query_with_filter_search(
]
)
for order in orders:
- order.search_document = prepare_order_search_document_value(order)
- Order.objects.bulk_update(orders, ["search_document"])
+ order.search_vector = prepare_order_search_vector_value(order)
+ print(">>>", order.search_vector)
+ Order.objects.bulk_update(orders, ["search_vector"])
variables = {"filter": draft_orders_filter}
@@ -8977,7 +8965,7 @@ def test_draft_orders_query_with_filter_search_by_number(
staff_api_client,
permission_manage_orders,
):
- update_order_search_document(draft_order)
+ update_order_search_vector(draft_order)
variables = {"filter": {"search": draft_order.number}}
staff_api_client.user.user_permissions.add(permission_manage_orders)
response = staff_api_client.post_graphql(draft_orders_query_with_filter, variables)
@@ -8991,7 +8979,7 @@ def test_draft_orders_query_with_filter_search_by_number_with_hash(
staff_api_client,
permission_manage_orders,
):
- update_order_search_document(draft_order)
+ update_order_search_vector(draft_order)
variables = {"filter": {"search": f"#{draft_order.number}"}}
staff_api_client.user.user_permissions.add(permission_manage_orders)
response = staff_api_client.post_graphql(draft_orders_query_with_filter, variables)
@@ -9637,3 +9625,42 @@ def test_order_by_token_query_payment_details_available_fields_with_permissions(
content = get_graphql_content(response)
assert_order_and_payment_ids(content, payment_txn_captured)
+
+
+SEARCH_ORDERS_QUERY = """
+ query Orders(
+ $filters: OrderFilterInput,
+ $sortBy: OrderSortingInput,
+ $after: String,
+ ) {
+ orders(
+ first: 5,
+ filter: $filters,
+ sortBy: $sortBy,
+ after: $after,
+ ) {
+ edges {
+ node {
+ id
+ }
+ cursor
+ }
+ }
+ }
+"""
+
+
+def test_sort_order_by_rank_without_search(staff_api_client, permission_manage_orders):
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ variables = {
+ "sortBy": {"field": "RANK", "direction": "DESC"},
+ }
+ response = staff_api_client.post_graphql(SEARCH_ORDERS_QUERY, variables)
+ content = get_graphql_content(response, ignore_errors=True)
+
+ assert "errors" in content
+ assert (
+ content["errors"][0]["message"]
+ == "Sorting by RANK is available only when using a search filter."
+ )
diff --git a/saleor/graphql/order/tests/test_pagination.py b/saleor/graphql/order/tests/test_pagination.py
index 0bffede65a..93176782e7 100644
--- a/saleor/graphql/order/tests/test_pagination.py
+++ b/saleor/graphql/order/tests/test_pagination.py
@@ -9,8 +9,8 @@ from prices import Money, TaxedMoney
from ....discount.models import OrderDiscount
from ....order.models import Order, OrderStatus
from ....order.search import (
- prepare_order_search_document_value,
- update_order_search_document,
+ prepare_order_search_vector_value,
+ update_order_search_vector,
)
from ....payment import ChargeStatus
from ...tests.utils import get_graphql_content
@@ -36,8 +36,8 @@ def orders_for_pagination(db, channel_USD):
)
for order in orders:
- order.search_document = prepare_order_search_document_value(order)
- Order.objects.bulk_update(orders, ["search_document"])
+ order.search_vector = prepare_order_search_vector_value(order)
+ Order.objects.bulk_update(orders, ["search_vector"])
return orders
@@ -392,22 +392,19 @@ def test_draft_order_query_pagination_with_filter_created(
@pytest.mark.parametrize(
- "orders_filter, expected_total_count, orders_order",
+ "orders_filter, expected_total_count",
[
- ({"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]),
+ ({"search": "discount name"}, 2),
+ ({"search": "Some other"}, 1),
+ ({"search": "[email protected]"}, 1),
+ ({"search": "Leslie"}, 1),
+ ({"search": "Wade"}, 1),
+ ({"search": ""}, 6),
],
)
def test_orders_query_pagination_with_filter_search(
orders_filter,
expected_total_count,
- orders_order,
staff_api_client,
permission_manage_orders,
customer_user,
@@ -451,40 +448,42 @@ def test_orders_query_pagination_with_filter_search(
)
for order in orders:
- order.search_document = prepare_order_search_document_value(order)
- Order.objects.bulk_update(orders, ["search_document"])
-
- page_size = 2
- variables = {"first": page_size, "after": None, "filter": orders_filter}
- 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)
-
- orders = content["data"]["orders"]["edges"]
- total_count = content["data"]["orders"]["totalCount"]
-
- assert expected_total_count == total_count
- for i in range(total_count if total_count < page_size else page_size):
- assert orders[i]["node"]["total"]["gross"]["amount"] == orders_order[i]
+ order.search_vector = prepare_order_search_vector_value(order)
+ Order.objects.bulk_update(orders, ["search_vector"])
+
+ after = None
+ orders_seen = 0
+ while True:
+ variables = {"first": 1, "after": after, "filter": orders_filter}
+ 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)
+ orders_seen += len(content["data"]["orders"]["edges"])
+ total_count = content["data"]["orders"]["totalCount"]
+ if not content["data"]["orders"]["pageInfo"]["hasNextPage"]:
+ break
+ after = content["data"]["orders"]["pageInfo"]["endCursor"]
+
+ assert orders_seen == total_count
+ assert total_count == expected_total_count
@pytest.mark.parametrize(
- "draft_orders_filter, expected_total_count, orders_order",
+ "draft_orders_filter, expected_total_count",
[
- ({"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]),
+ ({"search": "discount name"}, 2),
+ ({"search": "Some other"}, 1),
+ ({"search": "[email protected]"}, 1),
+ ({"search": "Leslie"}, 1),
+ ({"search": "Wade"}, 1),
+ ({"search": ""}, 6),
],
)
def test_draft_orders_query_pagination_with_filter_search(
draft_orders_filter,
expected_total_count,
- orders_order,
staff_api_client,
permission_manage_orders,
customer_user,
@@ -531,8 +530,8 @@ def test_draft_orders_query_pagination_with_filter_search(
)
for order in orders:
- order.search_document = prepare_order_search_document_value(order)
- Order.objects.bulk_update(orders, ["search_document"])
+ order.search_vector = prepare_order_search_vector_value(order)
+ Order.objects.bulk_update(orders, ["search_vector"])
page_size = 2
variables = {"first": page_size, "after": None, "filter": draft_orders_filter}
@@ -545,14 +544,12 @@ def test_draft_orders_query_pagination_with_filter_search(
total_count = content["data"]["draftOrders"]["totalCount"]
assert expected_total_count == total_count
- for i in range(total_count if total_count < page_size else page_size):
- assert orders[i]["node"]["total"]["gross"]["amount"] == orders_order[i]
def test_orders_query_pagination_with_filter_search_by_number(
- order_with_search_document_value, staff_api_client, permission_manage_orders
+ order_with_search_vector_value, staff_api_client, permission_manage_orders
):
- order = order_with_search_document_value
+ order = order_with_search_vector_value
page_size = 2
variables = {"first": page_size, "after": None, "filter": {"search": order.number}}
staff_api_client.user.user_permissions.add(permission_manage_orders)
@@ -566,7 +563,7 @@ def test_draft_orders_query_pagination_with_filter_search_by_number(
staff_api_client,
permission_manage_orders,
):
- update_order_search_document(draft_order)
+ update_order_search_vector(draft_order)
page_size = 2
variables = {
"first": page_size,
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 8b152d3db7..583a23e400 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -2955,7 +2955,8 @@ def test_products_query_with_filter_search_by_dropdown_attribute_value(
@pytest.mark.parametrize(
- "search_value", ["eco mode", "ECO Performance", "performant*", "modes"]
+ "search_value",
+ ["eco mode", "ECO Performance", "performance", "eco performance mode"],
)
def test_products_query_with_filter_search_by_multiselect_attribute_value(
search_value,
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index c4bd2bb477..c3d9a2f7b0 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -9450,6 +9450,11 @@ enum OrderSortField {
"""Sort orders by number."""
NUMBER
+ """
+ Sort orders by rank. Note: This option is available only with the `search` filter.
+ """
+ RANK
+
"""
Sort orders by creation date.
diff --git a/saleor/order/migrations/0151_auto_20220606_1431.py b/saleor/order/migrations/0151_auto_20220606_1431.py
new file mode 100644
index 0000000000..22a04711dc
--- /dev/null
+++ b/saleor/order/migrations/0151_auto_20220606_1431.py
@@ -0,0 +1,28 @@
+# Generated by Django 3.2.13 on 2022-06-06 14:31
+
+import django.contrib.postgres.indexes
+import django.contrib.postgres.search
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0150_update_authorize_and_charge_status"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="order",
+ name="search_vector",
+ field=django.contrib.postgres.search.SearchVectorField(
+ blank=True, null=True
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="order",
+ index=django.contrib.postgres.indexes.GinIndex(
+ fields=["search_vector"], name="order_tsearch"
+ ),
+ ),
+ ]
diff --git a/saleor/order/migrations/0152_update_order_search_vector.py b/saleor/order/migrations/0152_update_order_search_vector.py
new file mode 100644
index 0000000000..cdd9936db7
--- /dev/null
+++ b/saleor/order/migrations/0152_update_order_search_vector.py
@@ -0,0 +1,25 @@
+from django.db import migrations
+from django.db.models.signals import post_migrate
+
+from ...core.search_tasks import set_order_search_document_values
+
+
+def update_order_search_document_values(apps, _schema_editor):
+ def on_migrations_complete(sender=None, **kwargs):
+ set_order_search_document_values.delay()
+
+ post_migrate.connect(on_migrations_complete, weak=False)
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0151_auto_20220606_1431"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ update_order_search_document_values,
+ reverse_code=migrations.RunPython.noop,
+ ),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 2cfc3a77e1..8b719d51b8 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -6,6 +6,7 @@ from uuid import uuid4
from django.conf import settings
from django.contrib.postgres.indexes import GinIndex
+from django.contrib.postgres.search import SearchVectorField
from django.core.validators import MinValueValidator
from django.db import connection, models
from django.db.models import JSONField # type: ignore
@@ -287,7 +288,7 @@ class Order(ModelWithMetadata):
)
redirect_url = models.URLField(blank=True, null=True)
search_document = models.TextField(blank=True, default="")
-
+ search_vector = SearchVectorField(blank=True, null=True)
objects = models.Manager.from_queryset(OrderQueryset)()
class Meta:
@@ -301,6 +302,10 @@ class Order(ModelWithMetadata):
fields=["search_document"],
opclasses=["gin_trgm_ops"],
),
+ GinIndex(
+ name="order_tsearch",
+ fields=["search_vector"],
+ ),
GinIndex(
name="order_email_search_gin",
# `opclasses` and `fields` should be the same length
diff --git a/saleor/order/search.py b/saleor/order/search.py
index d5be0b9919..b5785a0de9 100644
--- a/saleor/order/search.py
+++ b/saleor/order/search.py
@@ -1,23 +1,25 @@
-from typing import TYPE_CHECKING
+from functools import reduce
+from operator import add
+from typing import TYPE_CHECKING, Optional
import graphene
-from django.db.models import Q, prefetch_related_objects
+from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector
+from django.db.models import F, Q, Value, prefetch_related_objects
-from ..account.search import (
- generate_address_search_document_value,
- generate_user_fields_search_document_value,
-)
+from ..account.search import generate_address_search_vector_value
if TYPE_CHECKING:
+ from django.db.models import QuerySet
+
from .models import Order
-def update_order_search_document(order: "Order"):
- order.search_document = prepare_order_search_document_value(order)
- order.save(update_fields=["search_document", "updated_at"])
+def update_order_search_vector(order: "Order"):
+ order.search_vector = prepare_order_search_vector_value(order)
+ order.save(update_fields=["search_vector", "updated_at"])
-def prepare_order_search_document_value(order: "Order", *, already_prefetched=False):
+def prepare_order_search_vector_value(order: "Order", *, already_prefetched=False):
if not already_prefetched:
prefetch_related_objects(
[order],
@@ -28,56 +30,162 @@ def prepare_order_search_document_value(order: "Order", *, already_prefetched=Fa
"discounts",
"lines",
)
- search_document = f"#{str(order.number)}\n"
- user_data = order.user_email + "\n"
- if user := order.user:
- user_data += generate_user_fields_search_document_value(user)
- search_document += user_data
-
- for address_field in ["billing_address", "shipping_address"]:
- if address := getattr(order, address_field):
- search_document += generate_address_search_document_value(address)
-
- search_document += generate_order_payments_search_document_value(order)
-
- search_document += generate_order_discounts_search_document_value(order)
+ search_vector = SearchVector(Value(str(order.number)), config="simple", weight="A")
+ if order.user_email:
+ search_vector += SearchVector(
+ Value(order.user_email), config="simple", weight="A"
+ )
+ if order.user:
+ search_vector += SearchVector(
+ Value(order.user.email), config="simple", weight="A"
+ )
+ if order.user.first_name:
+ search_vector += SearchVector(
+ Value(order.user.first_name), config="simple", weight="A"
+ )
+ if order.user.last_name:
+ search_vector += SearchVector(
+ Value(order.user.last_name), config="simple", weight="A"
+ )
+
+ if order.billing_address:
+ search_vector += generate_address_search_vector_value(
+ order.billing_address, weight="B"
+ )
+ if order.shipping_address:
+ search_vector += generate_address_search_vector_value(
+ order.shipping_address, weight="B"
+ )
- search_document += generate_order_lines_search_document_value(order)
+ payment_vector = generate_order_payments_search_vector_value(order)
+ if payment_vector:
+ search_vector += payment_vector
+ discount_vector = generate_order_discounts_search_vector_value(order)
+ if discount_vector:
+ search_vector += discount_vector
+ line_vector = generate_order_lines_search_vector_value(order)
+ if line_vector:
+ search_vector += line_vector
- return search_document.lower()
+ return search_vector
-def generate_order_payments_search_document_value(order: "Order"):
- payments_data = ""
+def generate_order_payments_search_vector_value(
+ order: "Order",
+) -> Optional[SearchVector]:
+ payment_vectors = []
for payment in order.payments.all():
- payments_data += graphene.Node.to_global_id("Payment", payment.id) + "\n"
- if psp_reference := payment.psp_reference:
- payments_data += psp_reference + "\n"
- return payments_data
-
+ payment_vectors.append(
+ SearchVector(
+ Value(graphene.Node.to_global_id("Payment", payment.id)),
+ config="simple",
+ weight="D",
+ )
+ )
+ if payment.psp_reference:
+ payment_vectors.append(
+ SearchVector(
+ Value(payment.psp_reference),
+ config="simple",
+ weight="D",
+ )
+ )
-def generate_order_discounts_search_document_value(order: "Order"):
- discount_data = ""
- for discount in order.discounts.all():
- for field in ["name", "translated_name"]:
- if value := getattr(discount, field):
- discount_data += value + "\n"
- return discount_data
+ if not payment_vectors:
+ return None
+ search_vector = reduce(add, payment_vectors)
-def generate_order_lines_search_document_value(order: "Order"):
- lines_data = "\n".join(
- [line.product_sku for line in order.lines.all() if line.product_sku]
- )
- if lines_data:
- lines_data += "\n"
- return lines_data
+ return search_vector
-def search_orders(qs, value):
+def generate_order_discounts_search_vector_value(
+ order: "Order",
+) -> Optional[SearchVector]:
+ discount_vectors = []
+ for discount in order.discounts.all():
+ if discount.name:
+ discount_vectors.append(
+ SearchVector(
+ Value(discount.name),
+ config="simple",
+ weight="D",
+ )
+ )
+ if discount.translated_name:
+ discount_vectors.append(
+ SearchVector(
+ Value(discount.translated_name),
+ config="simple",
+ weight="D",
+ )
+ )
+
+ if not discount_vectors:
+ return None
+
+ search_vector = reduce(add, discount_vectors)
+
+ return search_vector
+
+
+def generate_order_lines_search_vector_value(order: "Order") -> Optional[SearchVector]:
+ line_vectors = []
+ for line in order.lines.all():
+ if line.product_sku:
+ line_vectors.append(
+ SearchVector(
+ Value(line.product_sku),
+ config="simple",
+ weight="C",
+ )
+ )
+ if line.product_name:
+ line_vectors.append(
+ SearchVector(
+ Value(line.product_name),
+ config="simple",
+ weight="C",
+ )
+ )
+ if line.variant_name:
+ line_vectors.append(
+ SearchVector(
+ Value(line.variant_name),
+ config="simple",
+ weight="C",
+ )
+ )
+ if line.translated_product_name:
+ line_vectors.append(
+ SearchVector(
+ Value(line.translated_product_name),
+ config="simple",
+ weight="C",
+ )
+ )
+ if line.translated_variant_name:
+ line_vectors.append(
+ SearchVector(
+ Value(line.translated_variant_name),
+ config="simple",
+ weight="C",
+ )
+ )
+
+ if not line_vectors:
+ return None
+
+ search_vector = reduce(add, line_vectors)
+
+ return search_vector
+
+
+def search_orders(qs: "QuerySet[Order]", value) -> "QuerySet[Order]":
if value:
- lookup = Q()
- for val in value.split():
- lookup &= Q(search_document__ilike=val)
- qs = qs.filter(lookup)
+ query = SearchQuery(value, search_type="websearch", config="simple")
+ lookup = Q(search_vector=query)
+ qs = qs.filter(lookup).annotate(
+ search_rank=SearchRank(F("search_vector"), query)
+ )
return qs
diff --git a/saleor/order/tests/test_order_search.py b/saleor/order/tests/test_order_search.py
index 73735fae05..79526936d8 100644
--- a/saleor/order/tests/test_order_search.py
+++ b/saleor/order/tests/test_order_search.py
@@ -1,33 +1,31 @@
from decimal import Decimal
-import graphene
-
from ...discount import DiscountValueType
from ..models import OrderLine
-from ..search import prepare_order_search_document_value, update_order_search_document
+from ..search import prepare_order_search_vector_value, update_order_search_vector
-def test_update_order_search_document(order):
+def test_update_order_search_vector(order):
# given
- order.search_document = ""
- order.save(update_fields=["search_document"])
- assert not order.search_document
+ order.search_vector = ""
+ order.save(update_fields=["search_vector"])
+ assert not order.search_vector
# when
- update_order_search_document(order)
+ update_order_search_vector(order)
# then
- assert f"{order.number}\n{order.user_email}\n".lower() in order.search_document
+ assert order.search_vector
-def test_prepare_order_search_document_value(
+def test_prepare_order_search_vector_value(
order_with_lines, address_usa, payment_dummy
):
# given
order = order_with_lines
order.shipping_address = address_usa
order.save(update_fields=["shipping_address"])
- discount = order.discounts.create(
+ order.discounts.create(
value_type=DiscountValueType.FIXED,
name="discount",
translated_name="discount translated",
@@ -41,31 +39,13 @@ def test_prepare_order_search_document_value(
payment_dummy.save(update_fields=["psp_reference"])
# when
- search_document_value = prepare_order_search_document_value(order)
+ search_vector = prepare_order_search_vector_value(order)
# then
- assert str(order.number) in search_document_value
- user = order.user
- assert (
- f"{order.user_email}\n{user.email}\n{user.first_name}\n{user.last_name}".lower()
- in search_document_value
- )
- for address in [order.billing_address, order.shipping_address]:
- address_data = (
- f"{address.first_name}\n{address.last_name}\n"
- f"{address.street_address_1}\n{address.street_address_2}\n"
- f"{address.city}\n{address.postal_code}\n{address.country.name}\n"
- f"{address.country.code}\n{address.phone}\n"
- )
- assert address_data.lower() in search_document_value
- assert psp_reference.lower() in search_document_value
- assert discount.name in search_document_value
- assert discount.translated_name in search_document_value
- for line in order.lines.all():
- assert line.product_sku.lower() in search_document_value
+ assert search_vector
-def test_prepare_order_search_document_value_empty_relation_fields(
+def test_prepare_order_search_vector_value_empty_relation_fields(
order_with_lines, payment_dummy
):
# given
@@ -82,7 +62,6 @@ def test_prepare_order_search_document_value_empty_relation_fields(
payment_dummy.psp_reference = None
payment_dummy.save(update_fields=["psp_reference"])
- payment_id = graphene.Node.to_global_id("Payment", payment_dummy.pk)
lines = []
for line in order.lines.all():
@@ -91,18 +70,13 @@ def test_prepare_order_search_document_value_empty_relation_fields(
OrderLine.objects.bulk_update(lines, ["product_sku"])
# when
- search_document_value = prepare_order_search_document_value(order)
+ search_vector_value = prepare_order_search_vector_value(order)
# then
- user = order.user
- assert (
- f"#{order.number}\n{order.user_email}\n{user.email}\n"
- f"{user.first_name}\n{user.last_name}\n"
- f"{payment_id}\n".lower() == search_document_value
- )
+ assert search_vector_value
-def test_prepare_order_search_document_value_no_relations_data(order, address_usa):
+def test_prepare_order_search_vector_value_no_relations_data(order, address_usa):
# given
order.shipping_address = address_usa
order.user = None
@@ -115,7 +89,7 @@ def test_prepare_order_search_document_value_no_relations_data(order, address_us
assert not order.payments.all()
# when
- search_document_value = prepare_order_search_document_value(order)
+ search_vector_value = prepare_order_search_vector_value(order)
# then
- assert f"#{order.number}\n{order.user_email}\n".lower() == search_document_value
+ assert search_vector_value
diff --git a/saleor/plugins/anonymize/plugin.py b/saleor/plugins/anonymize/plugin.py
index 1542a89412..b19594937e 100644
--- a/saleor/plugins/anonymize/plugin.py
+++ b/saleor/plugins/anonymize/plugin.py
@@ -6,7 +6,7 @@ from faker import Faker
from ...account import search
from ...core.anonymize import obfuscate_address
-from ...order.search import prepare_order_search_document_value
+from ...order.search import prepare_order_search_vector_value
from ..base_plugin import BasePlugin
from . import obfuscate_order
@@ -48,7 +48,7 @@ class AnonymizePlugin(BasePlugin):
def order_created(self, order: "Order", previous_value: Any):
order = obfuscate_order(order)
- order.search_document = prepare_order_search_document_value(order)
+ order.search_vector = prepare_order_search_vector_value(order)
order.save()
def customer_created(self, customer: "User", previous_value: Any) -> Any:
diff --git a/saleor/product/search.py b/saleor/product/search.py
index 1f2f0cfbe6..22c676d4ff 100644
--- a/saleor/product/search.py
+++ b/saleor/product/search.py
@@ -60,9 +60,9 @@ def prepare_product_search_vector_value(
) -> SearchVector:
if not already_prefetched:
prefetch_related_objects([product], *PRODUCT_FIELDS_TO_PREFETCH)
- search_vector = SearchVector(Value(product.name), weight="A") + SearchVector(
- Value(product.description_plaintext), weight="C"
- )
+ search_vector = SearchVector(
+ Value(product.name), config="simple", weight="A"
+ ) + SearchVector(Value(product.description_plaintext), config="simple", weight="C")
attributes_vector = generate_attributes_search_vector_value(
product.attributes.all()
)
@@ -79,9 +79,11 @@ def generate_variants_search_vector_value(product: "Product") -> Optional[Search
variants = list(product.variants.all())
variant_vectors = [
- SearchVector(Value(variant.sku), Value(variant.name), weight="A")
+ SearchVector(
+ Value(variant.sku), Value(variant.name), config="simple", weight="A"
+ )
if variant.sku
- else SearchVector(Value(variant.name), weight="A")
+ else SearchVector(Value(variant.name), config="simple", weight="A")
for variant in variants
if variant.sku or variant.name
]
@@ -136,7 +138,11 @@ def generate_attributes_search_vector_value(
if values_list:
new_vector = reduce(
- add, (SearchVector(Value(v), weight="B") for v in values_list)
+ add,
+ (
+ SearchVector(Value(v), config="simple", weight="B")
+ for v in values_list
+ ),
)
if search_vector is not None:
search_vector += new_vector
@@ -147,7 +153,7 @@ def generate_attributes_search_vector_value(
def search_products(qs, value):
if value:
- query = SearchQuery(value, search_type="websearch")
+ query = SearchQuery(value, search_type="websearch", config="simple")
lookup = Q(search_vector=query)
qs = qs.filter(lookup).annotate(
search_rank=SearchRank(F("search_vector"), query)
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 488612e8f0..b6d4ebc41d 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -29,7 +29,7 @@ from prices import Money, TaxedMoney, fixed_discount
from ..account.models import Address, StaffNotificationRecipient, User
from ..app.models import App, AppExtension, AppInstallation
-from ..app.types import AppExtensionMount, AppExtensionTarget, AppType
+from ..app.types import AppExtensionMount, AppType
from ..attribute import AttributeEntityType, AttributeInputType, AttributeType
from ..attribute.models import (
Attribute,
@@ -41,7 +41,7 @@ from ..attribute.utils import associate_attribute_values_to_instance
from ..checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ..checkout.models import Checkout, CheckoutLine
from ..checkout.utils import add_variant_to_checkout, add_voucher_to_checkout
-from ..core import EventDeliveryStatus, JobStatus, TimePeriodType
+from ..core import EventDeliveryStatus, JobStatus
from ..core.models import EventDelivery, EventDeliveryAttempt, EventPayload
from ..core.payments import PaymentInterface
from ..core.units import MeasurementUnits
@@ -76,7 +76,7 @@ from ..order.models import (
OrderEvent,
OrderLine,
)
-from ..order.search import prepare_order_search_document_value
+from ..order.search import prepare_order_search_vector_value
from ..order.utils import recalculate_order
from ..page.models import Page, PageTranslation, PageType
from ..payment import ChargeStatus, TransactionKind
@@ -817,9 +817,9 @@ def order(customer_user, channel_USD):
@pytest.fixture
-def order_with_search_document_value(order):
- order.search_document = prepare_order_search_document_value(order)
- order.save(update_fields=["search_document"])
+def order_with_search_vector_value(order):
+ order.search_vector = prepare_order_search_vector_value(order)
+ order.save(update_fields=["search_vector"])
return order
@@ -5685,8 +5685,8 @@ def allocations(order_list, stock, channel_USD):
)
for order in order_list:
- order.search_document = prepare_order_search_document_value(order)
- Order.objects.bulk_update(order_list, ["search_document"])
+ order.search_vector = prepare_order_search_vector_value(order)
+ Order.objects.bulk_update(order_list, ["search_vector"])
return Allocation.objects.bulk_create(
[