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.

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?