For any project there may be a need to use a database full-text search. We expect high speed and relevant results from this search. When we face such problem, we usually think about Solr, ElasticSearch, Sphinx, AWS CloudSearch, etc. But in this article we will talk about PostgreSQL. Starting from version 8.3, a full-text search support in PostgreSQL is available. Let's look at how it is implemented in the DBMS itself.
The basic idea of a full-text search in PostgreSQL is that you create an index using a document, which contains the words you would like to use for search. For storing search data in PostgreSQL, new data type has been added - tsvector. Tsvector is a storage for the tokens from a document.
to_tsvector - is a support function that has been implemented to convert a document into the tsvector data type.
We can use logical operators
| (OR), and
! (NOT) for our queries. We need to use
tsquery for this:
When we want to check the search for a match, we have to use a full-text operator
Excellent! The match is found. Let's write a query that uses a logical operator
Match is found again. Now let's modify the query so that it could return a negative result:
More information can be found in the PostgreSQL documentation. So at this point we will stop talking about full-text search in PostgreSQL and move on to using this in Django.
A full-text search with PostgreSQL support in Django appeared with version 1.10. In previous Django versions the full-text search in PostgreSQL was possible with djorm-ext-pgfulltext library.
Let's look at what kind of interface gives for us django postgres full text search. The easiest way to do a full-text search using
search. Let’s consider the following example:
Post model 2 matches with the word
Programming have been found. This record creates
to_tsvector in the database for the
body field and
search lookup is great when we need to search by one field. If we want to search by two or more fields, SearchVector should be used, for example:
As you can see, this time we were searching by
category__title fields, and as a result, found 3 matches.
SearchVector objects can be grouped together for the further reuse (the DRY principles are followed):
If we need to convert the word into the search query object, we can use SearchQuery:
Now let's assume that we need to sort the search results by relevance. PostgreSQL provides a ranging function for these purposes, which determines how often the words are found in the document, how these words are close to each other in the document and how important that part of the document, where these words are situated, is. Ranking interface in Django full text search is provided by
SearchRank. Let's look at an example:
The most relevant records are at the top.
SearchQuery and SearchVector accept the config as a parameter. It is necessary for using different search settings, for example, if you want to change the language parser or dictionary.
We can also control the relevance, by setting different weight to those fields, which we plan to search by. For this
SearchVector accepts a
weight parameter. As the
weight value there can be one of these letters: D, C, B, A. The default values for these letters are 0.1, 0.2, 0.4 and 1.0 respectively.
Search in your project may be one of the most resource-intensive operations, especially if it is a search in a few hundred or even thousands of records. And this is the point when the optimization problem arises. Let's look at the tools for optimization which PostgreSQL gives us and how it is implemented in Django.
To speed up the search, PostgreSQL offers the use of indexes. It is worth noting that the index is not required for a full-text search. But if the search takes place in specific (constant) columns, the presence of the index is desirable.
There are 2 types of indexes:
GiST (Generalized Search Tree) - a bit signature is assigned for each document, which contains information about all the tokens that are in this document. It is created with a command:
GIN (Generalized Inverted Index) - in this type of index the key is a token and the value is an organized list of document identifiers which contain the token. It is created with a command:
There is a big difference in performance between these two types of indexes. Before you choose which one to use, I recommend you to study the documentation on them in detail. I would like to add that:
It is best to use GiST index for updated data, and GIN index suits well for static data.
Another way to speed up the search is to use SearchVectorField in the model. You will need to use triggers to fill in this field, for example, as described in the Triggers for Automatic Updates documentation. After that, you can query the field, so if it is annotated SearchVector.
When you need a full-text search, and you do not want to connect third-party libraries to the project, you can easily manage database resources using a full-text search in PostgreSQL and the api, which provides Django for work with the search.
For local project settings, I use old trick with settings_local file:try:from settings_local import \*except ImportError:passSo in settings_local.py we can override variables from settings.py. I didn't know how to supplement them. For example how to add line to INSTALLED_APPS without copying whole list.Yesterday I finally understood that I can import settings from settings_local:# settings_local.pyfrom settings import \*INSTALLED_APPS += (# ...)
It appears that not everyone knows that in python you can create classes dynamically without metaclasses. I'll show an example of how to do it.So we've learned how to use custom QuerySet to chain requests:Article.objects.old().public()Now we need to make it work for related objects:user.articles.old().public()This is done using use_for_related_fields, but it needs a little trick.