Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Improve account search results by using ILIKE instead of TrigramSimilarity. (#7559)
Filip Owczarek0d660dfe0068
diff --git a/saleor/account/migrations/0053_auto_20210719_1048.py b/saleor/account/migrations/0053_auto_20210719_1048.pynew file mode 100644index 0000000000..9714086a8c--- /dev/null+++ b/saleor/account/migrations/0053_auto_20210719_1048.py@@ -0,0 +1,48 @@+# Generated by Django 3.2.5 on 2021-07-19 10:48++import django.contrib.postgres.indexes+from django.db import migrations++import saleor.account.models+++class Migration(migrations.Migration):++ dependencies = [+ ("account", "0052_customerevent_app"),+ ]++ operations = [+ migrations.RemoveIndex(+ model_name="user",+ name="account_use_email_d707ff_gin",+ ),+ migrations.AlterField(+ model_name="address",+ name="phone",+ field=saleor.account.models.PossiblePhoneNumberField(+ blank=True, db_index=True, default="", max_length=128, region=None+ ),+ ),+ migrations.AddIndex(+ model_name="address",+ index=django.contrib.postgres.indexes.GinIndex(+ fields=["first_name", "last_name", "city", "country"],+ name="address_search_gin",+ opclasses=[+ "gin_trgm_ops",+ "gin_trgm_ops",+ "gin_trgm_ops",+ "gin_trgm_ops",+ ],+ ),+ ),+ migrations.AddIndex(+ model_name="user",+ index=django.contrib.postgres.indexes.GinIndex(+ fields=["email", "first_name", "last_name"],+ name="user_search_gin",+ opclasses=["gin_trgm_ops", "gin_trgm_ops", "gin_trgm_ops"],+ ),+ ),+ ]diff --git a/saleor/account/models.py b/saleor/account/models.pyindex 71e8ce82cc..2ecfcb2bd8 100644--- a/saleor/account/models.py+++ b/saleor/account/models.py@@ -67,12 +67,20 @@ class Address(models.Model):postal_code = models.CharField(max_length=20, blank=True)country = CountryField()country_area = models.CharField(max_length=128, blank=True)- phone = PossiblePhoneNumberField(blank=True, default="")+ phone = PossiblePhoneNumberField(blank=True, default="", db_index=True)objects = models.Manager.from_queryset(AddressQueryset)()class Meta:ordering = ("pk",)+ indexes = [+ GinIndex(+ name="address_search_gin",+ # `opclasses` and `fields` should be the same length+ fields=["first_name", "last_name", "city", "country"],+ opclasses=["gin_trgm_ops"] * 4,+ ),+ ]@propertydef full_name(self):@@ -176,7 +184,12 @@ class User(PermissionsMixin, ModelWithMetadata, AbstractBaseUser):indexes = [*ModelWithMetadata.Meta.indexes,# Orders searching index- GinIndex(fields=["email", "first_name", "last_name"]),+ GinIndex(+ name="user_search_gin",+ # `opclasses` and `fields` should be the same length+ fields=["email", "first_name", "last_name"],+ opclasses=["gin_trgm_ops"] * 3,+ ),]def __init__(self, *args, **kwargs):diff --git a/saleor/core/__init__.py b/saleor/core/__init__.pyindex 6a6963ba59..80eec0235d 100644--- a/saleor/core/__init__.py+++ b/saleor/core/__init__.py@@ -1,3 +1,6 @@+default_app_config = "saleor.core.app.CoreAppConfig"++class JobStatus:PENDING = "pending"SUCCESS = "success"diff --git a/saleor/core/app.py b/saleor/core/app.pynew file mode 100644index 0000000000..a9c2d66fc2--- /dev/null+++ b/saleor/core/app.py@@ -0,0 +1,11 @@+from django.apps import AppConfig+from django.db.models import Field++from .db.filters import PostgresILike+++class CoreAppConfig(AppConfig):+ name = "saleor.core"++ def ready(self):+ Field.register_lookup(PostgresILike)diff --git a/saleor/core/db/filters.py b/saleor/core/db/filters.pynew file mode 100644index 0000000000..9889302c5e--- /dev/null+++ b/saleor/core/db/filters.py@@ -0,0 +1,11 @@+from django.db.models.lookups import IContains+++class PostgresILike(IContains):+ lookup_name = "ilike"++ def as_postgresql(self, compiler, connection):+ lhs, lhs_params = self.process_lhs(compiler, connection)+ rhs, rhs_params = self.process_rhs(compiler, connection)+ params = lhs_params + rhs_params+ return "%s ILIKE %s" % (lhs, rhs), paramsdiff --git a/saleor/graphql/account/filters.py b/saleor/graphql/account/filters.pyindex 1a442f514b..54c55d371a 100644--- a/saleor/graphql/account/filters.py+++ b/saleor/graphql/account/filters.py@@ -33,19 +33,19 @@ def filter_user_search(qs, _, value):if value:UserAddress = User.addresses.throughaddresses = Address.objects.filter(- Q(first_name__trigram_similar=value)- | Q(last_name__trigram_similar=value)- | Q(city__trigram_similar=value)- | Q(country__trigram_similar=value)+ Q(first_name__ilike=value)+ | Q(last_name__ilike=value)+ | Q(city__ilike=value)+ | Q(country__ilike=value)| Q(phone=value)).values("id")user_addresses = UserAddress.objects.filter(Exists(addresses.filter(pk=OuterRef("address_id")))).values("user_id")qs = qs.filter(- Q(email__trigram_similar=value)- | Q(first_name__trigram_similar=value)- | Q(last_name__trigram_similar=value)+ Q(email__ilike=value)+ | Q(first_name__ilike=value)+ | Q(last_name__ilike=value)| Q(Exists(user_addresses.filter(user_id=OuterRef("pk")))))return qsdiff --git a/saleor/graphql/account/tests/test_account.py b/saleor/graphql/account/tests/test_account.pyindex 8138e59a18..7226772019 100644--- a/saleor/graphql/account/tests/test_account.py+++ b/saleor/graphql/account/tests/test_account.py@@ -4450,7 +4450,7 @@ def test_query_customers_with_sort(@pytest.mark.parametrize("customer_filter, count",[- ({"search": "example.com"}, 2),+ ({"search": "mirumee.com"}, 2),({"search": "Alice"}, 1),({"search": "Kowalski"}, 1),({"search": "John"}, 1), # first_name@@ -4472,13 +4472,13 @@ def test_query_customer_members_with_filter_search(users = User.objects.bulk_create([User(- email="[email protected]",+ email="[email protected]",first_name="Alice",last_name="Kowalski",is_active=False,),User(- email="[email protected]",+ email="[email protected]",is_active=True,),]@@ -4549,13 +4549,13 @@ def test_query_staff_members_app_no_permission(@pytest.mark.parametrize("staff_member_filter, count",[- ({"search": "example.com"}, 3),+ ({"search": "mirumee.com"}, 2),({"search": "Alice"}, 1),({"search": "Kowalski"}, 1),({"search": "John"}, 1), # first_name({"search": "Doe"}, 1), # last_name({"search": "wroc"}, 1), # city- ({"search": "pl"}, 1), # country+ ({"search": "pl"}, 2), # country],)def test_query_staff_members_with_filter_search(@@ -4570,19 +4570,19 @@ def test_query_staff_members_with_filter_search(users = User.objects.bulk_create([User(- email="[email protected]",+ email="[email protected]",first_name="Alice",last_name="Kowalski",is_staff=True,is_active=False,),User(- email="[email protected]",+ email="[email protected]",is_staff=True,is_active=True,),User(- email="[email protected]",+ email="[email protected]",first_name="Alice",last_name="Kowalski",is_staff=False,diff --git a/saleor/graphql/account/tests/test_pagination.py b/saleor/graphql/account/tests/test_pagination.pyindex 4bc788f26b..f3f6ea978b 100644--- a/saleor/graphql/account/tests/test_pagination.py+++ b/saleor/graphql/account/tests/test_pagination.py@@ -221,7 +221,7 @@ def test_query_customers_pagination_with_sort("customer_filter, users_order",[({"search": "example.com"}, ["Alan", "Harry"]), # email- ({"search": "test.com"}, ["Anthony", "Robert"]), # email+ ({"search": "[email protected]"}, ["Robert", "Xavier"]), # email({"search": "davis"}, ["Robert", "Xavier"]), # last_name({"search": "wroc"}, ["Anthony", "Alan"]), # city({"search": "pl"}, ["Anthony", "Alan"]), # country@@ -254,7 +254,7 @@ def test_query_customer_members_pagination_with_filter_search(@pytest.mark.parametrize("staff_member_filter, users_order",[- ({"search": "example.com"}, ["Anthony", "Alan"]), # email+ ({"search": "[email protected]"}, ["Robert", "Xavier"]), # email({"search": "davis"}, ["Robert", "Xavier"]), # last_name({"search": "wroc"}, ["Anthony", "Alan"]), # city({"search": "pl"}, ["Anthony", "Alan"]), # countrydiff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.pyindex 56ab1cd8a5..9c97c392c4 100644--- a/saleor/graphql/product/schema.py+++ b/saleor/graphql/product/schema.py@@ -1,5 +1,4 @@import graphene-from graphql.error import GraphQLErrorfrom saleor.core.tracing import traced_resolver@@ -111,7 +110,6 @@ from .sorters import (CategorySortingInput,CollectionSortingInput,ProductOrder,- ProductOrderField,ProductTypeSortingInput,)from .types import (@@ -317,17 +315,6 @@ class ProductQueries(graphene.ObjectType):@traced_resolverdef resolve_products(self, info, channel=None, **kwargs):- # sort by RANK can be used only with search filter- if "sort_by" in kwargs and ProductOrderField.RANK == kwargs["sort_by"].get(- "field"- ):- if (- "filter" not in kwargs- or kwargs["filter"].get("search") is None- or not kwargs["filter"]["search"].strip()- ):- raise GraphQLError("Sorting by Rank is available only with searching.")-requestor = get_user_or_app_from_context(info.context)if channel is None and not requestor_is_staff_member_or_app(requestor):channel = get_default_channel_slug_or_graphql_error()diff --git a/saleor/graphql/product/sorters.py b/saleor/graphql/product/sorters.pyindex a769a69493..e5a5861a7c 100644--- a/saleor/graphql/product/sorters.py+++ b/saleor/graphql/product/sorters.py@@ -14,6 +14,7 @@ from django.db.models import ()from django.db.models.expressions import Windowfrom django.db.models.functions import Coalesce, DenseRank+from graphql.error import GraphQLErrorfrom ...product.models import (Category,@@ -211,6 +212,12 @@ class ProductOrderField(graphene.Enum):))+ @staticmethod+ def qs_with_rank(queryset: QuerySet, **_kwargs) -> QuerySet:+ if "rank" in queryset.query.annotations.keys():+ return queryset+ raise GraphQLError("Sorting by Rank is available only with searching.")+class ProductOrder(SortInputObjectType):attribute_id = graphene.Argument(diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.pyindex e0029f911d..7e611fcfb0 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -3453,11 +3453,10 @@ def test_sort_product_by_rank_without_search("channel": channel_USD.slug,}response = user_api_client.post_graphql(SEARCH_PRODUCTS_QUERY, variables)- with pytest.raises(AssertionError) as e:- get_graphql_content(response)-+ data = get_graphql_content(response, ignore_errors=True)+ assert len(data["errors"]) == 1assert (- e._excinfo[1].args[0][0]["message"]+ data["errors"][0]["message"]== "Sorting by Rank is available only with searching.")@@ -3490,11 +3489,10 @@ def test_sort_product_by_rank_with_empty_search_value("channel": channel_USD.slug,}response = user_api_client.post_graphql(SEARCH_PRODUCTS_QUERY, variables)- with pytest.raises(AssertionError) as e:- get_graphql_content(response)-+ data = get_graphql_content(response, ignore_errors=True)+ assert len(data["errors"]) == 1assert (- e._excinfo[1].args[0][0]["message"]+ data["errors"][0]["message"]== "Sorting by Rank is available only with searching.")