A
A
axel2018-06-22 22:26:43
Django
axel, 2018-06-22 22:26:43

How to sort by icontains?

There is a table, according to which, some fields are searched through fieldname__icontains. Question - how to sort the resulting queryset by the "closeness" of the occurrence? For example, there are records (the recordset is not real, just to be clear):

котел
котлета
коты
котировка
икота
кот

With the search query "cat" - the first in the queryset was "cat", because the match is complete, then "cats", because after the occurrence of the word "cat" - just one letter following, then - in random order - "cauldron, cutlet, quote" - because after "cat" there are already a lot of letters, but the words begin with "cat", and only then, at the end - "hiccup", because it contains the desired string already inside the word.
Is it really possible to do this yourself? Or is it already necessary to use all sorts of search engines, such as elastic, sphinx?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2018-06-23
@Antoine

Postgres has a search for trigrams, trigrams have similarity (by which you can sort and filter). In django (it seems, since 1.10) there are bindings for all this - https://docs.djangoproject.com/en/2.0/ref/contrib/...
You need to install pg_trgm in the database; ( which is also in dzhanga , but for this the user of the dzhanga database must be a superuser)
You can make a GiN trigram index, which will speed up the execution of __icontains.
An example of a search can be found here: https://ukar.su/
I did a search for the guys just on trigrams. But there he is a little smarter - he knows how to understand the erroneous layout. You can search, for example, "Thermaflex". You enter Thermaflix, thermoflex, eukschaduly, termaflex, thermosfrex, nthvjaktrc, flexstermo - it still finds

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question