利用SearchVector()进行中文关键字搜索
发布时间:2023-12-22 20:38:56
SearchVector()是Django中用于中文关键字搜索的一个函数。它可以将中文文本转换为一个可搜索的向量,并提供了一些方法来对这些向量进行操作和使用。
下面是一个使用SearchVector()进行中文关键字搜索的例子:
首先,安装必要的依赖:
pip install django django.contrib.postgres
然后,在Django的settings.py文件中添加以下配置:
INSTALLED_APPS = [
...
'django.contrib.postgres',
...
]
DATABASES = {
...
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'your_database_name',
...
}
}
接下来,在需要进行搜索的模型中,导入SearchVector:
from django.contrib.postgres.search import SearchVector from django.db import models
然后,在模型中定义一个字段来存储被搜索的中文文本:
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
search_vector = SearchVector(fields=['title', 'content']) # 定义搜索向量字段
def __str__(self):
return self.title
然后,使用迁移命令来为模型创建数据库表:
python manage.py makemigrations python manage.py migrate
接下来,在视图函数中进行搜索:
from django.contrib.postgres.search import SearchQuery, SearchRank
def search_articles(request):
keyword = request.GET.get('keyword') # 获取搜索关键字
search_query = SearchQuery(keyword) # 创建搜索查询对象
articles = Article.objects.annotate(rank=SearchRank(article.search_vector, search_query)).filter(rank__gte=0.3) # 过滤搜索结果,将排名低于0.3的结果排除
context = {'articles': articles, 'keyword': keyword}
return render(request, 'search_results.html', context)
最后,在模板中显示搜索结果:
<h1>Search Results for "{{ keyword }}"</h1>
{% for article in articles %}
<div class="article">
<h2>{{ article.title }}</h2>
<p>{{ article.content }}</p>
</div>
{% empty %}
<p>No articles found.</p>
{% endfor %}
以上是一个简单的使用SearchVector()进行中文关键字搜索的例子。你可以根据自己的需求进行修改和扩展,以适应更复杂的场景。
