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

Can be used in these methods:
search, setSettings, browseObjects, searchForFacetValues, generateSecuredApiKey, addApiKey, updateApiKey

About this parameter# A

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

Usually, a record must match all words in the query. By creating a list of optional words, records can match only some words. When using optional words, records that match all words rank higher than records that match only some words.

Optional words are often used in the context of empty or insufficient results. An alternative to optional words is to use removeWordsIfNoResults.

Usage notes#

  • The size of the API response will be larger.
  • You don’t need to put commas between words. Each string will automatically be tokenized into words (and all will be considered optional).

Caveat#

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

Examples# A

Set default list of optional words#

1
2
3
4
5
6
$index->setSettings([
  'optionalWords' => [
    'blue',
    'iphone case'
  ]
]);

Override optional words for a search query#

1
2
3
4
5
6
$results = $index->search('query', [
  'optionalWords' => [
    'toyota',
    '2020 2021'
  ]
]);

Doing an OR between all words of a query#

By default, Algolia will perform a logical AND between each query word. For example, when searching for iphone case, the engine will return records containing iphone and case. To change this to a logical OR, you must specify each word in the query as an optional word.

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

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

$results = $index->search($query, $params);
Did you find this page helpful?
PHP v3