An example of using the Algolia search API using the example of a telegram bot

In this example, we will analyze how to use the search API in the well-known search service Algolia.

Idea

The idea was extremely simple, it was necessary to make a bot that, when entering the name of the drug, finds information about how much alcohol can be consumed. I must say right away that the bot was washed down and is working successfully, helping (I hope) to maintain the health of citizens. If anything, then Dr. Znaev’s Alcobot is here

A task

At the input we have the name of the drug, we use it to find the relevant record from the database and send it to the user. In principle, everything is quite simple, no rocket technology. But the problem is that users very often misspell or enter the name incorrectly. A search engine with fuzzy search was best suited for this task. It was decided to use Algolia, since it is convenient to add data to it and it provides a convenient, fairly simple API for use.

Here is a piece of data in JSON format

{
  "drugs": [ // по этому полю будем искать
    "Допегит", 
    "Метилдопа"
  ],
  "threashold": "12 часов", // это показываем пользователю
  "consequences": "Усиливает снижение давления", // и это показываем
  "objectID": "ff26ba646e8ba_dashboard_generated_id" // сгенерированный Algolia айди
}

Data

The data was collected long and painfully. A professional narcologist collected information from the RLS (Register of Medicines) for several weeks and sent it to me.

Index

Now you need to create a project and an index. Everything is quite simple here, click Create New, select the free version (it allows up to 10 thousand requests per month, more than enough). Next, select the data center. Algolia has moved its datacenters out of Russia, but mine are in Europe, so far there have been no problems. Next, click all the necessary checkboxes and click Create

You will immediately be prompted to create the first index, which of course must be done. I don’t think it makes sense to load each step, everything is very simple there. Next, you need to choose how we will enter the data, I chose the manual method.

Next, we need to take our JSON objects and paste them into the popup window.

When creating objects in this way, each entry will receive an id in the format ff26ba646e8ba_dashboard_generated_id. It looks so-so, but you can live.

Now the index needs to be adjusted so that the search does not take place on all data, but only on the array drugs

To do this, in the index interface, go to the Configuration tab and add a field for indexing (button Add searchable Attribute)

The code

To access the index, we need our application id and keys. I use the admin key as I sometimes write to the database. Let’s go to Settings -> API Keys, there are our keys.

Now let’s move on to the code. The server is running on node.js, examples will be on it.

So, we import the library and initialize the index

const algoliasearch = require('algoliasearch');

const client = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_ADMIN_API_KEY);

const alco = client.initIndex('alco'); // alco называется мой индекс в Algolia

Search

By the name of the drug we are looking for a record

exports.findDrug = async (drug, user = {}) => {
  return alco.search(drug, { userToken: `${user.id}`, typoTolerance: 'strict', });
}

This function will return an object that has a field hits, is an array with search results. Algolia has great documentation with code examples. Here link to our search function

Here we have three options

Nothing found. Show a message that nothing was found.

One variant found. We take the only option, take out the necessary values ​​and form a response to the user.

Found multiple options. A little more difficult. I don’t worry, I take the first two matches and pull out the names and ID of the entry from them and form a button out of them

    if (hits.length > 1) {
      const ret = [];
      const firstMatches = hits.splice(0, Math.min(2, hits.length));

      const matches = firstMatches.map(({ objectID, _highlightResult }) => ({ objectID, match: utils.fetchDrugNameFromAliases(_highlightResult.drugs) }));

      const buttons = matches.map(({ objectID, match }) => ([{ text: match, callback_data: `/match&${objectID}` }]));

      options.reply_markup = JSON.stringify({ inline_keyboard: buttons });

      return [FEW_RESULTS_FOUND, options];
    }

_highlightResult contains an array drugsbecause in the index this field is also an array, each record will have a match degree, and we filter by it

  • none (0)

  • partial (some)

  • full (all)

The result looks like this for the user:

Search by ID

In each button, the id of the entry is sewn up and when pressed, it is necessary to pull it out.

exports.find = async (drugId) => {
  return alco.getObject(drugId);
}

Total

In this simple way, we integrated high-end search into our humble application. I didn’t have to raise any databases, clusters or anything. In general, Algolia is a very powerful thing, they have AI built in there for recommendations, and in general everything is kosher.

Thanks to all. Your Ö.

Similar Posts

Leave a Reply