Skip to content

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

Update product search by name/clean up (#6783)

Damian Wysocki50eff94aa37c
diff --git a/saleor/core/tests/test_postgresql_search.py b/saleor/core/tests/test_postgresql_search.py
index 362fefe56e..087b4a33c9 100644
--- a/saleor/core/tests/test_postgresql_search.py
+++ b/saleor/core/tests/test_postgresql_search.py
@@ -41,15 +41,7 @@ def execute_search(phrase):
@pytest.mark.parametrize(
"phrase,product_num",
- [
- ("Arabika", 0),
- ("Aarabica", 0),
- ("Arab", 0),
- ("czicken", 2),
- ("blue", 1),
- ("roast", 2),
- ("coool", 1),
- ],
+ [("Arabica", 0), ("chicken", 2), ("blue", 1), ("roast", 2), ("cool", 1)],
)
@pytest.mark.integration
@pytest.mark.django_db
diff --git a/saleor/graphql/page/types.py b/saleor/graphql/page/types.py
index 17e69bb49d..e6cc82f1c1 100644
--- a/saleor/graphql/page/types.py
+++ b/saleor/graphql/page/types.py
@@ -59,6 +59,10 @@ class Page(CountableDjangoObjectType):
def resolve_page_type(root: models.Page, info):
return PageTypeByIdLoader(info.context).load(root.page_type_id)
+ @staticmethod
+ def resolve_content_json(root: models.Page, info):
+ return root.content
+
@staticmethod
def resolve_attributes(root: models.Page, info):
return SelectedAttributesByPageIdLoader(info.context).load(root.id)
diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.py
index 3a1291c26e..740cfb5b49 100644
--- a/saleor/graphql/product/filters.py
+++ b/saleor/graphql/product/filters.py
@@ -3,7 +3,6 @@ from typing import Dict, Iterable, List, Optional
import django_filters
import graphene
-from django.contrib.postgres.search import TrigramSimilarity
from django.db.models import Exists, F, OuterRef, Q, Subquery, Sum
from django.db.models.functions import Coalesce
from graphene_django.filter import GlobalIDFilter, GlobalIDMultipleChoiceFilter
@@ -212,21 +211,15 @@ def filter_stock_availability(qs, _, value):
def product_search(phrase):
"""Return matching products for storefront views.
- Fuzzy storefront search that is resistant to small typing errors made
- by user. Name is matched using trigram similarity, description uses
- standard postgres full text search.
+ Name and description is matched using search vector.
Args:
phrase (str): searched phrase
"""
- name_sim = TrigramSimilarity("name", phrase)
- ft_in_description = Q(search_vector=phrase)
+ ft_in_description_or_name = Q(search_vector=phrase)
ft_by_sku = Q(variants__sku__search=phrase)
- name_similar = Q(name_sim__gt=0.2)
- return Product.objects.annotate(name_sim=name_sim).filter(
- (ft_in_description | name_similar | ft_by_sku)
- )
+ return Product.objects.filter((ft_in_description_or_name | ft_by_sku))
def filter_search(qs, _, value):
diff --git a/saleor/graphql/product/tests/test_category.py b/saleor/graphql/product/tests/test_category.py
index dac09b4eaf..111b5b3573 100644
--- a/saleor/graphql/product/tests/test_category.py
+++ b/saleor/graphql/product/tests/test_category.py
@@ -61,6 +61,35 @@ def test_category_query_by_id(user_api_client, product, channel_USD):
assert len(category_data["children"]["edges"]) == category.get_children().count()
+def test_category_query_description(user_api_client, product, channel_USD):
+ category = Category.objects.first()
+ description = dummy_editorjs("Test description.", json_format=True)
+ category.description = dummy_editorjs("Test description.")
+ category.save()
+ variables = {
+ "id": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ }
+ query = """
+ query ($id: ID, $slug: String){
+ category(
+ id: $id,
+ slug: $slug,
+ ) {
+ id
+ name
+ description
+ descriptionJson
+ }
+ }
+ """
+ response = user_api_client.post_graphql(query, variables=variables)
+ content = get_graphql_content(response)
+ category_data = content["data"]["category"]
+ assert category_data["description"] == description
+ assert category_data["descriptionJson"] == description
+
+
def test_category_query_by_slug(user_api_client, product, channel_USD):
category = Category.objects.first()
variables = {"slug": category.slug, "channel": channel_USD.slug}
diff --git a/saleor/graphql/product/tests/test_collection.py b/saleor/graphql/product/tests/test_collection.py
index c676e7e7b9..c5335bb73c 100644
--- a/saleor/graphql/product/tests/test_collection.py
+++ b/saleor/graphql/product/tests/test_collection.py
@@ -1,4 +1,3 @@
-import json
from unittest.mock import Mock
import graphene
@@ -154,6 +153,7 @@ def test_collections_query(
name
slug
description
+ descriptionJson
products {
totalCount
}
@@ -165,6 +165,7 @@ def test_collections_query(
# query public collections only as regular user
variables = {"channel": channel_USD.slug}
+ description = dummy_editorjs("Test description.", json_format=True)
response = user_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
edges = content["data"]["collections"]["edges"]
@@ -172,9 +173,8 @@ def test_collections_query(
collection_data = edges[0]["node"]
assert collection_data["name"] == published_collection.name
assert collection_data["slug"] == published_collection.slug
- assert collection_data["description"] == json.dumps(
- published_collection.description
- )
+ assert collection_data["description"] == description
+ assert collection_data["descriptionJson"] == description
assert (
collection_data["products"]["totalCount"]
== published_collection.products.count()
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 585227c00c..11875c8e72 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -179,6 +179,44 @@ def test_product_query_by_id_available_as_staff_user(
assert product_data["name"] == product.name
+def test_product_query_description(
+ staff_api_client, permission_manage_products, product, channel_USD
+):
+ query = """
+ query ($id: ID, $slug: String, $channel:String){
+ product(
+ id: $id,
+ slug: $slug,
+ channel: $channel
+ ) {
+ id
+ name
+ description
+ descriptionJson
+ }
+ }
+ """
+ description = dummy_editorjs("Test description.", json_format=True)
+ product.description = dummy_editorjs("Test description.")
+ product.save()
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ }
+
+ response = staff_api_client.post_graphql(
+ query,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is not None
+ assert product_data["description"] == description
+ assert product_data["descriptionJson"] == description
+
+
def test_product_query_by_id_not_available_as_staff_user(
staff_api_client, permission_manage_products, product, channel_USD
):
@@ -2351,7 +2389,7 @@ def test_create_product_description_plaintext(
assert not data["productErrors"]
product = Product.objects.all().first()
- product.description_plaintext = description
+ assert product.description_plaintext == description
def test_search_product_by_description(user_api_client, product_list, channel_USD):
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 7d4499f2e0..99edb98c0e 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -430,7 +430,7 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
@key(fields="id")
class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
- description_json = graphene.String(
+ description_json = graphene.JSONString(
description="Description of the product (JSON).",
deprecation_reason=(
"Will be removed in Saleor 4.0. Use the `description` field instead."
@@ -537,6 +537,10 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
return None
return CategoryByIdLoader(info.context).load(category_id)
+ @staticmethod
+ def resolve_description_json(root: ChannelContext[models.Product], info):
+ return root.node.description
+
@staticmethod
def resolve_tax_type(root: ChannelContext[models.Product], info):
tax_data = info.context.plugins.get_tax_code_from_object_meta(root.node)
@@ -886,7 +890,7 @@ class ProductType(CountableDjangoObjectType):
@key(fields="id")
class Collection(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
- description_json = graphene.String(
+ description_json = graphene.JSONString(
description="Description of the collection (JSON).",
deprecation_reason=(
"Will be removed in Saleor 4.0. Use the `description` field instead."
@@ -956,10 +960,14 @@ class Collection(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
def __resolve_reference(root, _info, **_kwargs):
return graphene.Node.get_node_from_global_id(_info, root.id)
+ @staticmethod
+ def resolve_description_json(root: ChannelContext[models.Collection], info):
+ return root.node.description
+
@key(fields="id")
class Category(CountableDjangoObjectType):
- description_json = graphene.String(
+ description_json = graphene.JSONString(
description="Description of the category (JSON).",
deprecation_reason=(
"Will be removed in Saleor 4.0. Use the `description` field instead."
@@ -1010,6 +1018,10 @@ class Category(CountableDjangoObjectType):
def resolve_ancestors(root: models.Category, info, **_kwargs):
return root.get_ancestors()
+ @staticmethod
+ def resolve_description_json(root: models.Category, info):
+ return root.description
+
@staticmethod
def resolve_background_image(root: models.Category, info, size=None, **_kwargs):
if root.background_image:
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 75e12bea60..6109624f92 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -677,7 +677,7 @@ type Category implements Node & ObjectWithMetadata {
level: Int!
privateMetadata: [MetadataItem]!
metadata: [MetadataItem]!
- descriptionJson: String @deprecated(reason: "Will be removed in Saleor 4.0. Use the `description` field instead.")
+ descriptionJson: JSONString @deprecated(reason: "Will be removed in Saleor 4.0. Use the `description` field instead.")
ancestors(before: String, after: String, first: Int, last: Int): CategoryCountableConnection
products(channel: String, before: String, after: String, first: Int, last: Int): ProductCountableConnection
url: String @deprecated(reason: "This field will be removed after 2020-07-31.")
@@ -747,7 +747,7 @@ type CategoryTranslatableContent implements Node {
id: ID!
name: String!
description: JSONString!
- descriptionJson: String @deprecated(reason: "Will be removed in Saleor 4.0. Use the `description` field instead.")
+ descriptionJson: JSONString @deprecated(reason: "Will be removed in Saleor 4.0. Use the `description` field instead.")
translation(languageCode: LanguageCodeEnum!): CategoryTranslation
category: Category
}
@@ -765,7 +765,7 @@ type CategoryTranslation implements Node {
name: String!
description: JSONString!
language: LanguageDisplay!
- descriptionJson: String @deprecated(reason: "Will be removed in Saleor 4.0. Use the `description` field instead.")
+ descriptionJson: JSONString @deprecated(reason: "Will be removed in Saleor 4.0. Use the `description` field instead.")
}
type CategoryUpdate {
@@ -1054,7 +1054,7 @@ type Collection implements Node & ObjectWithMetadata {
slug: String!
privateMetadata: [MetadataItem]!
metadata: [MetadataItem]!
- descriptionJson: String @deprecated(reason: "Will be removed in Saleor 4.0. Use the `description` field instead.")
+ descriptionJson: JSONString @deprecated(reason: "Will be removed in Saleor 4.0. Use the `description` field instead.")
products(filter: ProductFilterInput, sortBy: ProductOrder, before: String, after: String, first: Int, last: Int): ProductCountableConnection
backgroundImage(size: Int): Image
translation(languageCode: LanguageCodeEnum!): CollectionTranslation
@@ -1206,7 +1206,7 @@ type CollectionTranslatableContent implements Node {
id: ID!
name: String!
description: JSONString!
- descriptionJson: String @deprecated(reason: "Will be removed in Saleor 4.0. Use the `description` field instead.")
+ descriptionJson: JSONString @deprecated(reason: "Will be removed in Saleor 4.0. Use the `description` field instead.")
translation(languageCode: LanguageCodeEnum!): CollectionTranslation
collection: Collection
}
@@ -1224,7 +1224,7 @@ type CollectionTranslation implements Node {
name: String!
description: JSONString!
language: LanguageDisplay!
- descriptionJson: String @deprecated(reason: "Will be removed in Saleor 4.0. Use the `description` field instead.")
+ descriptionJson: JSONString @deprecated(reason: "Will be removed in Saleor 4.0. Use the `description` field instead.")
}
type CollectionUpdate {
@@ -3802,7 +3802,7 @@ type Product implements Node & ObjectWithMetadata {
rating: Float
privateMetadata: [MetadataItem]!
metadata: [MetadataItem]!
- descriptionJson: String @deprecated(reason: "Will be removed in Saleor 4.0. Use the `description` field instead.")
+ descriptionJson: JSONString @deprecated(reason: "Will be removed in Saleor 4.0. Use the `description` field instead.")
url: String! @deprecated(reason: "This field will be removed after 2020-07-31.")
thumbnail(size: Int): Image
pricing: ProductPricingInfo
@@ -4097,7 +4097,7 @@ type ProductTranslatableContent implements Node {
seoDescription: String
name: String!
description: JSONString!
- descriptionJson: String @deprecated(reason: "Will be removed in Saleor 4.0. Use the `description` field instead.")
+ descriptionJson: JSONString @deprecated(reason: "Will be removed in Saleor 4.0. Use the `description` field instead.")
translation(languageCode: LanguageCodeEnum!): ProductTranslation
product: Product
}
@@ -4115,7 +4115,7 @@ type ProductTranslation implements Node {
name: String!
description: JSONString!
language: LanguageDisplay!
- descriptionJson: String @deprecated(reason: "Will be removed in Saleor 4.0. Use the `description` field instead.")
+ descriptionJson: JSONString @deprecated(reason: "Will be removed in Saleor 4.0. Use the `description` field instead.")
}
type ProductType implements Node & ObjectWithMetadata {
diff --git a/saleor/graphql/translations/types.py b/saleor/graphql/translations/types.py
index 444c82efa4..a543599812 100644
--- a/saleor/graphql/translations/types.py
+++ b/saleor/graphql/translations/types.py
@@ -129,7 +129,7 @@ class ProductVariantTranslatableContent(CountableDjangoObjectType):
class ProductTranslation(BaseTranslationType):
- description_json = graphene.String(
+ description_json = graphene.JSONString(
description="Translated description of the product (JSON).",
deprecation_reason=(
"Will be removed in Saleor 4.0. Use the `description` field instead."
@@ -143,7 +143,7 @@ class ProductTranslation(BaseTranslationType):
class ProductTranslatableContent(CountableDjangoObjectType):
- description_json = graphene.String(
+ description_json = graphene.JSONString(
description="Description of the product (JSON).",
deprecation_reason=(
"Will be removed in Saleor 4.0. Use the `description` field instead."
@@ -166,7 +166,7 @@ class ProductTranslatableContent(CountableDjangoObjectType):
class CollectionTranslation(BaseTranslationType):
- description_json = graphene.String(
+ description_json = graphene.JSONString(
description="Translated description of the product (JSON).",
deprecation_reason=(
"Will be removed in Saleor 4.0. Use the `description` field instead."
@@ -180,7 +180,7 @@ class CollectionTranslation(BaseTranslationType):
class CollectionTranslatableContent(CountableDjangoObjectType):
- description_json = graphene.String(
+ description_json = graphene.JSONString(
description="Description of the collection (JSON).",
deprecation_reason=(
"Will be removed in Saleor 4.0. Use the `description` field instead."
@@ -206,7 +206,7 @@ class CollectionTranslatableContent(CountableDjangoObjectType):
class CategoryTranslation(BaseTranslationType):
- description_json = graphene.String(
+ description_json = graphene.JSONString(
description="Translated description of the product (JSON).",
deprecation_reason=(
"Will be removed in Saleor 4.0. Use the `description` field instead."
@@ -220,7 +220,7 @@ class CategoryTranslation(BaseTranslationType):
class CategoryTranslatableContent(CountableDjangoObjectType):
- description_json = graphene.String(
+ description_json = graphene.JSONString(
description="Description of the category (JSON).",
deprecation_reason=(
"Will be removed in Saleor 4.0. Use the `description` field instead."
diff --git a/saleor/page/migrations/0019_auto_20210125_0905.py b/saleor/page/migrations/0019_auto_20210125_0905.py
new file mode 100644
index 0000000000..04ee14f8b7
--- /dev/null
+++ b/saleor/page/migrations/0019_auto_20210125_0905.py
@@ -0,0 +1,21 @@
+# Generated by Django 3.1.5 on 2021-01-25 09:05
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("page", "0018_migrate_content_json_into_content"),
+ ]
+
+ operations = [
+ migrations.RemoveField(
+ model_name="page",
+ name="content_json",
+ ),
+ migrations.RemoveField(
+ model_name="pagetranslation",
+ name="content_json",
+ ),
+ ]
diff --git a/saleor/page/models.py b/saleor/page/models.py
index 3d606870c4..7b38b46c1e 100644
--- a/saleor/page/models.py
+++ b/saleor/page/models.py
@@ -15,9 +15,6 @@ class Page(ModelWithMetadata, SeoModel, PublishableModel):
"PageType", related_name="pages", on_delete=models.CASCADE
)
content = SanitizedJSONField(blank=True, default=dict, sanitizer=clean_editor_js)
- content_json = SanitizedJSONField(
- blank=True, default=dict, sanitizer=clean_editor_js
- )
created = models.DateTimeField(auto_now_add=True)
translated = TranslationProxy()
@@ -37,9 +34,6 @@ class PageTranslation(SeoModelTranslation):
)
title = models.CharField(max_length=255, blank=True)
content = SanitizedJSONField(blank=True, default=dict, sanitizer=clean_editor_js)
- content_json = SanitizedJSONField(
- blank=True, default=dict, sanitizer=clean_editor_js
- )
class Meta:
ordering = ("language_code", "page", "pk")
diff --git a/saleor/product/migrations/0140_auto_20210125_0905.py b/saleor/product/migrations/0140_auto_20210125_0905.py
new file mode 100644
index 0000000000..b295c49dc2
--- /dev/null
+++ b/saleor/product/migrations/0140_auto_20210125_0905.py
@@ -0,0 +1,37 @@
+# Generated by Django 3.1.5 on 2021-01-25 09:05
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("product", "0139_description_vector_search"),
+ ]
+
+ operations = [
+ migrations.RemoveField(
+ model_name="category",
+ name="description_json",
+ ),
+ migrations.RemoveField(
+ model_name="categorytranslation",
+ name="description_json",
+ ),
+ migrations.RemoveField(
+ model_name="collection",
+ name="description_json",
+ ),
+ migrations.RemoveField(
+ model_name="collectiontranslation",
+ name="description_json",
+ ),
+ migrations.RemoveField(
+ model_name="product",
+ name="description_json",
+ ),
+ migrations.RemoveField(
+ model_name="producttranslation",
+ name="description_json",
+ ),
+ ]
diff --git a/saleor/product/migrations/0141_update_product_ts_vector.py b/saleor/product/migrations/0141_update_product_ts_vector.py
new file mode 100644
index 0000000000..16ad7f171c
--- /dev/null
+++ b/saleor/product/migrations/0141_update_product_ts_vector.py
@@ -0,0 +1,47 @@
+# Generated by Django 3.1.5 on 2021-01-25 09:23
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("product", "0140_auto_20210125_0905"),
+ ]
+
+ operations = [
+ migrations.RunSQL(
+ """
+ DROP TRIGGER title_vector_update ON product_product;
+ """
+ ),
+ migrations.RunSQL(
+ """
+ CREATE TRIGGER title_vector_update BEFORE INSERT OR UPDATE
+ ON product_product FOR EACH ROW EXECUTE PROCEDURE
+ tsvector_update_trigger(
+ 'search_vector', 'pg_catalog.english', 'description_plaintext', 'name'
+ )
+ """
+ ),
+ migrations.RunSQL(
+ """
+ CREATE FUNCTION product_trigger() RETURNS trigger AS $$
+ begin
+ new.search_vector :=
+ setweight(
+ to_tsvector('pg_catalog.english', coalesce(new.name,'')), 'A'
+ ) ||
+ setweight(
+ to_tsvector(
+ 'pg_catalog.english', coalesce(new.description_plaintext,'')),
+ 'B'
+ );
+ return new;
+ end
+ $$ LANGUAGE plpgsql;
+ CREATE TRIGGER tsvectorupdate BEFORE INSERT OR UPDATE
+ ON product_product FOR EACH ROW EXECUTE FUNCTION product_trigger();
+ """
+ ),
+ ]
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 135886fe0e..bf4dff485e 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -62,9 +62,6 @@ class Category(MPTTModel, ModelWithMetadata, SeoModel):
description = SanitizedJSONField(
blank=True, default=dict, sanitizer=clean_editor_js
)
- description_json = SanitizedJSONField(
- blank=True, default=dict, sanitizer=clean_editor_js
- )
parent = models.ForeignKey(
"self", null=True, blank=True, related_name="children", on_delete=models.CASCADE
)
@@ -90,9 +87,6 @@ class CategoryTranslation(SeoModelTranslation):
description = SanitizedJSONField(
blank=True, default=dict, sanitizer=clean_editor_js
)
- description_json = SanitizedJSONField(
- blank=True, default=dict, sanitizer=clean_editor_js
- )
class Meta:
unique_together = (("language_code", "category"),)
@@ -320,9 +314,6 @@ class Product(SeoModel, ModelWithMetadata):
description_plaintext = TextField(blank=True, default="")
search_vector = SearchVectorField(null=True, blank=True)
- description_json = SanitizedJSONField(
- blank=True, default=dict, sanitizer=clean_editor_js
- )
category = models.ForeignKey(
Category,
related_name="products",
@@ -394,9 +385,6 @@ class ProductTranslation(SeoModelTranslation):
description = SanitizedJSONField(
blank=True, default=dict, sanitizer=clean_editor_js
)
- description_json = SanitizedJSONField(
- blank=True, default=dict, sanitizer=clean_editor_js
- )
class Meta:
unique_together = (("language_code", "product"),)
@@ -715,9 +703,6 @@ class Collection(SeoModel, ModelWithMetadata):
description = SanitizedJSONField(
blank=True, default=dict, sanitizer=clean_editor_js
)
- description_json = SanitizedJSONField(
- blank=True, default=dict, sanitizer=clean_editor_js
- )
objects = CollectionsQueryset.as_manager()
@@ -760,9 +745,6 @@ class CollectionTranslation(SeoModelTranslation):
description = SanitizedJSONField(
blank=True, default=dict, sanitizer=clean_editor_js
)
- description_json = SanitizedJSONField(
- blank=True, default=dict, sanitizer=clean_editor_js
- )
class Meta:
unique_together = (("language_code", "collection"),)
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 66adacfbd5..5d7a4c5827 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -206,7 +206,7 @@ def generate_product_payload(product: "Product"):
product_fields = (
"name",
- "description_json",
+ "description",
"currency",
"attributes",
"updated_at",