Full-Text Search in Django with PostgreSQL
paulox.net
paulox.net
I just finished a a project where we chose Postgres's FTS over using Elastic Search. At the beginning, I was worried about what performance we'd see since we choose to not use ES. But after slight performance tweaking, we had even our least performing queries under 50ms.
You could lean on the relevancy strategies built in to ES, but in my experience you're better off understanding what relevancy means for your dataset and implementing a strategy yourself. Your millage may vary though, I'd never advocate reimplenting something that's already provided by your chosen tool.
The options and tools for configuring and tweaking relevancy between ES and PostgreSQL's FTS are surprisingly similar for many application use cases. If you're interested you can check out Postgres' search rank and query weighting configurations.
I've had to build complex queries against ElasticSearch and it is specifically designed for things like this. We had custom weightings so when you searched for certain natural keys associated with each item they would rank above everything else, and that is easily do-able with ES. Simultaneously, we would weigh results according to various metadata we had attached to each entry (audio stream languages, subtitles, content owner name, genre, etc.). And finally, if you searched for the name of the media (a movie or an episode in a TV show) the user would see all the matches ranked accordingly, but again weighed according to the content owner and various language features of that media file.
You can probably hack that together with PostgreSQL, but is basically one big query in ES. PG's FTS is still great; but its use-case is slightly different.
( Maybe surprisingly? ) This is type of query is natively supported by Postgres. That support is robust and mature, you don’t have to hack it together.
ES is a great tool and it’s clear your a fan of it. If you’re interested, I’d recommend you look into Postgres capabilities. It’s not a replacement for ES by any means ( or even a competitor to in my opinion; Postgres isn’t even distributed ). But for specific use cases, you might find that Postgres capabilities surprise you!
By the way, I am a huge fan of PG and relational databases in general; PG, especially, is a great database, and the first tool I reach for when it comes to data storage. However, we had other requirements (aside from the complexity I left out) to do with versioning and so forth that swung in favour of ES. Ultimately the problem with FTS in RDBMS, for me, boils down to doing FTS across disparate -- let's call them 'documents' -- stored across multiple tables. Basically you have to use materialised views (with manual refreshing) or complex join mechanics that affect performance. Perhaps PG 10 has improved in this area also?
Ranking is hard. You SHOULD lean on the tools available in Lucene/Solr/ES. PG's ranking tools are a joke in comparison.
> The options and tools for configuring and tweaking relevancy between ES and PostgreSQL's FTS are surprisingly similar for many application use cases.
That simply isn't true.
This is not the case.
The OOTB search capabilities in ElasticSearch (even by default) far, far exceed what you get in PostgreSQL FTS.
Also you're completely contradicting yourself. You say you don't advocate reimplmenting something provided by the tool but then suggest doing exactly that.
Maybe in very very limited scenarios, but in general, they aren't even close. PostgreSQL doesn't take corpus frequencies into account, which makes it pretty difficult to come anywhere near the relevance ranking quality of Elasticsearch (or any proper search engine).
In order to tell whether PG vs Elastic is appropriate for your use case, you need to do an evaluation. See: https://en.wikipedia.org/wiki/Text_Retrieval_Conference
I'm putting together a product which has a search feature and that uses Django + MySQL and I'm struggling with relevancy. I'd happily accept 500ms queries if that guaranteed me the relevant hit would be on the first page. That's FAR more usable than 50ms queries and then the relevant hit is on page 5.
1. issues with i18n and l10n tokenization. Does PG support other languages?
2. At minimum you need to support tf-idf (or something better), it doesn't look like PG supports this either.
3. For extremely dumb ranking, you can have a render/engaged column in PG. For decent production stuff you need a decision tree ranker (or GBDT).
All in all, none of these are there in PG, I'm not familiar with Solr/Lucene either, but please educate yourselves before expressing such strong opinions marketed as the absolute truth.
ElastiSearch easily gets expensive and the search suggestion is pretty bad.
ElasticSearch starts off as a small Java application that wraps the Lucene library.
Obviously heap will increase with usage and number of documents but I am still confused how it is in any way "expensive".
In other project I used Elastic for the search function: Django + PostgreSQL (DB) + Haystack + ES (FTS).
Is obvious that the second solution is more expensive.
- Using a `SearchVectorField` is a must after 500K rows.
- Make keeping this field up to date easy for yourself by populating it using `SeachVector` with a Django pre_save signal or PostgreSQL trigger. This reduces CPU utilization significantly as the parsing and tokenization of the field your searching on is done a head of time.
- Adding a GIN Index on your `SearchVectorField` column will improve performance dramatically.
- You should specify your language configuration for postgres FTS parser. The default parser doesn't do much. It just removes spaces and normalize case. Specifying a language lets the parser make heavier optimizations that noticeably improve performance and the quality of results. If you need support for more then one langue, Django already makes it easy for this configuration to be dynamic.
Even more importantly in some circumstances, having the full column allows the optimizer to pick another index when it's totally relevant, and filter the relevant rows without needing to recompute the TSV one by one for the subset.
You might be able to get away with if if you were indexing a less then large amount of very small documents.
I like your expression index idea a lot.
Unless you're saying that you would populate the field only on some rows and not all of them, and control this from the app. But you could do that with an expression index, too, assuming the rule is a simple, pure function:
CREATE INDEX index_posts_on_body
ON posts (to_tsvector(body, 'english'))
WHERE published = true;
or similar.If you want the out-of-the-box distributed experience, then you can't go wrong with Elasticsearch because of the built-in sharding mechanism. However, figuring out how many shards you need for each index, where should each shard sits, and how to balance out the cluster has always been a trial and error exercise. Indices continue to grow like there is infinite space, and performance will degrade. What I find useful in the end is to have multiple ES clusters, which seems obvious right? One of the most frequently asked questions is "how many nodes do I need", and the answer is always "it depends" which is true, but gives me a chill. With Cassandra, from my experience, adding more nodes (scale horizontally) so data spread more thinly, and revisit some data structure change, would be an acceptable answer.
The other thing is a lot of folks I have worked with just dump stuff into ES because ES feels like a dumping ground for "json"-like documents (reminds of me MongoDB). Please compress, understand mappings and different fields to make the document smaller...
I am still very convinced SQL databases are robust enough to take any lazy dumping.
1. https://www.elastic.co/guide/en/elasticsearch/reference/6.1/...
2. https://www.elastic.co/guide/en/elasticsearch/reference/6.1/...
That way you're not having to completely redo your search infrastructure at some point in time.
You can seamlessly scale from 1 document to billions without any change to your code, backup approach, monitoring etc.
Sorry, I am not sure why you brought up a single instance. If you run on a single instance, you lose half of the benefits of ES which is trying to be highly available.
If we have an index which does not need any backups, single instance is fine, but for most people single instance is not an option. Furthermore, if one is already struggling with 3-4 nodes, how helpful is single instance?
My point was merely that ElasticSearch scales from very small use cases to very large ones. You don't have to setup a cluster. And that using your SQL database isn't going to be significantly easier to manage.
A SQL database doesn't run out of memory and crash when you add documents to it "too fast". ElasticSearch does.
https://sqlalchemy-searchable.readthedocs.io/en/latest/insta...
had us easily swap out Algolia for search with Postgres FTS.
In elasticsearch, relevance is Tf-IDF or BM25. I don't see anything similar in FTS.
Not sure how I can results around ranking as well as spell correction/suggestions simultaneously.
Maybe in other project ES will be a better solutions.
https://www.elastic.co/guide/en/elasticsearch/reference/curr...
Ping me (http://o19s.com/doug) if you’d like a discount code!
similarity/relevance is the mathematical difference between search and database query. Its an inexact match.
1. https://lucene.apache.org/solr/guide/7_2/uploading-structure...
With PostgREST you can avoid the abstractions overhead and just use plain SQL and REST calls, basically to do a fts using `to_tsquery` you would do:
CREATE TABLE blog_entry( headline text, body_text tsvector );
GET localhost:3000/blog_entry?body_text=fts.Cheese&select=headline
http://django-haystack.readthedocs.io/en/master/tutorial.htm...
I'll write another article about it and, if they vote it, I'll have a talk about it in the next PyCon Nove conference http://www.paulox.net/talks/#pycon-nove
This screenshot was taken on my secondary monitor, which is 1280x1024 in portrait mode: https://i.imgur.com/n3LGCKM.png
Also I'm not a fan of all the visual noise, such as the orange paragraph markers next to every title.
EDIT: Replaced "fucking" with the intended "funky", I have no idea how that typo happened.
I used the default markdown plugin to generate paragraph markers and I found convenient to link directly to a paragraph.
Until it's fixed you can probably just narrow your browser window until the hero image moves from the side to the top.
The Flex theme is not so old, but can be better, but I'm going to update it based on many report I received here.
BTW pelican site is quite fast https://developers.google.com/speed/pagespeed/insights/?url=...
Can I ask which browser are you using ?