Skip to content

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

Refactor product search (#7340)

Filip Owczarek5c458f26276d
diff --git a/saleor/core/tests/test_postgresql_search.py b/saleor/core/tests/test_postgresql_search.py
index 087b4a33c9..b54e016a33 100644
--- a/saleor/core/tests/test_postgresql_search.py
+++ b/saleor/core/tests/test_postgresql_search.py
@@ -36,7 +36,8 @@ def named_products(category, product_type, channel_USD):
def execute_search(phrase):
"""Execute storefront search."""
- return product_search(phrase)
+ qs = Product.objects.all()
+ return product_search(qs, phrase)
@pytest.mark.parametrize(
diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.py
index 47e8851691..4a90f20d33 100644
--- a/saleor/graphql/product/filters.py
+++ b/saleor/graphql/product/filters.py
@@ -257,12 +257,13 @@ def _filter_stock_availability(qs, _, value, channel_slug):
return qs
-def product_search(phrase):
+def product_search(qs, phrase):
"""Return matching products for storefront views.
Name and description is matched using search vector.
Args:
+ qs (ProductsQueryset): searched data set
phrase (str): searched phrase
"""
@@ -270,17 +271,19 @@ def product_search(phrase):
vector = F("search_vector")
ft_in_description_or_name = Q(search_vector=query)
- ft_by_sku = Q(variants__sku__search=phrase)
+ variants = ProductVariant.objects.filter(sku=phrase).values("id")
+ ft_by_sku = Q(Exists(variants.filter(product_id=OuterRef("pk"))))
+
return (
- Product.objects.annotate(rank=SearchRank(vector, query))
+ qs.annotate(rank=SearchRank(vector, query))
.filter((ft_in_description_or_name | ft_by_sku))
- .order_by("-rank")
+ .order_by("-rank", "id")
)
def filter_search(qs, _, value):
if value:
- qs = product_search(value).distinct() & qs.distinct()
+ qs = product_search(qs, value)
return qs
@@ -303,12 +306,13 @@ def filter_product_type(qs, _, value):
def filter_stocks(qs, _, value):
warehouse_ids = value.get("warehouse_ids")
quantity = value.get("quantity")
+ # distinct's wil be removed in separated PR
if warehouse_ids and not quantity:
- return filter_warehouses(qs, _, warehouse_ids)
+ return filter_warehouses(qs, _, warehouse_ids).distinct()
if quantity and not warehouse_ids:
- return filter_quantity(qs, quantity)
+ return filter_quantity(qs, quantity).distinct()
if quantity and warehouse_ids:
- return filter_quantity(qs, quantity, warehouse_ids)
+ return filter_quantity(qs, quantity, warehouse_ids).distinct()
return qs
diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.py
index 22a64818be..d7a586ecf0 100644
--- a/saleor/graphql/product/resolvers.py
+++ b/saleor/graphql/product/resolvers.py
@@ -1,6 +1,7 @@
-from django.db.models import Sum
+from django.db.models import Exists, OuterRef, Sum
from ...account.utils import requestor_is_staff_member_or_app
+from ...channel.models import Channel
from ...core.tracing import traced_resolver
from ...order import OrderStatus
from ...product import models
@@ -8,7 +9,6 @@ from ..channel import ChannelQsContext
from ..core.utils import from_global_id_or_error
from ..utils import get_user_or_app_from_context
from ..utils.filters import filter_by_period
-from .filters import filter_products_by_stock_availability
def resolve_category_by_slug(slug):
@@ -73,17 +73,18 @@ def resolve_product_by_slug(info, product_slug, channel_slug, requestor):
@traced_resolver
-def resolve_products(
- info, requestor, stock_availability=None, channel_slug=None, **_kwargs
-) -> ChannelQsContext:
+def resolve_products(info, requestor, channel_slug=None, **_kwargs) -> ChannelQsContext:
qs = models.Product.objects.visible_to_user(requestor, channel_slug)
- if stock_availability:
- qs = filter_products_by_stock_availability(qs, stock_availability, channel_slug)
if not requestor_is_staff_member_or_app(requestor):
- qs = qs.annotate_visible_in_listings(channel_slug).exclude(
- visible_in_listings=False
+ channels = Channel.objects.filter(slug=str(channel_slug))
+ product_channel_listings = models.ProductChannelListing.objects.filter(
+ Exists(channels.filter(pk=OuterRef("channel_id"))),
+ visible_in_listings=True,
+ )
+ qs = qs.filter(
+ Exists(product_channel_listings.filter(product_id=OuterRef("pk")))
)
- return ChannelQsContext(qs=qs.distinct(), channel_slug=channel_slug)
+ return ChannelQsContext(qs=qs, channel_slug=channel_slug)
@traced_resolver
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index b67b8da4a5..72324666a8 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -3170,6 +3170,9 @@ def test_search_product_by_description_and_name(
product_1 = product_list[0]
product_1.description_plaintext = "some red product"
product_1.save()
+ product_3 = product_list[2]
+ product_3.description_plaintext = "desc without searched word"
+ product_3.save()
variables = {
"filters": {
@@ -3182,6 +3185,7 @@ def test_search_product_by_description_and_name(
content = get_graphql_content(response)
data = content["data"]["products"]["edges"]
+ assert len(data) == 3
assert data[0]["node"]["name"] == product_2.name
assert data[1]["node"]["name"] == product.name
assert data[2]["node"]["name"] == product_1.name
diff --git a/saleor/product/migrations/0145_auto_20210511_1043.py b/saleor/product/migrations/0145_auto_20210511_1043.py
new file mode 100644
index 0000000000..5f1be41d47
--- /dev/null
+++ b/saleor/product/migrations/0145_auto_20210511_1043.py
@@ -0,0 +1,19 @@
+# Generated by Django 3.1.8 on 2021-05-11 10:43
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("product", "0144_auto_20210318_1155"),
+ ]
+
+ operations = [
+ migrations.AddIndex(
+ model_name="productchannellisting",
+ index=models.Index(
+ fields=["publication_date"], name="product_pro_publica_67290c_idx"
+ ),
+ ),
+ ]
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 3198994dcf..e0263c56f6 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -13,6 +13,7 @@ from django.db.models import (
Case,
Count,
DateField,
+ Exists,
ExpressionWrapper,
F,
FilteredRelation,
@@ -141,13 +142,15 @@ class ProductType(ModelWithMetadata):
class ProductsQueryset(models.QuerySet):
def published(self, channel_slug: str):
today = datetime.date.today()
- return self.filter(
- Q(channel_listings__publication_date__lte=today)
- | Q(channel_listings__publication_date__isnull=True),
- channel_listings__channel__slug=str(channel_slug),
- channel_listings__channel__is_active=True,
- channel_listings__is_published=True,
- )
+ channels = Channel.objects.filter(
+ slug=str(channel_slug), is_active=True
+ ).values("id")
+ channel_listings = ProductChannelListing.objects.filter(
+ Q(publication_date__lte=today) | Q(publication_date__isnull=True),
+ Exists(channels.filter(pk=OuterRef("channel_id"))),
+ is_published=True,
+ ).values("id")
+ return self.filter(Exists(channel_listings.filter(product_id=OuterRef("pk"))))
def not_published(self, channel_slug: str):
today = datetime.date.today()
@@ -159,17 +162,28 @@ class ProductsQueryset(models.QuerySet):
def published_with_variants(self, channel_slug: str):
published = self.published(channel_slug)
- query = ProductVariantChannelListing.objects.filter(
- variant_id=OuterRef("variants__id"),
- channel__slug=str(channel_slug),
+ channels = Channel.objects.filter(
+ slug=str(channel_slug), is_active=True
+ ).values("id")
+ variant_channel_listings = ProductVariantChannelListing.objects.filter(
+ Exists(channels.filter(pk=OuterRef("channel_id"))),
price_amount__isnull=False,
- ).values_list("variant", flat=True)
- return published.filter(variants__in=query).distinct()
+ ).values("id")
+ variants = ProductVariant.objects.filter(
+ Exists(variant_channel_listings.filter(variant_id=OuterRef("pk")))
+ )
+ return published.filter(Exists(variants.filter(product_id=OuterRef("pk"))))
def visible_to_user(self, requestor: Union["User", "App"], channel_slug: str):
if requestor_is_staff_member_or_app(requestor):
if channel_slug:
- return self.filter(channel_listings__channel__slug=str(channel_slug))
+ channels = Channel.objects.filter(slug=str(channel_slug)).values("id")
+ channel_listings = ProductChannelListing.objects.filter(
+ Exists(channels.filter(pk=OuterRef("channel_id")))
+ ).values("id")
+ return self.filter(
+ Exists(channel_listings.filter(product_id=OuterRef("pk")))
+ )
return self.all()
return self.published_with_variants(channel_slug)
@@ -476,6 +490,9 @@ class ProductChannelListing(PublishableModel):
class Meta:
unique_together = [["product", "channel"]]
ordering = ("pk",)
+ indexes = [
+ models.Index(fields=["publication_date"]),
+ ]
def is_available_for_purchase(self):
return (