API Reference / API Parameters / optionalWords
Feb. 26, 2019

optionalWords

Type: string | list of strings
Engine default: []
Parameter syntax
'optionalWords' => [
  'word',
  'word1 word2', // both words are optional
  ...
]

Can be used in these methods:

About this parameter

A list of words that should be considered as optional when found in the query.

Normally, in order for a record to match it must match all words in the query. By creating a list of optional words, you are also matching records that match only some of the words.

This impacts ranking as follows:

  • records that match all words are ranked higher
  • records that match only some words are ranked lower

Usage notes:

  • This invariably leads to a larger response.

  • This is a strategy to improve a response with little or no results.

  • You don’t need to put commas between words. Each string will automatically be tokenized into words, all of which will be considered as optional.

  • This parameter is often used in the context of empty or insufficient results. See discussion here. An alternative to optional words is to use removeWordsIfNoResults. See discussion here.

Caveat

  • If a query is four or more words AND all its words are optional, the default behavior of optionalWords changes.
    • The number of matched words needed for an object to be returned increases every time 1000 objects are found.
    • If optionalWords contains less than 10 optional words, the number of matched words required for a result increments by one.
    • From 10 optional words onwards, the number of matched words required increments by the number of optional words divided by 5 (rounded down). For example, for an 18 word query with all words optional, the number of matched words needed goes up by 3 for every 1000 results returned. (results 1-1000 require only one word, results 1001-2000 need four matched words, etc).

Examples

Set default list of optional words

1
2
3
4
5
6
$index->setSettings([
  'optionalWords' => [
    'word1',
    'word2 word3'
  ]
]);

Override optional words for a search query

1
2
3
4
5
6
$results = $index->search('query', [
  'optionalWords' => [
    'word1',
    'word2 word3'
  ]
]);

Doing an OR between all words of a query

By default Algolia will do an AND between each word of the query. That means that when searching for ‘word1 word2’, the engine will return records containing word1 AND word2. If instead of an AND you want to do an OR, you need to specify every word the query in optional words.

1
2
3
4
5
6
7
$query = 'the query';

$params = [
  'optionalWords' => $query
];

$results = $index->search($query, $params);

Did you find this page helpful?