我拥有丰富的产品数据库,旨在实现全文搜索功能,使用户能够轻松搜索产品。为此,我将 SearchVector 与 Postgres 结合使用;然而,性能却相当低迷。尽管尝试通过索引来提高速度,但并未产生预期的结果。下面是我一直在使用的代码片段。
models.py
class Product(models.Model):
brand = models.ForeignKey(BrandName,related_name="brand_products", on_delete=models.CASCADE,db_index = True)
item_name_title = models.CharField(max_length=10000, db_index = True,)
product_description = models.TextField(db_index = True,)
class Meta:
indexes = [
GinIndex(fields=['search_vector']),
]
Views.py
search = request.GET.get('search')
search_vector = SearchVector(
'product__mob_sku',
'product__item_name_title',
'product__product_description',
'product__brand__brand_name',
)
query = SearchQuery(search)
vendor_products = VendorProducts.objects.annotate(
rank = (SearchRank(search_vector , query))
).filter(rank__gte=0.001).select_related(
'vendor', 'product').prefetch_related(
'product__product_images', 'product__brand').exclude(
vendor__vendor_name = "ALL_123").order_by('-rank')
您的索引未被使用,因为您的搜索跨越多个模型。您确实需要将所有这些相关字段放入一个大搜索索引中。
如果您愿意使用第 3 方 Django 应用程序,
django-watson
支持此功能:
https://github.com/etianen/django-watson/wiki/registering-models#searching-across-lated-models
(我很久以前就写了
django-watson
,但它仍然保留着!)