Guides / Algolia AI

Algolia Answers

Algolia Answers lets you semantically search your index data. It leverages NLU technologies to deeply analyze your user’s query and your records, and return the most relevant answer from within your content using machine learning.

For example, given the query “healthy soup” and an index of recipe blog articles, Answers could return the title “Bone Broth Strengthens Immunity, Body, and Joints”. Even if no query words appear in this title, semantic search allows you to draw connections within your content and find answers for your users in seconds.

An example usage of Algolia Answers

This feature is currently in closed beta. You can sign up to request access.

Getting started

Authentication

Once you have access to the Answers API, you need an API key with the nluReadAnswers ACL.
We recommend creating a new API key with only that permission, and optionally the search permission to allow building a hybrid Answers/Search interface.

Choosing your data

We have found that long texts, such as articles and transcripts, work best with Answers.

Finding Answers in your index

Once you have your credentials set up, you can send requests to the Answers API:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const data = {
  "query": "when do babies start learning?",
  "queryLanguages": ["en"],
  "attributesForPrediction": ["title", "description", "transcript"],
  "nbHits": 2
};

const URL = `https://${APPLICATION_ID}-dsn.algolia.net/1/answers/${INDEX_NAME}/prediction`;
fetch(URL, {
  method: "POST",
  headers: {
    "X-Algolia-Application-Id": ${APPLICATION_ID},
    "X-Algolia-API-Key": ${API_KEY_WITH_ANSWERS_ACL}
  },
  body: JSON.stringify(data)
})
  .then((response) => response.json())
  .then((res) => displayResults(res.hits))
  .catch(console.error);

The response is the same as the search response, with an extra _answer field in each hit. This field contains an extract from the hit answering the query, with its confidence score and source attribute in the hit as extractAttribute. Answers are ordered by decreasing confidence scores.

If no answers match the query, we return an empty hits array.

