dimamik

dimamik

Torus - Integrate PostgreSQL's search into Ecto queries

Torus is a plug-and-play Elixir library that seamlessly integrates PostgreSQL’s search into Ecto, streamlining the construction of advanced search queries.

The goal is to help developers create Ecto queries that return relevant results with optimal performance, and it’s best to show how on an example:

  1. Pattern matching: Searches for a specific pattern in a string.

    iex> insert_posts!(["Wand", "Magic wand", "Owl"])
    ...> Post
    ...> |> Torus.ilike([p], [p.title], "wan%")
    ...> |> select([p], p.title)
    ...> |> Repo.all()
    ["Wand"]
    

    See like/5, ilike/5, and similar_to/5 for more details.

  2. Similarity: Searches for items that are closely alike based on attributes, often using measures like cosine similarity or Euclidean distance. Is great for fuzzy searching and ignoring typos in short texts.

    iex> insert_posts!(["Hogwarts Secrets", "Quidditch Fever", "Hogwart’s Secret"])
    ...> Post
    ...> |> Torus.similarity([p], [p.title], "hoggwarrds")
    ...> |> limit(2)
    ...> |> select([p], p.title)
    ...> |> Repo.all()
    ["Hogwarts Secrets", "Hogwart’s Secret"]
    

    See similarity/5 for more details.

  3. Text Search Vectors: Uses term-document matrix vectors for full-text search, enabling efficient querying and ranking based on term frequency. - PostgreSQL: Full Text Search. Is great for large datasets to quickly return relevant results.

       iex> insert_post!(title: "Hogwarts Shocker", body: "A spell disrupts the Quidditch Cup.")
       ...> insert_post!(title: "Diagon Bombshell", body: "Secrets uncovered in the heart of Hogwarts.")
       ...> insert_post!(title: "Completely unrelated", body: "No magic here!")
       ...>  Post
       ...> |> Torus.full_text([p], [p.title, p.body], "uncov hogwar")
       ...> |> select([p], p.title)
       ...> |> Repo.all()
       ["Diagon Bombshell"]
    

    See full_text/5 for more details.

  4. Semantic Search: Understands the contextual meaning of queries to match and retrieve related content utilizing natural language processing. Read more about semantic search in Semantic search with Torus guide.

    insert_post!(title: "Hogwarts Shocker", body: "A spell disrupts the Quidditch Cup.")
    insert_post!(title: "Diagon Bombshell", body: "Secrets uncovered in the heart of Hogwarts.")
    insert_post!(title: "Completely unrelated", body: "No magic here!")
    
    embedding_vector = Torus.to_vector("A magic school in the UK")
    
    Post
    |> Torus.semantic([p], p.embedding, embedding_vector)
    |> select([p], p.title)
    |> Repo.all()
    ["Diagon Bombshell"]
    

    See semantic/5 for more details.

The above macros accept a list of options to customize their behavior. See function docs for examples. Most functions have an optimization section that might help you boost the performance of these search queries.

In upcoming plans, we’ll add support for highlighting search results and extend the search with hybrid search. Please let me know what do you think of it, and I’ll gladly hear any suggestions on how to make it better!

Links

Most Liked

dimamik

dimamik

Hey!

Semantic search is finally here! Read more in Semantic search with Torus guide.
Shortly - it allows you to generate embeddings using a configurable (and chainable) adapters and use them to compare against the ones stored in your database.

Supported adapters (for now):

  • Torus.Embeddings.OpenAI - uses OpenAI’s API to generate embeddings.

  • Torus.Embeddings.HuggingFace - uses HuggingFace’s API to generate embeddings.

  • Torus.Embeddings.LocalNxServing - generate embeddings on your local machine using a variety of models available on Hugging Face

  • Torus.Embeddings.PostgresML - uses PostgreSQL PostgresML extension to generate embeddings

  • Torus.Embeddings.Batcher - a long‑running GenServer that collects individual embedding calls, groups them into a single batch, and forwards the batch to the configured embedding_module (any from the above or your custom one).

  • Torus.Embeddings.NebulexCache - a wrapper around Nebulex cache, allowing you to cache the embedding calls in memory, so you save the resources/cost of calling the embedding module multiple times for the same input.

