Semantic Queries

With the index now equipped with ELSER embeddings, the handle_search() function in app.py can be changed to search these embeddings. For now, you'll see how to search only through ELSER, later the previous search methods will be incorporated back to create a combined solution.

To use ELSER inferences when searching, the text_expansion query type is used. Below you can see an updated handle_search() function with this query:

The text_expansion query receives a key with the name of the field to be searched. Under this key, model_id configures which model to use in the search, and model_text defines what to search for. Note how in this case there is no need to generate an embedding for the search text, as Elasticsearch manages the model and can take care of that.

In the above version of handle_search() the filters have been left unused, and the aggregations have been omitted. These can be added back in the same way they were incorporated into the full-text search solution. Below is an updated handle_search() function that moves the text_expansion query inside a bool.must section, with filters included in bool.filter and aggregations added as before.

Spend some time experimenting with different searches. You will notice that as with dense vector embeddings, searches driven by the ELSER model work better than full-text search when the exact words do not appear in the indexed documents.

Ready to build state of the art search experiences?

Sufficiently advanced search isn’t achieved with the efforts of one. Elasticsearch is powered by data scientists, ML ops, engineers, and many more who are just as passionate about search as your are. Let’s connect and work together to build the magical search experience that will get you the results you want.

Try it yourself