- Django 2 by Example
- Antonio Melé
- 201字
- 2021-06-25 21:19:08
Searching with trigram similarity
Another search approach is trigram similarity. A trigram is a group of three consecutive characters. You can measure the similarity of two strings by counting the number of trigrams they share. This approach turns out to be very effective for measuring the similarity of words in many languages.
In order to use trigrams in PostgreSQL, you will need to install the pg_trgm extension first. Execute the following command from the shell to connect to your database:
psql blog
Then, execute the following command to install the pg_trgm extension:
CREATE EXTENSION pg_trgm;
Let's edit our view and modify it to search for trigrams. Edit the views.py file of your blog application and add the following import:
from django.contrib.postgres.search import TrigramSimilarity
Then, replace Post search query with the following lines:
results = Post.objects.annotate(
similarity=TrigramSimilarity('title', query),
).filter(similarity__gt=0.3).order_by('-similarity')
Open http://127.0.0.1:8000/blog/search/ in your browser and test different searches for trigrams. The following example displays a hypothetical typo in the django term, showing search results for yango:

Now, you have a powerful search engine built into your project. You can find more information about full-text search at https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/search/.
- 物聯網安全(原書第2版)
- 光網絡評估及案例分析
- Building Django 2.0 Web Applications
- Web Application Development with R Using Shiny
- 物聯網+BIM:構建數字孿生的未來
- Go Web Scraping Quick Start Guide
- Building RESTful Web Services with Spring 5(Second Edition)
- 網管員必讀:網絡管理(第2版)
- Windows Server 2012 Hyper-V虛擬化管理實踐
- 網絡AI+:2030后的未來網絡
- 物聯網頂層設計與關鍵技術
- 精通SEO:100%網站流量提升密碼
- 5G智慧交通
- 移動互聯網環境下的核心網剖析及演進
- RestKit for iOS