首页 > 解决方案 > 如何在包含大型数据集的 django 中实现快速搜索(2-3 秒)?

问题描述

我正在 Django 中开展一个项目,我必须找到一个解决方案来创建快速搜索,该快速搜索大约需要 2 - 3 秒才能立即加载搜索结果。我正在使用 Django REST API 来处理查询。目前,我得到了结果,但往往需要花费大量时间来浏览包含大量数据的整个数据库。我需要一个我可以实施的解决方案,以便我可以将搜索时间减少到最多 3 秒。PS。我使用 PostgreSQL 作为数据库。

我的动机是搜索城市或国家,我需要得到结果。

模型.py

 class Search(models.Model):
 city = models.CharField('Search Destination', max_length=256, null = true)
 country = models.CharField('Search country', max_length=256, null = true)
 latitude = models.CharField('Search latitude', max_length=256, null = true)
 longitude = models.CharField('Search longitude', max_length=256, null = true)
 createdAt = models.DateTimeField('Created At', auto_now_add=True, null = true)
 slug = models.SlugField(max_length=256, null=True, blank=True)

 def __str__(self):
     return self.city

序列化程序.py

class SearchSerializer(serializers.ModelSerializer):
    class Meta:
        model = Search
        fields = '__all__'

视图.py

class ApiLandingSearchView(generics.ListAPIView):
    search_fields = ['city', country ]
    serializer_class = SearchSerializer
    filter_backends = [filters.SearchFilter]
    queryset = Search.objects.all()

标签: djangopostgresqlsearchdjango-rest-frameworkdataset

解决方案


您似乎希望通过 API 对您的搜索进行全文搜索。

SearchFilter在后台使用 django-admin 搜索功能,因此它在文本字段中搜索文本,默认情况下这在每个数据库上都很慢。

您必须为您的应用程序添加适当的全文搜索。

在您的情况下,我看到您可以采用两种方法:

  • django-watson,它基于 postgres 全文搜索功能
  • django-haystack,它可以让您与 elasticsearch 集成

您都必须通过构建自己的自定义过滤器后端来与 django-rest-framework 集成。


推荐阅读