【问题标题】:Do a full text search by using two models使用两个模型进行全文搜索
【发布时间】:2019-08-16 11:23:09
【问题描述】:

我有两个型号ItemOwner

class Item(models.Model):
    name = models.CharField(max_length=255)
    owner = models.ForeignKey(
        Owner, related_name='owner_items',
        on_delete=models.CASCADE,
    )
    is_featured = models.BooleanField(
        choices=CHOICES, default=BOOL_NO
    )
    # ...

我在项目名称和描述字段中进行全文搜索(基于 Django 文档)。 PostgreSQL 版本是 10。

search_vectors = (
    SearchVector('name', weight='A', config='english') +
    SearchVector('description', weight='B', config='english')
)
terms = [SearchQuery(term) for term in keyword.split()]
search_query = functools.reduce(operator.or_, terms)
search_rank = SearchRank(
    search_vectors, search_query, weights=[0.2, 0.4, 0.6, 1]
)
qs = Item.objects.all().annotate(
    rank=search_rank
).filter(rank__gte=0.2).order_by('-rank')

我还想在方程式中引入Ownername 字段,如果is_featuredtrue,也可以稍微提升排名。

在进行此搜索之前,我有 Owner 实例模型。

【问题讨论】:

  • 如果我的回答解决了你的问题,请接受!

标签: python django postgresql full-text-search django-queryset


【解决方案1】:

您可以在search_vector 中添加Owner 类中的字段name,可能使用不同的weight 和相同的config (这只是一个假设,因为您没有指定所有者模型定义或数据)

使用is_featured 作为rank 提升的一种方法可以是注释1 (您可以使用其他值)如果它是True,然后将其添加到@987654329 @结果。

from django.db import models
from django.db.models import Case, Value, When
from django.contrib.postgres.search import (
    SearchQuery, SearchRank, SearchVector,
)

search_vectors = (
    SearchVector('name', weight='A', config='english') +
    SearchVector('description', weight='B', config='english') +
    SearchVector('owner__name', weight='C', config='english')
)
terms = [SearchQuery(term) for term in keyword.split()]
search_query = functools.reduce(operator.or_, terms)
search_rank = SearchRank(
    search_vectors, search_query, weights=[0.2, 0.4, 0.6, 1]
)
qs = Item.objects.all().annotate(
    featured_boost=Case(
        When(is_featured=True, then=Value(1)),
        default=Value(0),
        output_field=models.IntegerField(),
    )
).annotate(
    rank=search_rank + featured_boost
).filter(rank__gte=0.2).order_by('-rank')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 2020-05-06
    • 2012-07-29
    • 2023-03-02
    • 2010-11-11
    • 2010-11-25
    • 2017-06-04
    相关资源
    最近更新 更多