在视图中使用全文搜索 + GIN (Django 1.11)

Chi*_*fir 7 postgresql gwt-gin django-models django-queryset django-views

我需要一些帮助来在 django 视图中使用 GIN 索引为全文搜索构建正确的查询。我有一个相当大的数据库(约 40 万行),需要对其中的 3 个字段进行全文搜索。尝试使用django 文档搜索,这是 GIN 之前的代码。它有效,但需要 6 秒以上的时间来搜索所有字段。接下来,我尝试实现GIN索引以加快搜索速度。已经有很多问题如何构建它。但我的问题是 -使用 GIN 索引进行搜索时,视图查询如何更改?我应该搜索哪些字段?

在 GIN 之前:

models.py

class Product(TimeStampedModel):
    product_id = models.AutoField(primary_key=True)
    shop = models.ForeignKey("Shop", to_field="shop_name")
    brand = models.ForeignKey("Brand", to_field="brand_name")
    title = models.TextField(blank=False, null=False)
    description = models.TextField(blank=True, null=True)
Run Code Online (Sandbox Code Playgroud)

视图.py

   
def get_cosmetic(request):
    if request.method == "GET":
        pass
    else:
        search_words = request.POST.get("search")
        search_vectors = (
            SearchVector("title", weight="B")
            + SearchVector("description", weight="C")
            + SearchVector("brand__brand_name", weight="A")
        )

        products = (
            Product.objects.annotate(
                search=search_vectors, rank=SearchRank(search_vectors, search)
            )
            .filter(search=search_words)
            .order_by("-rank")
        )

        return render(request, "example.html", {"products": products})
Run Code Online (Sandbox Code Playgroud)

在 GIN 之后:
models.py

class ProductManager(models.Manager):
    def with_documents(self):
        vector = (
            pg_search.SearchVector("brand__brand_name", weight="A")
            + pg_search.SearchVector("title", weight="A")
            + pg_search.SearchVector("description", weight="C")
        )
        return self.get_queryset().annotate(document=vector)


class Product(TimeStampedModel):
    product_id = models.AutoField(primary_key=True)
    shop = models.ForeignKey("Shop", to_field="shop_name")
    brand = models.ForeignKey("Brand", to_field="brand_name")
    title = models.TextField(blank=False, null=False)
    description = models.TextField(blank=True, null=True)

    search_vector = pg_search.SearchVectorField(null=True)

    objects = ProductManager()

    class Meta:
        indexes = [
            indexes.GinIndex(
                fields=["search_vector"],
                name="title_index",
            ),
        ]

    # update search_vector every time the entry updates
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        if (
            "update_fields" not in kwargs
            or "search_vector" not in kwargs["update_fields"]
        ):
            instance = (
                self._meta.default_manager
                .with_documents().get(pk=self.pk)
            )
            instance.search_vector = instance.document
            instance.save(update_fields=["search_vector"])
Run Code Online (Sandbox Code Playgroud)

视图.py

def get_cosmetic(request):
    if request.method == "GET":
        pass

    else:
        search_words = request.POST.get('search')    
        products = ?????????
        return render(request, 'example.html', {"products": products})
Run Code Online (Sandbox Code Playgroud)

Chi*_*fir 7

回答我自己的问题:

products = (
    Product.objects.annotate(rank=SearchRank(F("search_vector"), search_words))
    .filter(search_vector=search_words)
    .order_by("-rank")
)
Run Code Online (Sandbox Code Playgroud)


这意味着您应该搜索您的索引字段 - 在我的案例search_vector字段中。
另外我在 ProductManager() 类中更改了我的代码,所以现在我可以使用

products = Product.objects.with_documents(search_words)
Run Code Online (Sandbox Code Playgroud)

with_documents()自定义 ProductManager() 的自定义函数在哪里。此更改的秘诀在这里(第 29 页)

所有这些代码的作用是什么:

  1. 创建带有分数的 search_vector 字段,分数较大的字段 - 在结果排序中获得更高的位置。
  2. 通过 ORM Django 创建用于全文搜索的 GIN 索引
  3. 每次更改模型实例时都会更新 GIN 索引

    此代码不做的事情:
  4. 它不按查询的子字符串的相关性排序。可能的解决方案。

    希望这会对在 Django 中进行有点复杂的全文搜索的人有所帮助。