Example response

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
{
  "nbPages": 1,
  "nbHits": 2,
  "params": "query=when+do+babies+start+learning%3F&naturalLanguages=%5B%22en%22%5D&hitsPerPage=150&analyticsTags=%5B%22algolia-answers%22%5D&queryType=prefixNone&attributesToSnippet=%5B%22description%3A80%22%2C%22title%3A80%22%2C%22transcript%3A80%22%5D&restrictSearchableAttributes=%5B%22description%22%2C%22title%22%2C%22transcript%22%5D&queryLanguages=%5B%22en%22%5D&ignorePlurals=en&removeStopWords=en&removeWordsIfNoResults=allOptional&ruleContexts=natural_language&analyticsTags=algolia-answers%2Cnatural_language",
  "hitsPerPage": 150,
  "query": "when do babies start learning?",
  "exhaustiveNbHits": true,
  "hits": [
    {
      "description": "Pop quiz: When does learning begin? Answer: Before we are born. Science writer Annie Murphy Paul talks through new research that shows how much we learn in the womb -- from the lilt of our native language to our soon-to-be-favorite foods.",
      "duration": 1006,
      "languages": 37,
      "main_speaker": "Annie Murphy Paul",
      "name": "Annie Murphy Paul: What we learn before we're born",
      "speaker_occupation": "Science author",
      "tags": [
        "brain",
        "children",
        "culture",
        "education",
        "evolution",
        "food",
        "mental health",
        "neuroscience",
        "pregnancy",
        "science",
        "writing"
      ],
      "title": "What we learn before we're born",
      "url": "https://www.ted.com/talks/annie_murphy_paul_what_we_learn_before_we_re_born\n",
      "transcript": "French babies cry on a rising note while German babies end on a falling note, imitating the melodic contours of those languages. Now why would this kind of fetal learning be useful? It may have evolved to aid the baby's survival. From the moment of birth, the baby responds most to the voice of the person who is most likely to care for it — its mother. It even makes its cries sound like the mother's language, which may further endear the baby to the mother, and which may give the baby a head start in the critical task of learning how to understand and speak its native language.But it's not just sounds that fetuses are learning about in utero. It's also tastes and smells. By seven months of gestation, the fetus' taste buds are fully developed, and its olfactory receptors, which allow it to smell, are functioning. The flavors of the food a pregnant woman eats find their way into the amniotic fluid, which is continuously swallowed by the fetus. Babies seem to remember and prefer these tastes once they're out in the world. In one experiment, a group of pregnant women was asked to drink a lot of carrot juice during their third trimester of pregnancy, while another group of pregnant women drank only water. Six months later, the women's infants were offered cereal mixed with carrot juice, and their facial expressions were observed while they ate it. The offspring of the carrot juice drinking women ate more carrot-flavored cereal, and from the looks of it, they seemed to enjoy it more.A sort of French version of this experiment was carried out in Dijon, France where researchers found that mothers who consumed food and drink flavored with licorice-flavored anise during pregnancy showed a preference for anise on their first day of life, and again, when they were tested later, on their fourth day of life. Babies whose mothers did not eat anise during pregnancy showed a reaction that translated roughly as \"yuck.\" What this means is that fetuses are effectively being taught by their mothers about what is safe and good to eat. Fetuses are also being taught about the particular culture that they'll be joining through one of culture's most powerful expressions, which is food. They're being introduced to the characteristic flavors and spices of their culture's cuisine even before birth.Now it turns out that fetuses are learning even bigger lessons. But before I get to that, I want to address something that you may be wondering about. The notion of fetal learning may conjure up for you attempts to enrich the fetus — like playing Mozart through headphones placed on a pregnant belly. But actually, the nine-month-long process of molding and shaping that goes on in the womb is a lot more visceral and consequential than that. Much of what a pregnant woman encounters in her daily life — the air she breathes, the food and drink she consumes, the chemicals she's exposed to, even the emotions she feels — are shared in some fashion with her fetus. They make up a mix of influences as individual and idiosyncratic as the woman herself. The fetus incorporates these offerings into its own body, makes them part of its flesh and blood. And often it does something more. It treats these maternal contributions as information, as what I like to call biological postcards from the world outside.So what a fetus is learning about in utero is not Mozart's \"Magic Flute\" but answers to questions much more critical to its survival. Will it be born into a world of abundance or scarcity? Will it be safe and protected, or will it face constant dangers and threats? Will it live a long, fruitful life or a short, harried one? The pregnant woman's diet and stress level in particular provide important clues to prevailing conditions like a finger lifted to the wind. The resulting tuning and tweaking of a fetus' brain and other organs are part of what give us humans our enormous flexibility, our ability to thrive in a huge variety of environments, from the country to the city, from the tundra to the desert.",
      "objectID": "299355000",
      "_answer": {
        "extract": "Pop quiz: When does <em>learning</em> begin? Answer: Before we are born. Science writer Annie Murphy Paul talks through new research that shows how much we learn in the womb -- from the lilt of our native language to our soon-to-be-favorite foods.",
        "score": 212.239,
        "extractAttribute": "description"
      }
    },
    {
      "description": "Pawan Sinha details his groundbreaking research into how the brain's visual system develops. Sinha and his team provide free vision-restoring treatment to children born blind, and then study how their brains learn to interpret visual data. The work offers insights into neuroscience, engineering and even autism.",
      "duration": 1103,
      "languages": 30,
      "main_speaker": "Pawan Sinha",
      "name": "Pawan Sinha: How brains learn to see",
      "speaker_occupation": "Visual neuroscientist",
      "tags": [
        "biology",
        "health care",
        "medicine",
        "neuroscience",
        "science",
        "sight"
      ],
      "title": "How brains learn to see",
      "url": "https://www.ted.com/talks/pawan_sinha_on_how_brains_learn_to_see\n",
      "transcript": "If you are a blind child in India, you will very likely have to contend with at least two big pieces of bad news. The first bad news is that the chances of getting treatment are extremely slim to none, and that's because most of the blindness alleviation programs in the country are focused on adults, and there are very, very few hospitals that are actually equipped to treat children. In fact, if you were to be treated, you might well end up being treated by a person who has no medical credentials as this case from Rajasthan illustrates. This is a three-year-old orphan girl who had cataracts. So, her caretakers took her to the village medicine man, and instead of suggesting to the caretakers that the girl be taken to a hospital, the person decided to burn her abdomen with red-hot iron bars to drive out the demons. The second piece of bad news will be delivered to you by neuroscientists, who will tell you that if you are older than four or five years of age, that even if you have your eye corrected, the chances of your brain learning how to see are very, very slim — again, slim or none.So when I heard these two things, it troubled me deeply, both because of personal reasons and scientific reasons. So let me first start with the personal reason. It'll sound corny, but it's sincere. That's my son, Darius. As a new father, I have a qualitatively different sense of just how delicate babies are, what our obligations are towards them and how much love we can feel towards a child. I would move heaven and earth in order to get treatment for Darius, and for me to be told that there might be other Dariuses who are not getting treatment, that's just viscerally wrong. So that's the personal reason.Scientific reason is that this notion from neuroscience of critical periods — that if the brain is older than four or five years of age, it loses its ability to learn — that doesn't sit well with me, because I don't think that idea has been tested adequately. The birth of the idea is from David Hubel and Torsten Wiesel's work, two researchers who were at Harvard, and they got the Nobel Prize in 1981 for their studies of visual physiology, which are remarkably beautiful studies, but I believe some of their work has been extrapolated into the human domain prematurely. So, they did their work with kittens, with different kinds of deprivation regiments, and those studies, which date back to the '60s, are now being applied to human children.So I felt that I needed to do two things. One: provide care to children who are currently being deprived of treatment. That's the humanitarian mission. And the scientific mission would be to test the limits of visual plasticity. And these two missions, as you can tell, thread together perfectly. One adds to the other; in fact, one would be impossible without the other. So, to implement these twin missions, a few years ago, I launched Project Prakash. Prakash, as many of you know, is the Sanskrit word for light, and the idea is that in bringing light into the lives of children, we also have a chance of shedding light on some of the deepest mysteries of neuroscience. And the logo — even though it looks extremely Irish, it's actually derived from the Indian symbol of Diya, an earthen lamp. The Prakash, the overall effort has three components: outreach, to identify children in need of care; medical treatment; and in subsequent study. And I want to show you a short video clip that illustrates the first two components of this work.This is an outreach station conducted at a school for the blind.(Text: Most of the children are profoundly and permanently blind ...)Pawan Sinha: So, because this is a school for the blind, many children have permanent conditions. That's a case of microphthalmos, which is malformed eyes, and that's a permanent condition; it cannot be treated. That's an extreme of micropthalmos called enophthalmos. But, every so often, we come across children who show some residual vision, and that is a very good sign that the condition might actually be treatable.",
      "objectID": "301167000",
      },
      "_answer": {
        "extract": "the chances of your brain <em>learning</em> how to see are very, very slim — again, slim or none.So when I heard these two things, it troubled me deeply, both because of personal reasons and scientific reasons. So let me first <em>start</em> with the personal reason. It'll sound corny, but it's sincere. That's my son, Darius. As a new father, I have a qualitatively different sense of just how delicate <em>babies</em> are, what our obligations are towards them",
        "score": 152.885,
        "extractAttribute": "transcript"
      }
    }
  ],
  "processingTimeMS": 56,
  "page": 0
}