And you can easily create your own adapter by implementing the Torus.Embedding behaviour.

So after you’ll pick your favorite embedding adapter, you can add semantic search:

def search(term) do
  search_vector = Torus.to_vector(term)

  Post
  |> Torus.semantic([p], p.embedding, search_vector, distance: :l2_distance, pre_filter: 0.7)
  |> Repo.all()
end

Future plans:

  • Release torus_example app that would allow experimenting with options and different search types to pick the best one
  • Add support for highlighting search results. (Base off of a ts_headline function)
  • Extend similarity search to support fuzzystrmatch extension distance options.

Links

dimamik

dimamik

Torus v0.5.2 is released!

New :fire:

  • New demo page where you can explore different search types and their options. It also includes semantic search, so if you’re hesitant - go check it out!
  • Other documentation improvements

Fixes

  • Correctly handles order: :none in Torus.semantic/5 search.
  • Updates Torus.Embeddings.HuggingFace to point to the updated feature extraction endpoint.
  • Suppresses warnings for missing ecto_sql dependency by adding it to the required dependencies. Most of us already had it, but now it’ll be explicit.
  • Correctly parses an array of integers in Torus.QueryInspector.substituted_sql/3 and Torus.QueryInspector.tap_substituted_sql/3. Now we should be able to handle all possible query variations.
e class="onebox allowlistedgeneric" data-onebox-src="https://torus.dimamik.com">
torus.dimamik.com
D4no0

D4no0

What is the difference between the ecto like/ilike and the one provided by your library?

dimamik

dimamik

There are a few options, either in postgresql.conf or per-database in a migration:

defmodule YourApp.Repo.Migrations.SetWordSimilarityThreshold do
  use Ecto.Migration

  @database Application.compile_env!(:your_app_name, YourApp.Repo)[:database]

  def up do
    execute("""
    ALTER DATABASE #{@database} SET pg_trgm.word_similarity_threshold = 0.5;
    """)
  end

  def down do
    execute("""
    ALTER DATABASE #{@database} RESET pg_trgm.word_similarity_threshold;
    """)
  end
end

gushonorato

gushonorato

Looks interesting! I saw that all the examples were using “function-style queries.” Does Torus support “macro-style” queries? If not, are you planning to add support for them?

Where Next?

Popular in Libraries Top

scohen
Lexical Lexical is a next-generation language server for the Elixir programming language. Features Context aware code completion As-you...
New
tmbb
I’ve been working on two packages (not on hex.pm yet) to build admin interfaces for phoenix apps: bureaucrat - which contains a bunch ...
New
oltarasenko
Dear Elixir community, After a year of development, bug fixes, and improvements, we are proudly ready to share the release of Crawly 0.1...
New
sabiwara
Dune is a sandbox for Elixir and aims to safely evaluate user-provided code. You can try it out using this basic Elixir playground made ...
New
tfwright
After working on it for a couple of months and using it in production for most of that time, today I’ve released LiveAdmin, a LiveView ba...
New
tmbb
I’ve published the first version of my Makeup library. It’s a syntax highlighter for Elixir in the spirit of Pygments, Currently it highl...
New
tmbb
PhoenixWS - Websockets over Phoenix Channels Source code on Github here: https://github.com/tmbb/phoenix_ws Phoenix channels are a great...
New
ericlathrop
I built a silly site for Halloween that uses Phoenix Channels on the backend, and React on the frontend. I had many problems integrating ...
New
Crowdhailer
Experimenting with this code. OK.try do user <- fetch_user(1) cart <- fetch_cart(1) order = checkout(cart, user) save_or...
New
ostinelli
Let’s write a database! Well not really, but I think it’s a little sad that there doesn’t seem to be a simple in-memory distributed KV da...
New

Other popular topics Top

openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New

Sub Categories:

We're in Beta

About us Mission Statement