官术网_书友最值得收藏!

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/.

主站蜘蛛池模板: 弥渡县| 嘉善县| 林口县| 通化县| 长葛市| 平顶山市| 伊宁市| 定远县| 旌德县| 东辽县| 阿瓦提县| 穆棱市| 天镇县| 巧家县| 从江县| 昆山市| 平谷区| 淄博市| 文水县| 皮山县| 桑植县| 永丰县| 万荣县| 青河县| 白城市| 图木舒克市| 台中市| 聊城市| 锦州市| 江油市| 读书| 新蔡县| 旺苍县| 日喀则市| 南汇区| 泸溪县| 太保市| 扬中市| 云阳县| 云龙县| 兴文县|