Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Improve searching experience (#18802)
Iga Karbowiak1233f8eb3c56
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b8feedb1c1..7a6816cb5e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,9 +5,10 @@ All notable, unreleased changes to this project will be documented in this file.# 3.23.0 [Unreleased]### Breaking changes+- Fix missing denormalization of shipping methods metadata when creating an order.- - Shipping method metadata is now copied to dedicated order fields (`shipping_method_metadata` and `shipping_method_private_metadata`) during checkout-to-order conversion. This ensures that order metadata remains consistent even if the original shipping method is modified or deleted. As a result, updates made to a shipping method's metadata after order creation will no longer be reflected in the order's `shippingMethod.metadata` field.- - Shipping method metadata is now also denormalized during draft order finalization, ensuring consistent behavior across all order creation flows.+ - Shipping method metadata is now copied to dedicated order fields (`shipping_method_metadata` and `shipping_method_private_metadata`) during checkout-to-order conversion. This ensures that order metadata remains consistent even if the original shipping method is modified or deleted. As a result, updates made to a shipping method's metadata after order creation will no longer be reflected in the order's `shippingMethod.metadata` field.+ - Shipping method metadata is now also denormalized during draft order finalization, ensuring consistent behavior across all order creation flows.- Fields `options`, `mount` and `target` are removed from `AppExtension` and `AppManifestExtension` types. Use `mountName`, `targetName` and `settings`- Deprecate the `hasVariants` field on `ProductType`. This setting is a legacy artifact from the former Simple/Configurable product distinction. Products can have multiple variants regardless of this flag. Previously, it only prevented assigning variant attributes to a product type; this restriction will no longer apply.- Improved error handling in Federation - #18718 by @NyanKiyoshi@@ -21,6 +22,7 @@ All notable, unreleased changes to this project will be documented in this file.- Mutations `channelCreate` and `channelUpdate` now raise GraphQL errors instead `INVALID` when negative `MINUTE`/`HOUR`/`DAY` values are passed.### GraphQL API+- Gift cards support as payment method within Transaction API (read more in the [docs](https://docs.saleor.io/developer/gift-cards#using-gift-cards-in-checkout)).- `Attribute` fields `name`, `slug` and `type` are now non-nullable in schema.- Added new scalar `NonNegativeInt` which allows integer values greater than or equal to zero.@@ -30,10 +32,15 @@ All notable, unreleased changes to this project will be documented in this file.For order webhook events, sync webhooks (such as `ORDER_CALCULATE_TAXES` and `ORDER_FILTER_SHIPPING_METHODS`) are no longer pre-fired before sending async webhook events. Sync webhooks are now only triggered when their data is actually requested, improving performance and decoupling async event delivery from sync webhook execution.### Other changes-- Improved page search with search vectors. Pages can now be searched by slug, title, content, attribute values, and page type information.+- Enhanced search functionality across key entities (products, orders, gift cards, checkouts, pages, and users) with advanced query capabilities:+ - Prefix matching: partial word searches (e.g., "coff" matches "coffee")+ - Boolean operators: `AND`, `OR`, and `-` (NOT) for complex queries+ - Exact phrase matching: use quotation marks `" "` for precise searches+ - Relevance-based ranking: exact matches score higher than prefix matches and appear first by default (can be overridden with `sortBy` parameter)+ - New `RANK` sort field available when using search filters to sort by relevance score+- Improved page search with search vectors. Pages can now be searched by slug, title, content, attribute values, and page type information.- Fix send order confirmation email to staff - #18342 by @Shaokun-X-- Validation on `AppExtension` is now removed. Saleor will accept string values for `mount` and `target` from Manifest during App installation and JSON value for `options` field.Validation is now performed on the frontend (Dashboard). This change increases velocity of features related to apps and extensions, now Dashboard is only entity that ensures the contract- Improve user search. Use search vector functionality to enable searching users by email address, first name, last name, and addresses.@@ -42,5 +49,6 @@ Validation is now performed on the frontend (Dashboard). This change increases v- The app can now be installed without providing a `tokenTargetUrl` in the manifest file.### Deprecations+- Deprecate the `hasVariants` field on `ProductType`.- Deprecate export mutations (`exportProducts`, `exportGiftCards`, `exportVoucherCodes`). All data can be fetched via the GraphQL API and parsed into the desired format by apps or external tools.diff --git a/saleor/account/search.py b/saleor/account/search.pyindex 50ba768be3..744ee4d7db 100644--- a/saleor/account/search.py+++ b/saleor/account/search.py@@ -1,7 +1,6 @@from typing import TYPE_CHECKING-from django.contrib.postgres.search import SearchQuery, SearchRank-from django.db.models import F, Q, QuerySet, Value, prefetch_related_objects+from django.db.models import Value, prefetch_related_objectsfrom ..core.postgres import FlatConcatSearchVector, NoValidationSearchVector@@ -138,13 +137,3 @@ def generate_address_search_vector_value())return search_vectors---def search_users(qs: "QuerySet[User]", value) -> "QuerySet[User]":- if value:- 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 qsdiff --git a/saleor/checkout/search/indexing.py b/saleor/checkout/search/indexing.pyindex 7739161c5e..681cedd47f 100644--- a/saleor/checkout/search/indexing.py+++ b/saleor/checkout/search/indexing.py@@ -2,9 +2,8 @@ from typing import TYPE_CHECKINGimport graphenefrom django.conf import settings-from django.contrib.postgres.search import SearchQuery, SearchRankfrom django.db import transaction-from django.db.models import F, Q, Value+from django.db.models import Valuefrom ...account.search import (generate_address_search_vector_value,@@ -20,8 +19,6 @@ from .loaders import CheckoutData, CheckoutLineData, TransactionData, load_checkif TYPE_CHECKING:from uuid import UUID- from django.db.models import QuerySet-from ...payment.models import Paymentfrom ..models import Checkout@@ -218,14 +215,3 @@ def generate_checkout_lines_search_vector_value()return line_vectors---def search_checkouts(qs: "QuerySet[Checkout]", value) -> "QuerySet[Checkout]":- """Filter checkouts by search query using the search_vector field."""- if value:- 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 qsdiff --git a/saleor/checkout/tests/test_search_indexing.py b/saleor/checkout/tests/test_search_indexing.pyindex d32c7e91ac..82e5b091a2 100644--- a/saleor/checkout/tests/test_search_indexing.py+++ b/saleor/checkout/tests/test_search_indexing.py@@ -14,7 +14,6 @@ from ..search.indexing import (generate_checkout_payments_search_vector_value,generate_checkout_transactions_search_vector_value,prepare_checkout_search_vector_value,- search_checkouts,update_checkouts_search_vector,)from ..search.loaders import (@@ -615,175 +614,6 @@ def test_generate_checkout_transactions_search_vector_value_respects_max_limit(assert len(result) == limit * 2-def test_search_checkouts_with_value(checkout, checkout_JPY):- # given- checkout.email = "[email protected]"- checkout.save(update_fields=["email"])- update_checkouts_search_vector([checkout, checkout_JPY])- qs = Checkout.objects.all()-- # when- result = search_checkouts(qs, "[email protected]")-- # then- assert result.count() == 1- assert result.first() == checkout---def test_search_checkouts_without_value(checkout, checkout_JPY):- # given- qs = Checkout.objects.all()-- # when- result = search_checkouts(qs, None)-- # then- assert result.count() == Checkout.objects.count()---def test_search_checkouts_by_token(checkout, checkout_JPY):- # given- update_checkouts_search_vector([checkout, checkout_JPY])- qs = Checkout.objects.all()-- # when- result = search_checkouts(qs, str(checkout.token))-- # then- assert result.count() == 1- assert result.first() == checkout---def test_search_checkouts_by_user_email(checkout, checkout_JPY, customer_user):- # given- checkout.user = customer_user- checkout.save(update_fields=["user"])-- checkout_JPY.user = customer_user- checkout_JPY.save(update_fields=["user"])-- update_checkouts_search_vector([checkout, checkout_JPY])- qs = Checkout.objects.all()-- # when- result = search_checkouts(qs, customer_user.email)-- # then- assert result.count() == 2---def test_search_checkouts_by_user_name(checkout, checkout_JPY, customer_user):- # given- checkout.user = customer_user- checkout.save(update_fields=["user"])-- checkout_JPY.user = None- checkout_JPY.save(update_fields=["user"])- update_checkouts_search_vector([checkout, checkout_JPY])- qs = Checkout.objects.all()-- # when- result = search_checkouts(qs, customer_user.first_name)-- # then- assert result.count() == 1- assert result.first() == checkout---def test_search_checkouts_by_product_name(checkout_with_item, checkout_JPY, product):- # given- update_checkouts_search_vector([checkout_with_item, checkout_JPY])- qs = Checkout.objects.all()-- # when- result = search_checkouts(qs, product.name)-- # then- assert result.count() == 1- assert result.first() == checkout_with_item---def test_search_checkouts_by_sku(checkout_with_item, checkout_JPY):- # given- sku = "UNIQUE-SKU-999"- line = checkout_with_item.lines.first()- variant = line.variant- variant.sku = sku- variant.save(update_fields=["sku"])- update_checkouts_search_vector([checkout_with_item, checkout_JPY])- qs = Checkout.objects.all()-- # when- result = search_checkouts(qs, sku)-- # then- assert result.count() == 1- assert result.first() == checkout_with_item---def test_search_checkouts_by_payment_psp_reference(checkout, checkout_JPY):- # given- psp_reference = "UNIQUE-PSP-REF-789"- Payment.objects.create(- gateway="mirumee.payments.dummy",- is_active=True,- checkout=checkout_JPY,- total=Decimal("10.00"),- currency="USD",- psp_reference=psp_reference,- )- update_checkouts_search_vector([checkout, checkout_JPY])- qs = Checkout.objects.all()-- # when- result = search_checkouts(qs, psp_reference)-- # then- assert result.count() == 1- assert result.first() == checkout_JPY---def test_search_checkouts_by_transaction_psp_reference(checkout, checkout_JPY):- # given- psp_reference = "UNIQUE-TRANS-PSP-456"- TransactionItem.objects.create(- name="Credit card",- psp_reference=psp_reference,- available_actions=["refund"],- currency="USD",- checkout_id=checkout_JPY.pk,- charged_value=Decimal(10),- )- update_checkouts_search_vector([checkout, checkout_JPY])- qs = Checkout.objects.all()-- # when- result = search_checkouts(qs, psp_reference)-- # then- assert result.count() == 1- assert result.first() == checkout_JPY---def test_search_checkouts_by_partial_email(checkout, checkout_with_item):- # given- checkout.email = "[email protected]"- checkout.save(update_fields=["email"])- checkout_with_item.email = "[email protected]"- checkout_with_item.save(update_fields=["email"])-- update_checkouts_search_vector([checkout, checkout_with_item])- qs = Checkout.objects.all()-- # when- result = search_checkouts(qs, "test")-- # then- results_list = list(result)- assert len(results_list) == 1- assert results_list[0] == checkout--def test_update_checkouts_search_vector_handles_deleted_checkout(checkout_with_item, checkout_JPY):diff --git a/saleor/core/search.py b/saleor/core/search.pynew file mode 100644index 0000000000..3acba2e8ed--- /dev/null+++ b/saleor/core/search.py@@ -0,0 +1,175 @@+import re+from typing import TYPE_CHECKING++from django.contrib.postgres.search import SearchQuery, SearchRank+from django.db.models import F, Value++if TYPE_CHECKING:+ from django.db.models import QuerySet+++def _sanitize_word(word: str) -> str:+ """Remove PostgreSQL tsquery metacharacters from a word.++ Replaces special characters that have meaning in tsquery syntax with spaces,+ so that e.g. "22:20" becomes "22 20" (two separate tokens) rather than "2220".++ Preserved: alphanumeric, underscore, hyphen, @, period+ Replaced with space: parentheses, &, |, !, :, <, >, ', *+ """+ return re.sub(r"[()&|!:<>\'*]", " ", word).strip()+++def _tokenize(value: str) -> list[dict]:+ """Tokenize a search string into structured tokens.++ Recognizes:+ - Quoted phrases: "green tea"+ - OR operator: coffee OR tea+ - Negation: -decaf+ - Regular words: coffee+ """+ tokens: list[dict] = []+ i = 0++ while i < len(value):+ # Skip whitespace+ if value[i].isspace():+ i += 1+ continue++ # Check for negation prefix+ negated = False+ if value[i] == "-" and i + 1 < len(value) and not value[i + 1].isspace():+ negated = True+ i += 1++ # Quoted phrase+ if i < len(value) and value[i] == '"':+ end = value.find('"', i + 1)+ if end == -1:+ phrase = value[i + 1 :]+ i = len(value)+ else:+ phrase = value[i + 1 : end]+ i = end + 1+ words = []+ for w in phrase.split():+ sanitized = _sanitize_word(w)+ words.extend(sanitized.split())+ if words:+ tokens.append({"type": "phrase", "words": words, "negated": negated})+ continue++ # Read the next word+ end = i+ while end < len(value) and not value[end].isspace():+ end += 1+ raw_word = value[i:end]+ i = end++ # OR operator (must not be negated)+ if raw_word == "OR" and not negated:+ tokens.append({"type": "or"})+ continue++ # AND operator – explicit AND is a no-op (AND is implicit between terms)+ if raw_word == "AND" and not negated:+ continue++ sanitized = _sanitize_word(raw_word)+ for word in sanitized.split():+ tokens.append({"type": "word", "word": word, "negated": negated})++ return tokens+++def parse_search_query(value: str) -> str | None:+ """Parse a search string into a raw PostgreSQL tsquery with prefix matching.++ Supports websearch-compatible syntax:+ - Multiple words (implicit AND): "coffee shop" -> coffee:* & shop:*+ - OR operator: "coffee OR tea" -> coffee:* | tea:*+ - Negation: "-decaf" -> !decaf:*+ - Quoted phrases (exact match): '"green tea"' -> (green <-> tea)++ Returns:+ A raw tsquery string, or None if the input yields no searchable terms.++ """+ value = value.strip()+ if not value:+ return None++ tokens = _tokenize(value)+ if not tokens:+ return None++ parts: list[str] = []+ pending_connector = " & "++ for token in tokens:+ if token["type"] == "or":+ pending_connector = " | "+ continue++ # Insert connector between terms+ if parts:+ parts.append(pending_connector)+ pending_connector = " & "++ neg = "!" if token["negated"] else ""++ if token["type"] == "word":+ parts.append(f"{neg}{token['word']}:*")++ elif token["type"] == "phrase":+ words = token["words"]+ if len(words) == 1:+ parts.append(f"{neg}{words[0]}")+ else:+ # Use <-> (followed-by) for phrase matching+ phrase_tsquery = " <-> ".join(words)+ if neg:+ parts.append(f"!({phrase_tsquery})")+ else:+ parts.append(f"({phrase_tsquery})")++ result = "".join(parts)+ return result if result else None+++def prefix_search(qs: "QuerySet", value: str) -> "QuerySet":+ """Apply prefix-based search to a queryset with perfect match prioritization.++ Supports websearch-compatible syntax (AND, OR, negation, quoted phrases)+ while adding prefix matching so partial words produce results.++ Scoring: exact (websearch) matches get 2x weight, prefix matches get 1x.++ The queryset must have a ``search_vector`` SearchVectorField.+ """+ if not value:+ # return a original queryset annotated with search_rank=0+ # to allow default RANK sorting+ return qs.annotate(search_rank=Value(0))++ parsed_query = parse_search_query(value)+ if not parsed_query:+ # return empty queryset as the provided value is not searchable+ # annotated with search_rank=0 to allow default RANK sorting+ return qs.annotate(search_rank=Value(0)).none()++ # Prefix query – broadens matching via :*+ prefix_query = SearchQuery(parsed_query, search_type="raw", config="simple")++ # Exact (websearch) query – used only for ranking, not filtering+ exact_query = SearchQuery(value, search_type="websearch", config="simple")++ qs = qs.filter(search_vector=prefix_query).annotate(+ prefix_rank=SearchRank(F("search_vector"), prefix_query),+ exact_rank=SearchRank(F("search_vector"), exact_query),+ search_rank=F("exact_rank") * 2 + F("prefix_rank"),+ )++ return qsdiff --git a/saleor/core/tests/test_postgresql_search.py b/saleor/core/tests/test_postgresql_search.pyindex 91d2ac7ba2..60b82a537c 100644--- a/saleor/core/tests/test_postgresql_search.py+++ b/saleor/core/tests/test_postgresql_search.py@@ -5,9 +5,9 @@ from django.utils.text import slugifyfrom ...account.models import Addressfrom ...product.models import Product, ProductChannelListing-from ...product.search import search_productsfrom ...tests.utils import dummy_editorjsfrom ..postgres import FlatConcat+from ..search import prefix_searchPRODUCTS = [("Arabica Coffee", "The best grains in galactic"),@@ -45,7 +45,7 @@ def named_products(category, product_type, channel_USD):def execute_search(phrase):"""Execute storefront search."""qs = Product.objects.all()- return search_products(qs, phrase)+ return prefix_search(qs, phrase)@pytest.mark.parametrize(diff --git a/saleor/core/tests/test_search.py b/saleor/core/tests/test_search.pynew file mode 100644index 0000000000..c18dc8b785--- /dev/null+++ b/saleor/core/tests/test_search.py@@ -0,0 +1,423 @@+import pytest+from django.contrib.postgres.search import SearchVector+from django.db.models import Value++from ...account.models import User+from ...account.search import update_user_search_vector+from ...checkout.models import Checkout+from ...checkout.search.indexing import update_checkouts_search_vector+from ...product.models import Product, ProductChannelListing+from ..search import _sanitize_word, parse_search_query, prefix_search+++def test_sanitize_word_removes_tsquery_metacharacters():+ # given+ word_with_metacharacters = "test()&|!:<>'"++ # when+ result = _sanitize_word(word_with_metacharacters)++ # then+ assert result == "test"+++def test_sanitize_word_preserves_safe_characters():+ # given+ safe_word = "[email protected]"++ # when+ result = _sanitize_word(safe_word)++ # then+ assert result == "[email protected]"+++def test_sanitize_word_handles_empty_string():+ # given+ empty_string = ""++ # when+ result = _sanitize_word(empty_string)++ # then+ assert result == ""+++def test_sanitize_word_handles_only_metacharacters():+ # given+ only_metacharacters = "()&|!"++ # when+ result = _sanitize_word(only_metacharacters)++ # then+ assert result == ""+++def test_parse_search_query_single_word():+ assert parse_search_query("coffee") == "coffee:*"+++def test_parse_search_query_multiple_words_implicit_and():+ assert parse_search_query("coffee shop") == "coffee:* & shop:*"+++def test_parse_search_query_or_operator():+ assert parse_search_query("coffee OR tea") == "coffee:* | tea:*"+++def test_parse_search_query_negation():+ assert parse_search_query("coffee -decaf") == "coffee:* & !decaf:*"+++def test_parse_search_query_quoted_phrase():+ assert parse_search_query('"green tea"') == "(green <-> tea)"+++def test_parse_search_query_quoted_phrase_with_other_terms():+ assert parse_search_query('coffee "green tea"') == "coffee:* & (green <-> tea)"+++def test_parse_search_query_negated_quoted_phrase():+ assert parse_search_query('coffee -"green tea"') == "coffee:* & !(green <-> tea)"+++def test_parse_search_query_or_with_negation():+ assert parse_search_query("coffee OR tea -decaf") == "coffee:* | tea:* & !decaf:*"+++def test_parse_search_query_with_email():+ assert parse_search_query("[email protected]") == "[email protected]:*"+++def test_parse_search_query_empty_string():+ assert parse_search_query("") is None+++def test_parse_search_query_whitespace_normalization():+ assert parse_search_query(" multiple spaces ") == "multiple:* & spaces:*"+++def test_parse_search_query_preserves_case():+ assert parse_search_query("Coffee SHOP") == "Coffee:* & SHOP:*"+++def test_parse_search_query_single_word_in_quotes():+ # Single word in quotes should be an exact match (no prefix)+ assert parse_search_query('"coffee"') == "coffee"+++def test_parse_search_query_quoted_word_with_or():+ assert parse_search_query('"aaron" OR aallen') == "aaron | aallen:*"+++def test_parse_search_query_or_two_plain_words():+ assert parse_search_query("aaron0 OR aallen") == "aaron0:* | aallen:*"+++def test_parse_search_query_or_between_phrases():+ assert (+ parse_search_query('"green tea" OR "black coffee"')+ == "(green <-> tea) | (black <-> coffee)"+ )+++def test_parse_search_query_negated_word_with_or():+ assert parse_search_query("coffee OR tea -decaf -sugar") == (+ "coffee:* | tea:* & !decaf:* & !sugar:*"+ )+++def test_parse_search_query_phrase_and_prefix_and_negation():+ assert parse_search_query('"green tea" maker -cheap') == (+ "(green <-> tea) & maker:* & !cheap:*"+ )+++def test_parse_search_query_multiple_or_operators():+ assert parse_search_query("coffee OR tea OR juice") == (+ "coffee:* | tea:* | juice:*"+ )+++def test_parse_search_query_or_with_negated_phrase():+ assert parse_search_query('coffee OR -"green tea"') == (+ "coffee:* | !(green <-> tea)"+ )+++def test_parse_search_query_quoted_exact_and_prefix_mixed():+ assert parse_search_query('"exact" prefix') == "exact & prefix:*"+++def test_parse_search_query_multiple_phrases_with_words():+ assert parse_search_query('"green tea" "black coffee" sugar') == (+ "(green <-> tea) & (black <-> coffee) & sugar:*"+ )+++def test_parse_search_query_or_chain_with_phrase_in_middle():+ assert parse_search_query('coffee OR "green tea" OR juice') == (+ "coffee:* | (green <-> tea) | juice:*"+ )+++def test_parse_search_query_negation_before_or():+ # Negation applies to decaf, then OR connects to tea+ assert parse_search_query("coffee -decaf OR tea") == ("coffee:* & !decaf:* | tea:*")+++def test_parse_search_query_parentheses_are_stripped():+ # Parentheses are not supported for grouping; they are stripped as special chars+ assert parse_search_query("(green AND Tea) OR (coffee AND -black)") == (+ "green:* & Tea:* | coffee:* & !black:*"+ )+++def test_parse_search_query_lowercase_or_is_regular_word():+ # Only uppercase OR is recognized as an operator+ assert parse_search_query("coffee or tea") == "coffee:* & or:* & tea:*"+++def test_parse_search_query_lowercase_and_is_regular_word():+ assert parse_search_query("coffee and tea") == "coffee:* & and:* & tea:*"+++def test_parse_search_query_mixed_case_or_is_regular_word():+ assert parse_search_query("coffee Or tea") == "coffee:* & Or:* & tea:*"+++def test_parse_search_query_unclosed_quote():+ # Unclosed quote should still parse the words as a phrase+ assert parse_search_query('"green tea') == "(green <-> tea)"+++def test_parse_search_query_whitespace_only_returns_none():+ assert parse_search_query(" ") is None+++def test_parse_search_query_hyphenated_words_preserved():+ assert parse_search_query("my-product-slug") == "my-product-slug:*"+++def test_parse_search_query_quoted_phrase_with_metacharacters():+ assert parse_search_query('"test(value)"') == "(test <-> value)"+++def products_for_search(category, product_type, channel_USD):+ products = []+ for name, description in [+ ("Coffee Maker", "Best coffee maker"),+ ("Coffeehouse Special", "Special blend for coffeehouses"),+ ("Tea Kettle", "Great for brewing tea"),+ ]:+ product = Product.objects.create(+ name=name,+ slug=name.lower().replace(" ", "-"),+ description_plaintext=description,+ product_type=product_type,+ category=category,+ search_vector=(+ SearchVector(Value(name), config="simple", weight="A")+ + SearchVector(Value(description), config="simple", weight="C")+ ),+ )+ ProductChannelListing.objects.create(+ product=product, channel=channel_USD, is_published=True+ )+ products.append(product)+ return products+++def test_prefix_search_returns_prefix_matches(products_for_search):+ # given+ qs = Product.objects.all()++ # when+ results = prefix_search(qs, "coff")++ # then+ assert results.count() == 2+ names = {p.name for p in results}+ assert names == {"Coffee Maker", "Coffeehouse Special"}+++def test_prefix_search_perfect_match_scores_higher(products_for_search):+ # given+ qs = Product.objects.all()++ # when+ results = list(prefix_search(qs, "coffee").order_by("-search_rank"))++ # then – "Coffee Maker" has exact word match, ranks above "Coffeehouse"+ assert len(results) == 2+ assert results[0].name == "Coffee Maker"+++def test_prefix_search_empty_value_returns_all(products_for_search):+ # when+ results = prefix_search(Product.objects.all(), "")++ # then+ assert results.count() == 3+++def test_prefix_search_not_searchable_value_returns_nothing(products_for_search):+ # when+ results = prefix_search(Product.objects.all(), ":::")++ # then+ assert results.count() == 0+++def test_prefix_search_no_matches(products_for_search):+ # when+ results = prefix_search(Product.objects.all(), "xyz")++ # then+ assert results.count() == 0+++def test_prefix_search_case_insensitive(products_for_search):+ # when+ results = prefix_search(Product.objects.all(), "COFFEE")++ # then+ assert results.count() == 2+++def test_prefix_search_multiple_terms_and(products_for_search):+ # when+ results = prefix_search(Product.objects.all(), "coffee mak")++ # then – only "Coffee Maker" matches both terms+ assert results.count() == 1+ assert results.first().name == "Coffee Maker"+++def test_prefix_search_or_operator(products_for_search):+ # when+ results = prefix_search(Product.objects.all(), "coffee OR tea")++ # then – all three products match (Coffee Maker, Coffeehouse, Tea Kettle)+ assert results.count() == 3+++def test_prefix_search_negation(products_for_search):+ # when+ results = prefix_search(Product.objects.all(), "coffee -special")++ # then – only "Coffee Maker" remains (Coffeehouse Special is excluded)+ assert results.count() == 1+ assert results.first().name == "Coffee Maker"+++def users_for_search():+ users = []+ for email, first, last in [+ ("[email protected]", "John", "Doe"),+ ("[email protected]", "Johnny", "Smith"),+ ("[email protected]", "Jane", "Doe"),+ ]:+ user = User.objects.create(email=email, first_name=first, last_name=last)+ update_user_search_vector(user, attach_addresses_data=False)+ users.append(user)+ return users+++def test_prefix_search_users(users_for_search):+ # when+ results = prefix_search(User.objects.all(), "joh")++ # then+ assert results.count() == 2+ emails = {u.email for u in results}+ assert emails == {"[email protected]", "[email protected]"}+++def test_prefix_search_users_perfect_match_priority(users_for_search):+ # when+ results = list(prefix_search(User.objects.all(), "john").order_by("-search_rank"))++ # then – "John" exact match should rank higher than "Johnny"+ assert len(results) == 2+ assert results[0].first_name == "John"+++def test_prefix_search_checkout_exact_match_priority(+ channel_USD,+):+ # given++ checkouts = []++ # Checkout 1: email starts with "aaron00"+ checkout1 = Checkout.objects.create(+ channel=channel_USD,+ email="[email protected]",+ user=None,+ currency="USD",+ )++ # Checkout 2: different email, user is "Aaron Smith" (exact match for "aaron")+ user2 = User.objects.create(+ email="[email protected]", first_name="Aaron", last_name="Smith"+ )+ checkout2 = Checkout.objects.create(+ channel=channel_USD,+ email=user2.email,+ user=user2,+ currency="USD",+ )++ # Checkout 3: email contains "aaron" in middle, user is "Bob Wilson"+ # - not found as search uses prefix match+ user3 = User.objects.create(+ email="[email protected]", first_name="Bob", last_name="Wilson"+ )+ checkout3 = Checkout.objects.create(+ channel=channel_USD,+ email=user3.email,+ user=user3,+ currency="USD",+ )++ # Checkout 4: user last name is "Aaron" (exact match), and email starts with `aaron`+ user4 = User.objects.create(+ email="[email protected]", first_name="Jane", last_name="Aaron"+ )+ checkout4 = Checkout.objects.create(+ channel=channel_USD,+ email=user4.email,+ user=user4,+ currency="USD",+ )++ # Checkout 5: no match at all+ user5 = User.objects.create(+ email="[email protected]", first_name="Charlie", last_name="Brown"+ )+ checkout5 = Checkout.objects.create(+ channel=channel_USD,+ email=user5.email,+ user=user5,+ currency="USD",+ )++ checkouts = [checkout1, checkout2, checkout3, checkout4, checkout5]++ # Update search vectors+ update_checkouts_search_vector(checkouts)++ # when+ results = list(+ prefix_search(Checkout.objects.all(), "aaron").order_by("-search_rank")+ )++ # then+ expected_indexes = [3, 1, 0]+ assert len(results) == len(expected_indexes)+ for result, expected_index in zip(results, expected_indexes, strict=False):+ assert result.pk == checkouts[expected_index].pkdiff --git a/saleor/giftcard/search.py b/saleor/giftcard/search.pyindex ce6b4b5ff2..8d05886df5 100644--- a/saleor/giftcard/search.py+++ b/saleor/giftcard/search.py@@ -1,5 +1,4 @@from django.conf import settings-from django.contrib.postgres.search import SearchQueryfrom django.db.models import Q, QuerySet, Value, prefetch_related_objectsfrom ..account.models import User@@ -68,10 +67,3 @@ def update_gift_cards_search_vector(gift_cards: list[GiftCard]):)GiftCard.objects.bulk_update(gift_cards, ["search_vector", "search_index_dirty"])---def search_gift_cards(qs, value):- if value:- query = SearchQuery(value, search_type="websearch", config="simple")- qs = qs.filter(search_vector=query)- return qsdiff --git a/saleor/graphql/account/filters.py b/saleor/graphql/account/filters.pyindex b928b35a2a..57af7916d4 100644--- a/saleor/graphql/account/filters.py+++ b/saleor/graphql/account/filters.py@@ -2,7 +2,7 @@ import django_filtersfrom django.db.models import Count, Exists, OuterReffrom ...account.models import Address, User-from ...account.search import search_users+from ...core.search import prefix_searchfrom ...order.models import Orderfrom ..core.doc_category import DOC_CATEGORY_USERSfrom ..core.filters import (@@ -66,7 +66,7 @@ def filter_staff_status(qs, _, value):def filter_user_search(qs, _, value):- return search_users(qs, value)+ return prefix_search(qs, value)def filter_search(qs, _, value):diff --git a/saleor/graphql/account/schema.py b/saleor/graphql/account/schema.pyindex c4e4189e54..026cae02e2 100644--- a/saleor/graphql/account/schema.py+++ b/saleor/graphql/account/schema.py@@ -1,6 +1,6 @@import graphene-from ...account.search import search_users+from ...core.search import prefix_searchfrom ...permission.auth_filters import AuthorizationFiltersfrom ...permission.enums import AccountPermissions, OrderPermissionsfrom ...permission.utils import message_one_of_permissions_required@@ -11,7 +11,10 @@ from ..core.descriptions import ADDED_IN_322, DEPRECATED_IN_3X_INPUTfrom ..core.doc_category import DOC_CATEGORY_USERSfrom ..core.fields import BaseField, FilterConnectionField, PermissionsFieldfrom ..core.filters import FilterInputObjectType-from ..core.utils import from_global_id_or_error+from ..core.utils import (+ from_global_id_or_error,+ validate_and_apply_search_rank_sorting,+)from ..core.validators import validate_one_of_args_is_in_queryfrom .bulk_mutations import (CustomerBulkDelete,@@ -82,7 +85,7 @@ from .resolvers import (resolve_staff_users,resolve_user,)-from .sorters import PermissionGroupSortingInput, UserSortingInput+from .sorters import PermissionGroupSortingInput, UserSortField, UserSortingInputfrom .types import (Address,AddressValidationData,@@ -227,10 +230,13 @@ class AccountQueries(graphene.ObjectType):@staticmethoddef resolve_customers(_root, info: ResolveInfo, **kwargs):+ validate_and_apply_search_rank_sorting(+ kwargs, UserSortField.RANK, "UserSortingInput", info+ )search = kwargs.get("search")qs = resolve_customers(info)if search:- qs = search_users(qs, search)+ qs = prefix_search(qs, search)qs = filter_connection_queryset(qs, kwargs, allow_replica=info.context.allow_replica)diff --git a/saleor/graphql/account/sorters.py b/saleor/graphql/account/sorters.pyindex 33ffa52eb1..4b727db1d4 100644--- a/saleor/graphql/account/sorters.py+++ b/saleor/graphql/account/sorters.py@@ -11,12 +11,20 @@ class UserSortField(BaseEnum):ORDER_COUNT = ["order_count", "email"]CREATED_AT = ["date_joined", "pk"]LAST_MODIFIED_AT = ["updated_at", "pk"]+ RANK = ["search_rank", "pk"]class Meta:doc_category = DOC_CATEGORY_USERS@propertydef description(self):+ descriptions = {+ UserSortField.RANK.name: ( # type: ignore[attr-defined] # graphene.Enum is not typed # noqa: E501+ "rank. Note: This option is available only with the `search` filter."+ ),+ }+ if self.name in descriptions:+ return f"Sort users by {descriptions[self.name]}"if self.name in UserSortField.__enum__._member_names_:sort_name = self.name.lower().replace("_", " ")return f"Sort users by {sort_name}."diff --git a/saleor/graphql/account/tests/queries/test_customers_filtering.py b/saleor/graphql/account/tests/queries/test_customers_filtering.pyindex 72249d51ad..921a88078b 100644--- a/saleor/graphql/account/tests/queries/test_customers_filtering.py+++ b/saleor/graphql/account/tests/queries/test_customers_filtering.py@@ -84,6 +84,81 @@ def test_query_customer_members_with_filter_search(assert len(users) == count+def test_customers_search_sorted_by_rank_exact_match_prioritized(+ staff_api_client,+ permission_manage_users,+ query_customer_with_filter,+):+ # given+ users = User.objects.bulk_create(+ [+ User(+ email="[email protected]",+ first_name="John",+ last_name="Doe",+ is_staff=False,+ is_active=True,+ ),+ User(+ email="[email protected]",+ first_name="Aaron",+ last_name="Smith",+ is_staff=False,+ is_active=True,+ ),+ User(+ email="[email protected]",+ first_name="Charlie",+ last_name="Brown",+ is_staff=False,+ is_active=True,+ ),+ User(+ email="[email protected]",+ first_name="Aaronson",+ last_name="Jones",+ is_staff=False,+ is_active=True,+ ),+ ]+ )+ for user in users:+ update_user_search_vector(user)+ User.objects.bulk_update(users, ["search_vector"])++ variables = {+ "filter": {+ "search": "aaron",+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query_customer_with_filter,+ variables,+ permissions=[permission_manage_users],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customers"]+ assert data["totalCount"] == 3++ returned_ids = [edge["node"]["id"] for edge in data["edges"]]+ user_email_match_id = graphene.Node.to_global_id("User", users[0].pk)+ user_exact_name_id = graphene.Node.to_global_id("User", users[1].pk)+ user_no_match_id = graphene.Node.to_global_id("User", users[2].pk)+ user_prefix_name_id = graphene.Node.to_global_id("User", users[3].pk)++ # Exact name match "Aaron" should rank highest+ assert returned_ids[0] == user_exact_name_id+ # Charlie should not appear+ assert user_no_match_id not in returned_ids+ # Both prefix matches should appear+ assert user_email_match_id in returned_ids+ assert user_prefix_name_id in returned_ids++def test_query_customers_with_filter_by_one_id(query_customer_with_filter,staff_api_client,@@ -397,14 +472,17 @@ QUERY_CUSTOMERS_WITH_PAGINATION = """"""-def customers_for_search(db, address):+def test_query_customer_members_pagination_with_filter_search(+ staff_api_client,+ permission_manage_users,+):+ # givenaccounts = User.objects.bulk_create([User(first_name="Alan",- last_name="Smith",- email="[email protected]",+ last_name="Davis",+ email="[email protected]",is_staff=False,is_active=True,),@@ -431,43 +509,20 @@ def customers_for_search(db, address):),User(first_name="Anthony",- last_name="Matthews",- email="[email protected]",+ last_name="Davis",+ email="[email protected]",is_staff=False,is_active=True,),])- for i, user in enumerate(accounts):- if i in (0, 3, 4):- user.addresses.set([address])+ for user in accounts:update_user_search_vector(user)User.objects.bulk_update(accounts, ["search_vector"])- return accounts-- ("customer_filter", "expected_names"),- [- ({"search": "[email protected]"}, ["Alan"]), # email- ({"search": "[email protected]"}, ["Robert"]), # email- ({"search": "Davis"}, ["Robert", "Xavier"]), # last_name- ({"search": "WROCŁAW"}, ["Anthony", "Alan"]), # city- ({"search": "PL"}, ["Anthony", "Alan"]), # country- ],-)-def test_query_customer_members_pagination_with_filter_search(- customer_filter,- expected_names,- staff_api_client,- permission_manage_users,- address,- staff_user,- customers_for_search,-):- # given+ search_value = "Davis"page_size = 2- variables = {"first": page_size, "after": None, "filter": customer_filter}+ variables = {"first": page_size, "after": None, "filter": {"search": search_value}}staff_api_client.user.user_permissions.add(permission_manage_users)# when@@ -477,8 +532,13 @@ def test_query_customer_members_pagination_with_filter_search()content = get_graphql_content(response)- # thwn- users = content["data"]["customers"]["edges"]- assert len(users) == len(expected_names)- names = {user["node"]["firstName"] for user in users}- assert names == set(expected_names)+ # then+ customers = content["data"]["customers"]+ all_names = {edge["node"]["firstName"] for edge in customers["edges"]}+ # as the search rank will be the same for all instances, the second search field+ # is `pk` with the default `-` direction for search rank+ assert all_names == set(+ User.objects.filter(last_name=search_value)+ .order_by("-pk")+ .values_list("first_name", flat=True)[:page_size]+ )diff --git a/saleor/graphql/checkout/filters.py b/saleor/graphql/checkout/filters.pyindex 2709495842..2e70b4ebab 100644--- a/saleor/graphql/checkout/filters.py+++ b/saleor/graphql/checkout/filters.py@@ -6,7 +6,7 @@ from django.db.models import Exists, OuterRef, Qfrom ...account.models import Userfrom ...checkout.models import Checkout-from ...checkout.search.indexing import search_checkouts+from ...core.search import prefix_searchfrom ...payment.models import Paymentfrom ..channel.filters import get_currency_from_filter_datafrom ..channel.types import Channel@@ -99,7 +99,7 @@ def filter_channels(qs, _, values):def filter_checkout_search(qs, _, value):- return search_checkouts(qs, value)+ return prefix_search(qs, value)def filter_checkout_metadata(qs, _, value):diff --git a/saleor/graphql/checkout/schema.py b/saleor/graphql/checkout/schema.pyindex 66ebb4117c..246554438c 100644--- a/saleor/graphql/checkout/schema.py+++ b/saleor/graphql/checkout/schema.py@@ -14,6 +14,7 @@ from ..core.descriptions import DEPRECATED_IN_3X_INPUTfrom ..core.doc_category import DOC_CATEGORY_CHECKOUTfrom ..core.fields import BaseField, ConnectionField, FilterConnectionFieldfrom ..core.scalars import UUID+from ..core.utils import validate_and_apply_search_rank_sortingfrom ..payment.mutations import CheckoutPaymentCreatefrom .filters import CheckoutFilterInputfrom .mutations import (@@ -38,7 +39,7 @@ from .mutations import (OrderCreateFromCheckout,)from .resolvers import resolve_checkout, resolve_checkout_lines, resolve_checkouts-from .sorters import CheckoutSortingInput+from .sorters import CheckoutSortField, CheckoutSortingInputfrom .types import (Checkout,CheckoutCountableConnection,@@ -103,6 +104,9 @@ class CheckoutQueries(graphene.ObjectType):@staticmethoddef resolve_checkouts(_root, info: ResolveInfo, *, channel=None, **kwargs):+ validate_and_apply_search_rank_sorting(+ kwargs, CheckoutSortField.RANK, "CheckoutSortingInput", info+ )qs = resolve_checkouts(info, channel)qs = filter_connection_queryset(qs, kwargs, allow_replica=info.context.allow_replicadiff --git a/saleor/graphql/checkout/sorters.py b/saleor/graphql/checkout/sorters.pyindex c3c8a26f2b..f8ee8103e0 100644--- a/saleor/graphql/checkout/sorters.py+++ b/saleor/graphql/checkout/sorters.py@@ -9,12 +9,20 @@ class CheckoutSortField(BaseEnum):CREATION_DATE = ["created_at", "pk"]CUSTOMER = ["billing_address__last_name", "billing_address__first_name", "pk"]PAYMENT = ["last_charge_status", "pk"]+ RANK = ["search_rank", "pk"]class Meta:doc_category = DOC_CATEGORY_CHECKOUT@propertydef description(self):+ descriptions = {+ CheckoutSortField.RANK.name: ( # type: ignore[attr-defined] # graphene.Enum is not typed # noqa: E501+ "rank. Note: This option is available only with the `search` filter."+ ),+ }+ if self.name in descriptions:+ return f"Sort checkouts by {descriptions[self.name]}"if self.name in CheckoutSortField.__enum__._member_names_:sort_name = self.name.lower().replace("_", " ")return f"Sort checkouts by {sort_name}."diff --git a/saleor/graphql/checkout/tests/test_checkout_filters.py b/saleor/graphql/checkout/tests/test_checkout_filters.pyindex 7310bf3364..bf3b4fbaa5 100644--- a/saleor/graphql/checkout/tests/test_checkout_filters.py+++ b/saleor/graphql/checkout/tests/test_checkout_filters.py@@ -446,6 +446,87 @@ def test_checkouts_query_with_filter_search_by_global_payment_id(assert content["data"]["checkouts"]["totalCount"] == 1+def test_checkouts_search_exact_match_prioritized(+ staff_api_client,+ permission_manage_checkouts,+ channel_USD,+):+ # given+ user_with_matching_email = User.objects.create(+ first_name="John",+ last_name="Doe",+ email="[email protected]",+ )+ user_with_exact_name = User.objects.create(+ first_name="Aaron",+ last_name="Smith",+ email="[email protected]",+ )+ user_no_match = User.objects.create(+ first_name="Charlie",+ last_name="Brown",+ email="[email protected]",+ )+ user_with_prefix_name = User.objects.create(+ first_name="Aaronson",+ last_name="Jones",+ email="[email protected]",+ )++ checkouts = Checkout.objects.bulk_create(+ [+ Checkout(+ token=str(uuid.uuid4()),+ user=user_with_matching_email,+ channel=channel_USD,+ ),+ Checkout(+ token=str(uuid.uuid4()),+ user=user_with_exact_name,+ channel=channel_USD,+ ),+ Checkout(+ token=str(uuid.uuid4()),+ user=user_no_match,+ channel=channel_USD,+ ),+ Checkout(+ token=str(uuid.uuid4()),+ user=user_with_prefix_name,+ channel=channel_USD,+ ),+ ]+ )+ update_checkouts_search_vector(checkouts)++ variables = {+ "filter": {"search": "aaron"},+ }+ staff_api_client.user.user_permissions.add(permission_manage_checkouts)++ # when+ response = staff_api_client.post_graphql(CHECKOUT_QUERY_WITH_FILTER, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["checkouts"]+ assert data["totalCount"] == 3++ returned_ids = [edge["node"]["id"] for edge in data["edges"]]+ checkout_email_match_id = graphene.Node.to_global_id("Checkout", checkouts[0].pk)+ checkout_exact_name_id = graphene.Node.to_global_id("Checkout", checkouts[1].pk)+ checkout_no_match_id = graphene.Node.to_global_id("Checkout", checkouts[2].pk)+ checkout_prefix_name_id = graphene.Node.to_global_id("Checkout", checkouts[3].pk)++ # Exact name match "Aaron" should rank highest+ assert returned_ids[0] == checkout_exact_name_id+ # Charlie's checkout should not appear+ assert checkout_no_match_id not in returned_ids+ # Both prefix matches should appear after the exact match+ assert checkout_email_match_id in returned_ids+ assert checkout_prefix_name_id in returned_ids++def test_filtering_checkout_discounted_object_by_transaction_psp_reference(checkout_with_item, staff_api_client, permission_manage_checkouts):diff --git a/saleor/graphql/core/utils/__init__.py b/saleor/graphql/core/utils/__init__.pyindex b7e67322ca..7ba8f65f4f 100644--- a/saleor/graphql/core/utils/__init__.py+++ b/saleor/graphql/core/utils/__init__.py@@ -10,7 +10,7 @@ from django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom django.core.files import Filefrom graphene import ObjectType-from graphql.error import GraphQLError+from graphql import GraphQLErrorfrom requests import Responsefrom ....plugins.const import APP_ID_PREFIX@@ -186,3 +186,63 @@ def create_file_from_response(response: Response, filename: str) -> File:file_data.seek(0)# Create a Django File object from the BytesIO objectreturn File(file_data, filename)+++def validate_and_apply_search_rank_sorting(+ kwargs: dict,+ rank_sort_field,+ sorting_input_type_name: str,+ info,+) -> None:+ """Apply RANK sorting validation and defaults for search-based queries.++ Validates that RANK sorting is only used with search filters and automatically+ sets RANK as the default sort when search is used without explicit sorting.++ Args:+ kwargs: Query kwargs containing sort_by, filter, search parameters.+ Modified in-place to add default RANK sorting if needed.+ rank_sort_field: The RANK value from the SortField enum (e.g., CheckoutSortField.RANK)+ sorting_input_type_name: Name of the sorting input type in GraphQL schema+ (e.g., "CheckoutSortingInput")+ info: ResolveInfo object to access the GraphQL schema++ Raises:+ GraphQLError: If RANK sorting is used without a search filter++ """++ if sort_field_from_kwargs(kwargs) == rank_sort_field:+ # 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+ sorting_type = info.schema.get_type(sorting_input_type_name)+ kwargs["sort_by"] = sorting_type.create_container(+ {"direction": "-", "field": rank_sort_field.value}+ )+++def search_string_in_kwargs(kwargs: dict) -> bool:+ """Check if there's a search string in kwargs (filter or search parameter).++ Used to determine if search-based sorting (RANK) should be applied.+ """+ filter_search = (+ (kwargs.get("filter") or {}).get("search", "") or kwargs.get("search", "") or ""+ )+ return bool(filter_search.strip())+++def sort_field_from_kwargs(kwargs: dict) -> list[str] | None:+ """Extract the sort field from kwargs.++ Returns the field value from sort_by parameter, or None if not present.+ Also checks for attribute_id used by product sorting.+ """+ sort_by = kwargs.get("sort_by") or {}+ return sort_by.get("field") or sort_by.get("attribute_id")diff --git a/saleor/graphql/giftcard/schema.py b/saleor/graphql/giftcard/schema.pyindex c7bf9a50d5..f3a402867b 100644--- a/saleor/graphql/giftcard/schema.py+++ b/saleor/graphql/giftcard/schema.py@@ -1,8 +1,8 @@import graphenefrom graphql.error import GraphQLError+from ...core.search import prefix_searchfrom ...giftcard import models-from ...giftcard.search import search_gift_cardsfrom ...permission.enums import GiftcardPermissionsfrom ..core import ResolveInfofrom ..core.connection import create_connection_slice, filter_connection_queryset@@ -10,7 +10,10 @@ from ..core.context import get_database_connection_namefrom ..core.doc_category import DOC_CATEGORY_GIFT_CARDSfrom ..core.fields import FilterConnectionField, PermissionsFieldfrom ..core.types import NonNullList-from ..core.utils import from_global_id_or_error+from ..core.utils import (+ from_global_id_or_error,+ validate_and_apply_search_rank_sorting,+)from .bulk_mutations import (GiftCardBulkActivate,GiftCardBulkCreate,@@ -28,7 +31,7 @@ from .mutations import (GiftCardUpdate,)from .resolvers import resolve_gift_card, resolve_gift_card_tags, resolve_gift_cards-from .sorters import GiftCardSortingInput+from .sorters import GiftCardSortField, GiftCardSortingInputfrom .types import GiftCard, GiftCardCountableConnection, GiftCardTagCountableConnection@@ -85,9 +88,14 @@ class GiftCardQueries(graphene.ObjectType):return resolve_gift_card(info, id)@staticmethod- def resolve_gift_cards(- _root, info: ResolveInfo, /, *, sort_by=None, filter=None, search=None, **kwargs- ):+ def resolve_gift_cards(_root, info: ResolveInfo, /, **kwargs):+ validate_and_apply_search_rank_sorting(+ kwargs, GiftCardSortField.RANK, "GiftCardSortingInput", info+ )+ sort_by = kwargs.get("sort_by", None)+ filter = kwargs.get("filter", None)+ search = kwargs.get("search", None)+sorting_by_balance = sort_by and "current_balance_amount" in sort_by.get("field", [])@@ -96,7 +104,7 @@ class GiftCardQueries(graphene.ObjectType):raise GraphQLError("Sorting by balance requires filtering by currency.")qs = resolve_gift_cards(info)if search:- qs = search_gift_cards(qs, search)+ qs = prefix_search(qs, search)qs = filter_connection_queryset(qs,{"sort_by": sort_by, "filter": filter, **kwargs},diff --git a/saleor/graphql/giftcard/sorters.py b/saleor/graphql/giftcard/sorters.pyindex 34b6fd248d..949ee6189e 100644--- a/saleor/graphql/giftcard/sorters.py+++ b/saleor/graphql/giftcard/sorters.py@@ -7,12 +7,20 @@ class GiftCardSortField(BaseEnum):USED_BY = ["used_by__first_name", "used_by__last_name", "created_at"]CURRENT_BALANCE = ["current_balance_amount", "created_at"]CREATED_AT = ["created_at", "id"]+ RANK = ["search_rank", "id"]class Meta:doc_category = DOC_CATEGORY_GIFT_CARDS@propertydef description(self):+ descriptions = {+ GiftCardSortField.RANK.name: ( # type: ignore[attr-defined] # graphene.Enum is not typed # noqa: E501+ "rank. Note: This option is available only with the `search` filter."+ ),+ }+ if self.name in descriptions:+ return f"Sort gift cards by {descriptions[self.name]}"if self.name in GiftCardSortField.__enum__._member_names_:sort_name = self.name.lower().replace("_", " ")return f"Sort gift cards by {sort_name}."diff --git a/saleor/graphql/giftcard/tests/queries/test_gift_card_search.py b/saleor/graphql/giftcard/tests/queries/test_gift_card_search.pyindex 4dee2a68bf..41ae6aacf6 100644--- a/saleor/graphql/giftcard/tests/queries/test_gift_card_search.py+++ b/saleor/graphql/giftcard/tests/queries/test_gift_card_search.py@@ -1,7 +1,10 @@+import grapheneimport pytest+from saleor.giftcard.models import GiftCardfrom saleor.giftcard.search import update_gift_cards_search_vector+from .....account.models import Userfrom ....tests.utils import get_graphql_contentQUERY_GIFT_CARDS = """@@ -71,3 +74,73 @@ def test_query_gift_cards_with_search(assert {card["node"]["code"] for card in data} == {gift_card_list[index].code for index in indexes}+++def test_gift_cards_search_sorted_by_rank_exact_match_prioritized(+ staff_api_client,+ permission_manage_gift_card,+):+ # given+ user_exact = User.objects.create(+ first_name="Aaron", last_name="Smith", email="[email protected]"+ )+ user_prefix = User.objects.create(+ first_name="John", last_name="Doe", email="[email protected]"+ )+ user_no_match = User.objects.create(+ first_name="Charlie", last_name="Brown", email="[email protected]"+ )++ gift_cards = GiftCard.objects.bulk_create(+ [+ GiftCard(+ code="GIFT0001AAAA",+ created_by=user_exact,+ created_by_email=user_exact.email,+ initial_balance_amount=100,+ current_balance_amount=100,+ currency="USD",+ ),+ GiftCard(+ code="GIFT0002BBBB",+ created_by=user_prefix,+ created_by_email=user_prefix.email,+ initial_balance_amount=100,+ current_balance_amount=100,+ currency="USD",+ ),+ GiftCard(+ code="GIFT0003CCCC",+ created_by=user_no_match,+ created_by_email=user_no_match.email,+ initial_balance_amount=100,+ current_balance_amount=100,+ currency="USD",+ ),+ ]+ )+ update_gift_cards_search_vector(gift_cards)++ variables = {+ "search": "aaron",+ }++ # when+ response = staff_api_client.post_graphql(+ QUERY_GIFT_CARDS, variables, permissions=[permission_manage_gift_card]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["giftCards"]+ assert data["totalCount"] == 2++ returned_ids = [edge["node"]["id"] for edge in data["edges"]]+ gift_card_exact_id = graphene.Node.to_global_id("GiftCard", gift_cards[0].pk)+ gift_card_prefix_id = graphene.Node.to_global_id("GiftCard", gift_cards[1].pk)+ gift_card_no_match_id = graphene.Node.to_global_id("GiftCard", gift_cards[2].pk)++ # Exact name match "Aaron" should rank highest+ assert returned_ids[0] == gift_card_exact_id+ assert gift_card_prefix_id in returned_ids+ assert gift_card_no_match_id not in returned_idsdiff --git a/saleor/graphql/order/filters.py b/saleor/graphql/order/filters.pyindex 11c4001887..c5e18cdf93 100644--- a/saleor/graphql/order/filters.py+++ b/saleor/graphql/order/filters.py@@ -10,11 +10,11 @@ from django.utils import timezonefrom graphql.error import GraphQLErrorfrom ...core.postgres import FlatConcat+from ...core.search import prefix_searchfrom ...giftcard import GiftCardEventsfrom ...giftcard.models import GiftCardEventfrom ...invoice.models import Invoicefrom ...order.models import Fulfillment, FulfillmentLine, Order, OrderEvent, OrderLine-from ...order.search import search_ordersfrom ...payment import ChargeStatus, PaymentMethodTypefrom ...payment.models import TransactionItemfrom ...product.models import ProductVariant@@ -182,7 +182,7 @@ def filter_updated_at_range(qs, _, value):def filter_order_search(qs, _, value):- return search_orders(qs, value)+ return prefix_search(qs, value)def filter_channels(qs, _, values):diff --git a/saleor/graphql/order/schema.py b/saleor/graphql/order/schema.pyindex c4637cc83c..0727c571cc 100644--- a/saleor/graphql/order/schema.py+++ b/saleor/graphql/order/schema.py@@ -1,10 +1,9 @@import graphenefrom django.core.exceptions import ValidationError-from graphql import GraphQLErrorfrom ...core.exceptions import PermissionDenied+from ...core.search import prefix_searchfrom ...order import models-from ...order.search import search_ordersfrom ...permission.enums import OrderPermissionsfrom ...permission.utils import has_one_of_permissionsfrom ..core import ResolveInfo@@ -29,7 +28,11 @@ from ..core.fields import (from ..core.filters import FilterInputObjectTypefrom ..core.scalars import UUIDfrom ..core.types import TaxedMoney-from ..core.utils import ext_ref_to_global_id_or_error, from_global_id_or_error+from ..core.utils import (+ ext_ref_to_global_id_or_error,+ from_global_id_or_error,+ validate_and_apply_search_rank_sorting,+)from ..core.validators import validate_one_of_args_is_in_queryfrom ..utils import get_user_or_app_from_contextfrom .bulk_mutations.draft_orders import DraftOrderBulkDelete, DraftOrderLinesBulkDelete@@ -84,17 +87,6 @@ from .sorters import OrderSortField, OrderSortingInputfrom .types import Order, OrderCountableConnection, OrderEventCountableConnection-def search_string_in_kwargs(kwargs: dict) -> bool:- filter_search = (- kwargs.get("filter", {}).get("search", "") or kwargs.get("search", "") or ""- )- return bool(filter_search.strip())---def sort_field_from_kwargs(kwargs: dict) -> list[str] | None:- return kwargs.get("sort_by", {}).get("field") or None--class OrderFilterInput(FilterInputObjectType):class Meta:doc_category = DOC_CATEGORY_ORDERS@@ -235,23 +227,13 @@ class OrderQueries(graphene.ObjectType):@staticmethoddef resolve_orders(_root, info: ResolveInfo, *, 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"]}- )+ validate_and_apply_search_rank_sorting(+ kwargs, OrderSortField.RANK, "OrderSortingInput", info+ )search = kwargs.get("search")qs = resolve_orders(info, channel)if search:- qs = search_orders(qs, search)+ qs = prefix_search(qs, search)qs = filter_connection_queryset(qs, kwargs, allow_replica=info.context.allow_replica)@@ -261,23 +243,13 @@ class OrderQueries(graphene.ObjectType):@staticmethoddef resolve_draft_orders(_root, info: ResolveInfo, **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"]}- )+ validate_and_apply_search_rank_sorting(+ kwargs, OrderSortField.RANK, "OrderSortingInput", info+ )search = kwargs.get("search")qs = resolve_draft_orders(info)if search:- qs = search_orders(qs, search)+ qs = prefix_search(qs, search)qs = filter_connection_queryset(qs, kwargs, allow_replica=info.context.allow_replica)diff --git a/saleor/graphql/order/tests/queries/test_orders_search.py b/saleor/graphql/order/tests/queries/test_orders_search.pyindex 1f037d85d4..b5c748c82e 100644--- a/saleor/graphql/order/tests/queries/test_orders_search.py+++ b/saleor/graphql/order/tests/queries/test_orders_search.py@@ -534,3 +534,41 @@ def test_orders_query_with_search_by_external_reference(]expected_numbers = [str(order_list[idx].number) for idx in expected_order_idxes]assert set(returned_numbers) == set(expected_numbers)+++def test_orders_search_by_not_searchable_value(+ staff_api_client,+ permission_group_manage_orders,+ order_list,+):+ # given+ update_orders_search_vector(order_list)++ variables = {"search": ":::"}+ permission_group_manage_orders.user_set.add(staff_api_client.user)++ # when+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_SEARCH, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["orders"]["edges"]+++def test_orders_search_by_none_value(+ staff_api_client,+ permission_group_manage_orders,+ order_list,+):+ # given+ update_orders_search_vector(order_list)++ variables = {"search": None}+ permission_group_manage_orders.user_set.add(staff_api_client.user)++ # when+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_SEARCH, variables)++ # then+ content = get_graphql_content(response)+ assert len(content["data"]["orders"]["edges"]) == len(order_list)diff --git a/saleor/graphql/page/schema.py b/saleor/graphql/page/schema.pyindex 9daa924b65..d2a7a802f2 100644--- a/saleor/graphql/page/schema.py+++ b/saleor/graphql/page/schema.py@@ -1,6 +1,6 @@import graphene-from ...page.search import search_pages+from ...core.search import prefix_searchfrom ..channel.dataloaders.by_self import ChannelBySlugLoaderfrom ..core import ResolveInfofrom ..core.connection import create_connection_slice, filter_connection_queryset@@ -9,7 +9,7 @@ from ..core.descriptions import ADDED_IN_321, ADDED_IN_322, DEPRECATED_IN_3X_INPfrom ..core.doc_category import DOC_CATEGORY_PAGESfrom ..core.enums import LanguageCodeEnumfrom ..core.fields import BaseField, FilterConnectionField-from ..core.utils import from_global_id_or_error+from ..core.utils import from_global_id_or_error, validate_and_apply_search_rank_sortingfrom ..translations.mutations import PageTranslatefrom .bulk_mutations import PageBulkDelete, PageBulkPublish, PageTypeBulkDeletefrom .filters import PageFilterInput, PageTypeFilterInput, PageWhereInput@@ -31,7 +31,7 @@ from .resolvers import (resolve_page_types,resolve_pages,)-from .sorters import PageSortingInput, PageTypeSortingInput+from .sorters import PageSortField, PageSortingInput, PageTypeSortingInputfrom .types import Page, PageCountableConnection, PageType, PageTypeCountableConnection@@ -115,12 +115,16 @@ class PageQueries(graphene.ObjectType):@staticmethoddef resolve_pages(_root, info: ResolveInfo, *, channel=None, **kwargs):+ validate_and_apply_search_rank_sorting(+ kwargs, PageSortField.RANK, "PageSortingInput", info+ )+def _resolve_pages(channel_instance):qs = resolve_pages(info, channel_slug=channel, channel=channel_instance)search = kwargs.get("search") or kwargs.get("filter", {}).get("search")if search:qs = ChannelQsContext(- qs=search_pages(qs.qs, search), channel_slug=qs.channel_slug+ qs=prefix_search(qs.qs, search), channel_slug=qs.channel_slug)qs = filter_connection_queryset(diff --git a/saleor/graphql/page/sorters.py b/saleor/graphql/page/sorters.pyindex 0bf19bcf69..7a1e691795 100644--- a/saleor/graphql/page/sorters.py+++ b/saleor/graphql/page/sorters.py@@ -10,6 +10,7 @@ class PageSortField(BaseEnum):PUBLICATION_DATE = ["published_at", "title", "slug", "pk"]PUBLISHED_AT = ["published_at", "title", "slug"]CREATED_AT = ["created_at", "title", "slug"]+ RANK = ["search_rank", "slug"]class Meta:doc_category = DOC_CATEGORY_PAGES@@ -24,6 +25,9 @@ class PageSortField(BaseEnum):PageSortField.CREATED_AT.name: "creation date.", # type: ignore[attr-defined] # noqa: E501PageSortField.PUBLICATION_DATE.name: "publication date.", # type: ignore[attr-defined] # noqa: E501PageSortField.PUBLISHED_AT.name: "publication date.", # type: ignore[attr-defined] # noqa: E501+ PageSortField.RANK.name: ( # type: ignore[attr-defined] # noqa: E501+ "rank. Note: This option is available only with the `search` filter."+ ),}if self.name in descriptions:return f"Sort pages by {descriptions[self.name]}"diff --git a/saleor/graphql/page/tests/queries/test_pages_search.py b/saleor/graphql/page/tests/queries/test_pages_search.pyindex 84b48f662b..aad85b2388 100644--- a/saleor/graphql/page/tests/queries/test_pages_search.py+++ b/saleor/graphql/page/tests/queries/test_pages_search.py@@ -1,3 +1,4 @@+import grapheneimport pytestfrom .....attribute.utils import associate_attribute_values_to_instance@@ -340,3 +341,66 @@ def test_pages_query_with_filter(# thencontent = get_graphql_content(response)assert content["data"]["pages"]["totalCount"] == count+++def test_pages_search_sorted_by_rank_exact_match_prioritized(+ staff_api_client, permission_manage_pages, page_type+):+ # given+ pages = Page.objects.bulk_create(+ [+ Page(+ title="Authoring Guide",+ slug="authoring-guide",+ content=dummy_editorjs("How to write content"),+ page_type=page_type,+ ),+ Page(+ title="Author",+ slug="author-page",+ content=dummy_editorjs("About the author"),+ page_type=page_type,+ ),+ Page(+ title="Contact",+ slug="contact",+ content=dummy_editorjs("Contact information"),+ page_type=page_type,+ ),+ Page(+ title="Authority",+ slug="authority",+ content=dummy_editorjs("Authority overview"),+ page_type=page_type,+ ),+ ]+ )+ update_pages_search_vector(pages)++ variables = {+ "filter": {"search": "author"},+ }+ staff_api_client.user.user_permissions.add(permission_manage_pages)++ # when+ response = staff_api_client.post_graphql(QUERY_PAGES_WITH_FILTER, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["pages"]+ assert data["totalCount"] == 3++ returned_ids = [edge["node"]["id"] for edge in data["edges"]]+ expected_ids = [+ graphene.Node.to_global_id("Page", page.pk)+ for page in [pages[1], pages[0], pages[3]]+ ]+ assert set(returned_ids) == set(expected_ids)++ # Exact title match "Author" should rank highest+ assert returned_ids[0] == expected_ids[0]+ # Contact page should not appear+ assert graphene.Node.to_global_id("Page", pages[2].pk) not in returned_ids+ # Both prefix matches should appear+ assert graphene.Node.to_global_id("Page", pages[0].pk) in returned_ids+ assert graphene.Node.to_global_id("Page", pages[3].pk) in returned_idsdiff --git a/saleor/graphql/product/filters/product_helpers.py b/saleor/graphql/product/filters/product_helpers.pyindex cc56915ab9..16299f6d76 100644--- a/saleor/graphql/product/filters/product_helpers.py+++ b/saleor/graphql/product/filters/product_helpers.py@@ -7,6 +7,7 @@ from django.db.models.functions import Coalescefrom django.utils import timezonefrom ....channel.models import Channel+from ....core.search import prefix_searchfrom ....product import ProductTypeKindfrom ....product.models import (Category,@@ -16,7 +17,6 @@ from ....product.models import (ProductVariant,ProductVariantChannelListing,)-from ....product.search import search_productsfrom ....warehouse.models import Allocation, Reservation, Stock, Warehousefrom ...utils import resolve_global_ids_to_primary_keysfrom ...utils.filters import (@@ -297,7 +297,7 @@ def filter_stock_availability(qs, _, value, channel_slug):def filter_search(qs, _, value):- return search_products(qs, value)+ return prefix_search(qs, value)def filter_gift_card(qs, _, value):diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.pyindex afcb6c4b27..c47316f086 100644--- a/saleor/graphql/product/schema.py+++ b/saleor/graphql/product/schema.py@@ -2,6 +2,7 @@ import graphenefrom django.db.models import Exists, OuterReffrom promise import Promise+from ...core.search import prefix_searchfrom ...permission.enums import ProductPermissionsfrom ...permission.utils import has_one_of_permissionsfrom ...product import models@@ -9,7 +10,6 @@ from ...product.deprecations import (DEPRECATION_WARNING_MESSAGE as DEPRECATION_DIGITAL_CONTENT,)from ...product.models import ALL_PRODUCTS_PERMISSIONS-from ...product.search import search_productsfrom ..channel.dataloaders.by_self import ChannelBySlugLoaderfrom ..channel.utils import get_default_channel_slug_or_graphql_errorfrom ..core import ResolveInfo@@ -31,7 +31,7 @@ from ..core.fields import ()from ..core.tracing import traced_resolverfrom ..core.types import NonNullList-from ..core.utils import from_global_id_or_error+from ..core.utils import from_global_id_or_error, validate_and_apply_search_rank_sortingfrom ..core.validators import validate_one_of_args_is_in_queryfrom ..shop.resolvers import get_database_connection_namefrom ..translations.mutations import (@@ -132,6 +132,7 @@ from .sorters import (CategorySortingInput,CollectionSortingInput,ProductOrder,+ ProductOrderField,ProductTypeSortingInput,ProductVariantSortingInput,)@@ -149,7 +150,6 @@ from .types import (ProductVariant,ProductVariantCountableConnection,)-from .utils import check_for_sorting_by_rankclass ProductQueries(graphene.ObjectType):@@ -526,7 +526,9 @@ class ProductQueries(graphene.ObjectType):@staticmethod@traced_resolverdef resolve_products(_root, info: ResolveInfo, *, channel=None, **kwargs):- check_for_sorting_by_rank(info, kwargs)+ validate_and_apply_search_rank_sorting(+ kwargs, ProductOrderField.RANK, "ProductOrder", info+ )search = kwargs.get("search")requestor = get_user_or_app_from_context(info.context)@@ -543,7 +545,7 @@ class ProductQueries(graphene.ObjectType):qs = resolve_products(info, requestor, channel_obj, limited_channel_access)if search:qs = ChannelQsContext(- qs=search_products(qs.qs, search), channel_slug=channel+ qs=prefix_search(qs.qs, search), channel_slug=channel)kwargs["channel"] = channelqs = filter_connection_queryset(@@ -645,7 +647,7 @@ class ProductQueries(graphene.ObjectType):requestor=requestor,)if search:- products = search_products(+ products = prefix_search(models.Product.objects.using(get_database_connection_name(info.context)),diff --git a/saleor/graphql/product/tests/queries/test_collections_query.py b/saleor/graphql/product/tests/queries/test_collections_query.pyindex 12110f6e77..d552468a5a 100644--- a/saleor/graphql/product/tests/queries/test_collections_query.py+++ b/saleor/graphql/product/tests/queries/test_collections_query.py@@ -434,9 +434,6 @@ def test_collections_query_return_error_with_sort_by_rank_without_search(# thenerrors = content["errors"]- expected_message = (- "Sorting by RANK is available only when using a search filter "- "or search argument."- )+ expected_message = "Sorting by RANK is available only when using a search filter."assert len(errors) == 1assert errors[0]["message"] == expected_messagediff --git a/saleor/graphql/product/tests/queries/test_products_query.py b/saleor/graphql/product/tests/queries/test_products_query.pyindex 86f6f0c09e..e7ade53acb 100644--- a/saleor/graphql/product/tests/queries/test_products_query.py+++ b/saleor/graphql/product/tests/queries/test_products_query.py@@ -863,10 +863,7 @@ def test_sort_product_by_rank_without_search(}response = user_api_client.post_graphql(SEARCH_PRODUCTS_QUERY, variables)content = get_graphql_content(response, ignore_errors=True)- message = (- "Sorting by RANK is available only when using a search filter or search "- "argument."- )+ message = "Sorting by RANK is available only when using a search filter."assert "errors" in contentassert content["errors"][0]["message"] == message@@ -893,10 +890,7 @@ def test_products_query_by_rank_returns_error_with_filter_nontype_search(assert "errors" in contenterrors = content["errors"]- expected_message = (- "Sorting by RANK is available only when using a search filter "- "or search argument."- )+ expected_message = "Sorting by RANK is available only when using a search filter."assert len(errors) == 1assert errors[0]["message"] == expected_message@@ -936,10 +930,7 @@ def test_products_query_by_rank_returns_error_with_nontype_search(assert "errors" in contenterrors = content["errors"]- expected_message = (- "Sorting by RANK is available only when using a search filter "- "or search argument."- )+ expected_message = "Sorting by RANK is available only when using a search filter."assert len(errors) == 1assert errors[0]["message"] == expected_message@@ -1312,6 +1303,86 @@ def test_search_product_using_search_argument_with_sort_by(}+def test_products_search_sorted_by_rank_exact_match_prioritized(+ staff_api_client, permission_manage_products, product_type, category, channel_USD+):+ # given+ products = Product.objects.bulk_create(+ [+ Product(+ name="Authoring Tool",+ slug="authoring-tool",+ product_type=product_type,+ category=category,+ ),+ Product(+ name="Author",+ slug="author",+ product_type=product_type,+ category=category,+ ),+ Product(+ name="Unrelated Item",+ slug="unrelated-item",+ product_type=product_type,+ category=category,+ ),+ Product(+ name="Authority Badge",+ slug="authority-badge",+ product_type=product_type,+ category=category,+ ),+ ]+ )+ ProductChannelListing.objects.bulk_create(+ [+ ProductChannelListing(+ product=product,+ channel=channel_USD,+ is_published=True,+ visible_in_listings=True,+ discounted_price_amount=10,+ currency=channel_USD.currency_code,+ available_for_purchase_at=datetime.datetime(+ 1999, 1, 1, tzinfo=datetime.UTC+ ),+ )+ for product in products+ ]+ )+ for product in products:+ product.search_vector = FlatConcatSearchVector(+ *prepare_product_search_vector_value(product)+ )+ Product.objects.bulk_update(products, ["search_vector"])++ variables = {+ "search": "author",+ "sortBy": {"field": "RANK", "direction": "DESC"},+ "first": 10,+ "channel": channel_USD.slug,+ }++ staff_api_client.user.user_permissions.add(permission_manage_products)++ # when+ response = staff_api_client.post_graphql(PRODUCT_SEARCH_QUERY, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["products"]["edges"]++ assert len(data) == 3+ # Exact name match "Author" should rank highest+ assert data[0]["node"]["name"] == "Author"+ # Unrelated item should not appear+ returned_names = {node["node"]["name"] for node in data}+ assert "Unrelated Item" not in returned_names+ assert "Authoring Tool" in returned_names+ assert "Authority Badge" in returned_names++@pytest.mark.parametrize(("sort_order",diff --git a/saleor/graphql/product/types/categories.py b/saleor/graphql/product/types/categories.pyindex cc1f43a5c0..7348b79e96 100644--- a/saleor/graphql/product/types/categories.py+++ b/saleor/graphql/product/types/categories.py@@ -2,10 +2,10 @@ import graphenefrom graphene import relayfrom promise import Promise+from ....core.search import prefix_searchfrom ....permission.utils import has_one_of_permissionsfrom ....product import modelsfrom ....product.models import ALL_PRODUCTS_PERMISSIONS-from ....product.search import search_productsfrom ....thumbnail.utils import (get_image_or_proxy_url,get_thumbnail_format,@@ -25,6 +25,7 @@ from ...core.federation import federated_entity, resolve_federation_referencesfrom ...core.fields import ConnectionField, FilterConnectionField, JSONStringfrom ...core.scalars import DateTimefrom ...core.types import Image, ModelObjectType, ThumbnailField+from ...core.utils import validate_and_apply_search_rank_sortingfrom ...meta.types import ObjectWithMetadatafrom ...translations.fields import TranslationFieldfrom ...translations.types import CategoryTranslation@@ -35,7 +36,7 @@ from ..dataloaders import (ThumbnailByCategoryIdSizeAndFormatLoader,)from ..filters.product import ProductFilterInput, ProductWhereInput-from ..sorters import ProductOrder+from ..sorters import ProductOrder, ProductOrderFieldfrom .products import ProductCountableConnection@@ -166,6 +167,9 @@ class Category(ModelObjectType[models.Category]):@staticmethoddef resolve_products(root: models.Category, info, *, channel=None, **kwargs):+ validate_and_apply_search_rank_sorting(+ kwargs, ProductOrderField.RANK, "ProductOrder", info+ )search = kwargs.get("search")requestor = get_user_or_app_from_context(info.context)has_required_permissions = has_one_of_permissions(@@ -195,7 +199,7 @@ class Category(ModelObjectType[models.Category]):if search:channel_qs = ChannelQsContext(- qs=search_products(qs, search), channel_slug=channel+ qs=prefix_search(qs, search), channel_slug=channel)else:channel_qs = ChannelQsContext(qs=qs, channel_slug=channel)diff --git a/saleor/graphql/product/types/collections.py b/saleor/graphql/product/types/collections.pyindex 0e30ca2a04..373c07f8d2 100644--- a/saleor/graphql/product/types/collections.py+++ b/saleor/graphql/product/types/collections.py@@ -4,9 +4,9 @@ import graphenefrom graphene import relayfrom promise import Promise+from ....core.search import prefix_searchfrom ....permission.enums import ProductPermissionsfrom ....product import models-from ....product.search import search_productsfrom ....thumbnail.utils import (get_image_or_proxy_url,get_thumbnail_format,@@ -30,7 +30,10 @@ from ...core.federation import federated_entityfrom ...core.fields import FilterConnectionField, JSONString, PermissionsFieldfrom ...core.types import Image, NonNullList, ThumbnailFieldfrom ...core.types.context import ChannelContextType-from ...core.utils import from_global_id_or_error+from ...core.utils import (+ from_global_id_or_error,+ validate_and_apply_search_rank_sorting,+)from ...meta.types import ObjectWithMetadatafrom ...translations.fields import TranslationFieldfrom ...translations.types import CollectionTranslation@@ -40,8 +43,7 @@ from ..dataloaders import (ThumbnailByCollectionIdSizeAndFormatLoader,)from ..filters.product import ProductFilterInput, ProductWhereInput-from ..sorters import ProductOrder-from ..utils import check_for_sorting_by_rank+from ..sorters import ProductOrder, ProductOrderFieldfrom .channels import CollectionChannelListingfrom .products import ProductCountableConnection@@ -137,7 +139,9 @@ class Collection(ChannelContextType[models.Collection]):def resolve_products(root: ChannelContext[models.Collection], info: ResolveInfo, **kwargs):- check_for_sorting_by_rank(info, kwargs)+ validate_and_apply_search_rank_sorting(+ kwargs, ProductOrderField.RANK, "ProductOrder", info+ )search = kwargs.get("search")requestor = get_user_or_app_from_context(info.context)@@ -150,7 +154,7 @@ class Collection(ChannelContextType[models.Collection]):if search:qs = ChannelQsContext(- qs=search_products(qs, search), channel_slug=root.channel_slug+ qs=prefix_search(qs, search), channel_slug=root.channel_slug)else:qs = ChannelQsContext(qs=qs, channel_slug=root.channel_slug)diff --git a/saleor/graphql/product/utils.py b/saleor/graphql/product/utils.pyindex c3bfb771ce..28ac4c0bae 100644--- a/saleor/graphql/product/utils.py+++ b/saleor/graphql/product/utils.py@@ -7,14 +7,12 @@ import graphenefrom django.core.exceptions import ValidationErrorfrom django.db import DatabaseError, transactionfrom django.db.utils import IntegrityError-from graphql import GraphQLErrorfrom ...core.tracing import traced_atomic_transactionfrom ...order import OrderStatusfrom ...order import models as order_modelsfrom ...warehouse.models import Stockfrom ..core.enums import ProductErrorCode-from .sorters import ProductOrderFieldif TYPE_CHECKING:from ...product.models import ProductVariant@@ -149,31 +147,3 @@ def update_ordered_media(ordered_media):if errors:raise ValidationError(errors)---def search_string_in_kwargs(kwargs: dict) -> bool:- filter_search = kwargs.get("filter", {}).get("search", "") or ""- search = kwargs.get("search", "") or ""- return bool(filter_search.strip()) or bool(search.strip())---def sort_field_from_kwargs(kwargs: dict) -> list[str] | None:- sort_by = kwargs.get("sort_by", {}) or {}- return sort_by.get("field") or sort_by.get("attribute_id")---def check_for_sorting_by_rank(info, kwargs: dict):- if sort_field_from_kwargs(kwargs) == ProductOrderField.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 "- "or search argument."- )- 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("ProductOrder")- kwargs["sort_by"] = product_type.create_container(- {"direction": "-", "field": ["search_rank", "id"]}- )diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex f88dca2ba8..baf6da3700 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -13333,6 +13333,11 @@ enum PageSortField @doc(category: "Pages") {"""Sort pages by creation date."""CREATED_AT++ """+ Sort pages by rank. Note: This option is available only with the `search` filter.+ """+ RANK}input PageFilterInput @doc(category: "Pages") {@@ -13998,6 +14003,11 @@ enum GiftCardSortField @doc(category: "Gift cards") {"""Sort gift cards by created at."""CREATED_AT++ """+ Sort gift cards by rank. Note: This option is available only with the `search` filter.+ """+ RANK}input GiftCardFilterInput @doc(category: "Gift cards") {@@ -14831,6 +14841,11 @@ enum CheckoutSortField @doc(category: "Checkout") {"""Sort checkouts by payment."""PAYMENT++ """+ Sort checkouts by rank. Note: This option is available only with the `search` filter.+ """+ RANK}input CheckoutFilterInput @doc(category: "Checkout") {@@ -15191,6 +15206,11 @@ enum UserSortField @doc(category: "Users") {"""Sort users by last modified at."""LAST_MODIFIED_AT++ """+ Sort users by rank. Note: This option is available only with the `search` filter.+ """+ RANK}type GroupCountableConnection @doc(category: "Users") {diff --git a/saleor/order/search.py b/saleor/order/search.pyindex 8f5cb90b9f..e2189a3c68 100644--- a/saleor/order/search.py+++ b/saleor/order/search.py@@ -2,16 +2,13 @@ from typing import TYPE_CHECKINGimport graphenefrom 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 import Value, prefetch_related_objectsfrom ..account.search import generate_address_search_vector_valuefrom ..core.postgres import FlatConcatSearchVector, NoValidationSearchVectorfrom . import OrderEventsif TYPE_CHECKING:- from django.db.models import QuerySet-from .models import Order@@ -270,13 +267,3 @@ def generate_order_events_search_vector_value())return event_vectors---def search_orders(qs: "QuerySet[Order]", value) -> "QuerySet[Order]":- if value:- 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 qsdiff --git a/saleor/page/search.py b/saleor/page/search.pyindex 8a764c292a..27144ddf12 100644--- a/saleor/page/search.py+++ b/saleor/page/search.py@@ -2,9 +2,8 @@ from collections import defaultdictfrom typing import NamedTuplefrom django.conf import settings-from django.contrib.postgres.search import SearchQuery, SearchRankfrom django.db import transaction-from django.db.models import F, Q, QuerySet, Value+from django.db.models import Valuefrom ..attribute.models import Attribute, AttributeValuefrom ..attribute.search import get_search_vectors_for_attribute_values@@ -210,13 +209,3 @@ def generate_attributes_search_vector_value(attribute, values, page_id_to_title_map=page_id_to_title_map, weight="B")return search_vectors---def search_pages(qs: QuerySet[Page], value: str) -> QuerySet[Page]:- if value:- 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 qsdiff --git a/saleor/product/search.py b/saleor/product/search.pyindex be041c43f7..f7fde216e9 100644--- a/saleor/product/search.py+++ b/saleor/product/search.py@@ -3,8 +3,7 @@ from collections.abc import Iterablefrom typing import TYPE_CHECKINGfrom 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 import Value, prefetch_related_objectsfrom ..attribute.models import AssignedProductAttributeValue, AttributeValuefrom ..attribute.search import get_search_vectors_for_attribute_values@@ -171,13 +170,3 @@ def generate_attributes_search_vector_value_with_assignment(attribute, values, weight="B")return search_vectors---def search_products(qs, value):- if value:- 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