我正在使用Django 2.0和postgres(PostgreSQL)9.6.1
我有以下模型标题和body_text:
class Entry(models.Model):
headline = models.CharField(max_length=255)
body_text = models.TextField()
def __str__(self):
return self.headline
以下是我的内容
headline: cheese making
body_text:
The simplest way to use full text search is to search a single term against a single column in the database. For example: >>> Entry.objects.filter(body_text__search='Cheese') [<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>]. This creates a to_tsvector in the database from the body_text field and a plainto_tsquery ...
以下使用search lookup
的搜索结果。我在INSTALLED_APPS中添加了'django.contrib.postgres'。
Case 1: Works
In [1]: Entry.objects.filter(body_text__search='Cheese')
Out[1]: <QuerySet [<Entry: cheese making>]>
Case 2: Not working
In [2]: Entry.objects.filter(body_text__search='Pizza')
Out[2]: <QuerySet []>
(the word Pizza is there in the body_text still is not searching)
Case 3: Not working
In [3]: Entry.objects.filter(body_text__search='vector')
Out[3]: <QuerySet []>
(the word vector is there in to_tsvector
Case 4: Not working
In [9]: Entry.objects.filter(body_text__search='Entry')
Out[9]: <QuerySet []>
Case 5: Not working
In [10]: Entry.objects.filter(body_text__search='data')
Out[10]: <QuerySet []>
如何搜索不起作用的术语。
我们在django中使用了postgresql的全文搜索模块来处理工作中的一些项目,我认为全文搜索是从条目的body_text中删除html标签,并且因为<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>
和<
而剥离>
。
我试图在你的例子中使用to_tsvector
,使用<
和>
并且没有它们,并且得到的向量是不同的:
SELECT to_tsvector('The simplest way to use full text search is to search a single term against a single column in the database. For example: >>> Entry.objects.filter(body_text__search=''Cheese'') [<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>]. This creates a to_tsvector in the database from the body_text field and a plainto_tsquery ...');
'bodi':25,39'chees':28'栏':18'创造':30'数据库':21,36'intry.objects.filter':24'exampl':23'场':41'满':6'platto':44'搜索':8,11,27'最简单':2'单独':13,17'术语':14'文字':7,26,40'tsqueri':45'tsvector ':33'使用':'''方式':3
SELECT to_tsvector('The simplest way to use full text search is to search a single term against a single column in the database. For example: >>> Entry.objects.filter(body_text__search=''Cheese'') [Entry: Cheese on Toast recipes, Entry: Pizza Recipes]. This creates a to_tsvector in the database from the body_text field and a plainto_tsquery ...');
'bodi':25,47'chees':28,30'专栏':18'创造':38'数据库':21,44'entri':29,34'entry.objects.filter':24'exampl' :23'场':49'满':6'披萨':35'普通话':52'收件人':33,36'搜索':8,11,27'最简单':2'单身':13,17 'term':14'文字':7,26,48'吐司':32'tsqueri':53'tsvector':41'使用':'''方式':3
因此,请尝试从<
中删除>
和body_text
。
“to_tsvector”是一个PostgreSQL函数,用于将文档转换为tsvector数据类型。
https://www.postgresql.org/docs/9.6/static/textsearch-controls.html
django.contrib.postgres在内部使用它来提供搜索查找(__search
)
https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/search/#the-search-lookup