Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Allow searching without accents (#18843)
Iga Karbowiakc29d6428fed1
diff --git a/AGENTS.md b/AGENTS.mdindex 998d065579..38345873f2 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -118,3 +118,44 @@ with traced_atomic_transaction():| `select_for_update` | `saleor/payment/lock_objects.py` | Complex read-modify-write || `update_or_create` | `saleor/graphql/attribute/utils/type_handlers.py` | Upsert operations || `traced_atomic_transaction` | `saleor/core/tracing.py` | Multi-operation atomicity |++# Data Migrations++## Marking search indexes as dirty++When adding or changing search vector indexing logic, create a data migration that marks all existing rows as dirty so they get re-indexed.++### Structure++1. **Task file** — place in `saleor/<app>/migrations/tasks/saleor<version>.py`+2. **Migration file** — place in `saleor/<app>/migrations/<number>_<name>.py`++### Task rules++- Decorate with `@app.task(queue=settings.DATA_MIGRATIONS_TASKS_QUEUE_NAME)` and `@allow_writer()`+- Process in batches (e.g. 1000 rows) to avoid long-running transactions+- Use `select_for_update` via the app's `lock_objects` module to lock rows before updating+- Use the subquery pattern: lock rows first, then filter+update in a separate query:+ ```python+ with transaction.atomic():+ pks = (+ model_qs_select_for_update()+ .filter(pk__in=batch_pks)+ .values_list("pk", flat=True)+ )+ Model.objects.filter(pk__in=pks).update(search_index_dirty=True)+ ```+- Self-chain with `.delay()` at the end if there are more rows to process+- Stop chaining when the batch returns no results++### Migration rules++- Use `post_migrate` signal to trigger the celery task after all migrations complete (not inline)+- Connect to `post_migrate` inside a `RunPython` operation+- Use `registry.get_app_config("<app>")` as the sender+- Always provide `migrations.RunPython.noop` as the reverse operation++### Reference example++- Task: `saleor/giftcard/migrations/tasks/saleor3_22.py`+- Migration: `saleor/giftcard/migrations/0023_mark_gift_cards_search_vector_as_dirty.py`diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bac61255e6..e7c2f06c25 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -34,20 +34,24 @@ All notable, unreleased changes to this project will be documented in this file.### Other changes+- 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+- Add optional usage telemetry. - #18789 by @wcislo-saleor+- The app can now be installed without providing a `tokenTargetUrl` in the manifest file.++#### Search improvements++- Improved page search with search vectors. Pages can now be searched by slug, title, content, attribute values, and page type information.+- Improve user search. Use search vector functionality to enable searching users by email address, first name, last name, and addresses.+- Improved checkout search with search vectors. The `search_index_dirty` flag is set whenever indexed checkout data changes, and a background task runs every minute to update search vectors for dirty checkouts, processing the oldest first. Search results are returned in order of best match relevance.- 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+ - Accent-insensitive search: queries automatically normalize diacritical marks, allowing searches to match regardless of accents (e.g., "cafe" matches "café")- 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.-- Improved checkout search with search vectors. The `search_index_dirty` flag is set whenever indexed checkout data changes, and a background task runs every minute to update search vectors for dirty checkouts, processing the oldest first. Search results are returned in order of best match relevance.-- Add optional usage telemetry. - #18789 by @wcislo-saleor-- The app can now be installed without providing a `tokenTargetUrl` in the manifest file.### Deprecationsdiff --git a/saleor/celeryconf.py b/saleor/celeryconf.pyindex d1d32d731a..a2c6ae0591 100644--- a/saleor/celeryconf.py+++ b/saleor/celeryconf.py@@ -36,6 +36,7 @@ app.autodiscover_tasks()app.autodiscover_tasks(packages=["saleor.app.migrations.tasks",+ "saleor.product.migrations.tasks",],related_name="saleor3_23",)diff --git a/saleor/core/postgres.py b/saleor/core/postgres.pyindex e249013e76..dd6080213a 100644--- a/saleor/core/postgres.py+++ b/saleor/core/postgres.py@@ -6,7 +6,9 @@ from django.contrib.postgres.search import (SearchVector,SearchVectorCombinable,)-from django.db.models import Expression+from django.db.models import Expression, Value++from .utils.text import strip_accentslogger = logging.getLogger(__name__)@@ -42,6 +44,15 @@ class NoValidationSearchVector(SearchVector, NoValidationSearchVectorCombinable)and/or over clause."""+ def __init__(self, *expressions, **kwargs):+ processed = []+ for expr in expressions:+ if isinstance(expr, Value) and isinstance(expr.value, str):+ processed.append(Value(strip_accents(expr.value)))+ else:+ processed.append(expr)+ super().__init__(*processed, **kwargs)+class FlatConcat(Expression):"""Generate a SQL statements for expressions to be concatenated.diff --git a/saleor/core/search.py b/saleor/core/search.pyindex 3acba2e8ed..b27f79fa0c 100644--- a/saleor/core/search.py+++ b/saleor/core/search.py@@ -4,6 +4,8 @@ from typing import TYPE_CHECKINGfrom django.contrib.postgres.search import SearchQuery, SearchRankfrom django.db.models import F, Value+from .utils.text import strip_accents+if TYPE_CHECKING:from django.db.models import QuerySet@@ -154,6 +156,8 @@ def prefix_search(qs: "QuerySet", value: str) -> "QuerySet":# to allow default RANK sortingreturn qs.annotate(search_rank=Value(0))+ value = strip_accents(value)+parsed_query = parse_search_query(value)if not parsed_query:# return empty queryset as the provided value is not searchablediff --git a/saleor/core/search_tasks.py b/saleor/core/search_tasks.pyindex 0f85c442b6..55f68d9658 100644--- a/saleor/core/search_tasks.py+++ b/saleor/core/search_tasks.py@@ -58,7 +58,7 @@ def set_user_search_document_values(updated_count: int = 0) -> None:set_user_search_document_values.delay(updated_count)[email protected](queue=settings.DATA_MIGRATIONS_TASKS_QUEUE_NAME)def set_order_search_document_values(update_all: bool = False,database_connection_name: str = settings.DATABASE_CONNECTION_REPLICA_NAME,diff --git a/saleor/core/tests/test_search.py b/saleor/core/tests/test_search.pyindex c18dc8b785..5680b1322d 100644--- a/saleor/core/tests/test_search.py+++ b/saleor/core/tests/test_search.py@@ -1,5 +1,4 @@import pytest-from django.contrib.postgres.search import SearchVectorfrom django.db.models import Valuefrom ...account.models import User@@ -7,6 +6,7 @@ from ...account.search import update_user_search_vectorfrom ...checkout.models import Checkoutfrom ...checkout.search.indexing import update_checkouts_search_vectorfrom ...product.models import Product, ProductChannelListing+from ..postgres import NoValidationSearchVectorfrom ..search import _sanitize_word, parse_search_query, prefix_search@@ -211,6 +211,8 @@ def products_for_search(category, product_type, channel_USD):("Coffee Maker", "Best coffee maker"),("Coffeehouse Special", "Special blend for coffeehouses"),("Tea Kettle", "Great for brewing tea"),+ ("Magnésium B6", "Supplement with magnesium"),+ ("Crème brûlée", "Classic French dessert"),]:product = Product.objects.create(name=name,@@ -219,8 +221,10 @@ def products_for_search(category, product_type, channel_USD):product_type=product_type,category=category,search_vector=(- SearchVector(Value(name), config="simple", weight="A")- + SearchVector(Value(description), config="simple", weight="C")+ NoValidationSearchVector(Value(name), config="simple", weight="A")+ + NoValidationSearchVector(+ Value(description), config="simple", weight="C"+ )),)ProductChannelListing.objects.create(@@ -260,7 +264,7 @@ def test_prefix_search_empty_value_returns_all(products_for_search):results = prefix_search(Product.objects.all(), "")# then- assert results.count() == 3+ assert results.count() == 5def test_prefix_search_not_searchable_value_returns_nothing(products_for_search):@@ -313,6 +317,54 @@ def test_prefix_search_negation(products_for_search):assert results.first().name == "Coffee Maker"+def test_prefix_search_accent_insensitive_query(products_for_search):+ # given — product indexed as "Magnésium B6", query without accent+ qs = Product.objects.all()++ # when+ results = prefix_search(qs, "Magnesium")++ # then+ assert results.count() == 1+ assert results.first().name == "Magnésium B6"+++def test_prefix_search_accented_query_finds_accented_product(products_for_search):+ # given — accented query should also match+ qs = Product.objects.all()++ # when+ results = prefix_search(qs, "Magnésium")++ # then+ assert results.count() == 1+ assert results.first().name == "Magnésium B6"+++def test_prefix_search_accent_insensitive_partial(products_for_search):+ # given — partial unaccented prefix+ qs = Product.objects.all()++ # when+ results = prefix_search(qs, "crem")++ # then+ assert results.count() == 1+ assert results.first().name == "Crème brûlée"+++def test_prefix_search_accent_insensitive_multiword(products_for_search):+ # given — mixed accent/unaccented multi-word query+ qs = Product.objects.all()++ # when+ results = prefix_search(qs, "creme brulee")++ # then+ assert results.count() == 1+ assert results.first().name == "Crème brûlée"++@pytest.fixturedef users_for_search():users = []@@ -320,6 +372,7 @@ def users_for_search():("[email protected]", "John", "Doe"),("[email protected]", "Johnny", "Smith"),("[email protected]", "Jane", "Doe"),+ ("[email protected]", "José", "García"),]:user = User.objects.create(email=email, first_name=first, last_name=last)update_user_search_vector(user, attach_addresses_data=False)@@ -346,6 +399,42 @@ def test_prefix_search_users_perfect_match_priority(users_for_search):assert results[0].first_name == "John"+def test_prefix_search_users_accent_insensitive(users_for_search):+ # given — user indexed as "José García", query without accent+ qs = User.objects.all()++ # when+ results = prefix_search(qs, "Jose")++ # then+ assert results.count() == 1+ assert results.first().first_name == "José"+++def test_prefix_search_users_accented_query(users_for_search):+ # given — accented query should also match+ qs = User.objects.all()++ # when+ results = prefix_search(qs, "José García")++ # then+ assert results.count() == 1+ assert results.first().email == "[email protected]"+++def test_prefix_search_users_partial_accent_insensitive(users_for_search):+ # given — partial unaccented prefix on last name+ qs = User.objects.all()++ # when+ results = prefix_search(qs, "Garci")++ # then+ assert results.count() == 1+ assert results.first().last_name == "García"++def test_prefix_search_checkout_exact_match_priority(channel_USD,):diff --git a/saleor/core/tests/test_text.py b/saleor/core/tests/test_text.pynew file mode 100644index 0000000000..3a249629ce--- /dev/null+++ b/saleor/core/tests/test_text.py@@ -0,0 +1,21 @@+from ..utils.text import strip_accents+++def test_strip_accents_removes_diacritics():+ assert strip_accents("Magnésium") == "Magnesium"+++def test_strip_accents_removes_multiple_diacritics():+ assert strip_accents("café") == "cafe"+++def test_strip_accents_removes_diaeresis():+ assert strip_accents("naïve") == "naive"+++def test_strip_accents_preserves_ascii():+ assert strip_accents("hello world") == "hello world"+++def test_strip_accents_empty_string():+ assert strip_accents("") == ""diff --git a/saleor/core/utils/text.py b/saleor/core/utils/text.pyindex 92e56a1861..d0ba77ac34 100644--- a/saleor/core/utils/text.py+++ b/saleor/core/utils/text.py@@ -1,6 +1,12 @@import unicodedata+def strip_accents(text: str) -> str:+ """Remove diacritical marks from text, e.g. 'Magnésium' → 'Magnesium'."""+ nfkd = unicodedata.normalize("NFKD", text)+ return "".join(c for c in nfkd if not unicodedata.combining(c))++def safe_truncate(text: str, max_length: int) -> str:"""Truncate text to a safe length while avoiding breaking combining diacritical marks."""if max_length <= 0:diff --git a/saleor/order/migrations/0220_update_order_search_vector.py b/saleor/order/migrations/0220_update_order_search_vector.pynew file mode 100644index 0000000000..5eedfaad7d--- /dev/null+++ b/saleor/order/migrations/0220_update_order_search_vector.py@@ -0,0 +1,27 @@+# Generated by Django 5.2.11 on 2026-02-20 13:57+from django.apps import apps as registry+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(update_all=True)++ sender = registry.get_app_config("order")+ post_migrate.connect(on_migrations_complete, weak=False, sender=sender)+++class Migration(migrations.Migration):+ dependencies = [+ ("order", "0219_merge_20251212_0955"),+ ]++ operations = [+ migrations.RunPython(+ update_order_search_document_values,+ reverse_code=migrations.RunPython.noop,+ ),+ ]diff --git a/saleor/product/migrations/0203_mark_products_search_index_as_dirty.py b/saleor/product/migrations/0203_mark_products_search_index_as_dirty.pynew file mode 100644index 0000000000..f4f155f5ef--- /dev/null+++ b/saleor/product/migrations/0203_mark_products_search_index_as_dirty.py@@ -0,0 +1,27 @@+# Generated by Django 5.2.8 on 2026-02-20++from django.apps import apps as registry+from django.db import migrations+from django.db.models.signals import post_migrate++from .tasks.saleor3_23 import mark_products_search_index_as_dirty_task+++def mark_products_search_index_as_dirty(apps, _schema_editor):+ def on_migrations_complete(sender=None, **kwargs):+ mark_products_search_index_as_dirty_task.delay()++ sender = registry.get_app_config("product")+ post_migrate.connect(on_migrations_complete, weak=False, sender=sender)+++class Migration(migrations.Migration):+ dependencies = [+ ("product", "0202_category_product_category_tree_id_lf1e1"),+ ]++ operations = [+ migrations.RunPython(+ mark_products_search_index_as_dirty, migrations.RunPython.noop+ ),+ ]diff --git a/saleor/product/migrations/tasks/__init__.py b/saleor/product/migrations/tasks/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/product/migrations/tasks/saleor3_23.py b/saleor/product/migrations/tasks/saleor3_23.pynew file mode 100644index 0000000000..4e11ea91d6--- /dev/null+++ b/saleor/product/migrations/tasks/saleor3_23.py@@ -0,0 +1,31 @@+from django.conf import settings+from django.db import transaction++from ....celeryconf import app+from ....core.db.connection import allow_writer+from ...lock_objects import product_qs_select_for_update+from ...models import Product++# One batch updates took ~0.5s+BATCH_SIZE = 5000++[email protected](queue=settings.DATA_MIGRATIONS_TASKS_QUEUE_NAME)+@allow_writer()+def mark_products_search_index_as_dirty_task():+ product_pks = list(+ Product.objects.filter(search_index_dirty=False)+ .order_by("pk")+ .values_list("pk", flat=True)[:BATCH_SIZE]+ )+ if not product_pks:+ return++ with transaction.atomic():+ pks = (+ product_qs_select_for_update()+ .filter(pk__in=product_pks)+ .values_list("pk", flat=True)+ )+ Product.objects.filter(pk__in=pks).update(search_index_dirty=True)+ mark_products_search_index_as_dirty_task.delay()