In this example, we’re removed the _highlightResult and _snippetResult attributes from the response for the sake of brevity.

Note that this response contains two Answers from the same record: Answers can return multiple answers from a single record when several parts of its content answer well the query.

Retrieving multiple answers

You can retrieve multiple answers for a query using the nbHits parameter. For example, in the above snippet, we’ve set the nbHits parameter to 2, to retrieve two answers. When retrieving multiple answers, we’ll sort them by decreasing confidence scores.

Using threshold to filter results based on confidence scores

You can use the threshold parameter to fine-tune the results set depending on confidence score. We remove any result with an _answer that has a lower score than the threshold.

We recommend a threshold of 0 to always retrieve at least one relevant answer. Only results that are very unrelated to the query have a negative confidence score. We recommend a threshold of 185 to only retrieve hits that the Answers engine predicts are highly relevant.

The score attribute for any answer is dependent on the query. While you can compare scores from various answers to the same query, comparing scores on answers for different queries doesn’t make sense.

Controlling highlighting

By default, we return answers with the matching word extract highlighted in _highlightResult. You can control highlighting at query time by setting attributesToHighlight in the params parameter.

Managing search analytics

To understand how your users search your application and measure the impact of semantic search, Algolia Answers integrates with your search analytics.

By default, we tag requests sent to the Answers API with the analyticsTags: "algolia-answers". You can add additional analyticsTags by declaring them in the params parameter.

Did you find this page helpful?