> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# optionalWords

> Words to consider optional matches

export const Setting = ({type, default: defaultValue, defaultNote, scope, min, max, formerly}) => {
  const renderedDefault = defaultValue === '' ? '""' : defaultValue;
  const renderedNote = defaultNote ? `(${defaultNote})` : '';
  return <ul>
      <li><strong>Type:</strong> <code>{type}</code></li>
      <li><strong>Default:</strong> <code>{renderedDefault}</code>{renderedNote}</li>
      {min && <li><strong>Min:</strong> <code>{min}</code></li>}
      {max && <li><strong>Max:</strong> <code>{max}</code></li>}
      <li><strong>Scope:</strong> <a href="/doc/api-reference/api-parameters"><code>{scope}</code></a></li>
      {formerly && <li>
          <strong>Deprecated name:</strong> <code>{formerly}</code>
        </li>}
    </ul>;
};

<Setting type="string | list<string>" default="[]" scope="settings,search" />

The `optionalWords` parameter defines which words in the query are considered optional.

By default, all query terms must match for a record to be included in the search results.
For example, a search for `phone case` only returns records where the words `phone` **and** `case` occur in the searchable attributes.

Optional words allow for **query relaxation**.
For example, with `phone` and `case` as optional words,
the same search returns records with the words `phone` **or** `case`.

Matches with all words rank higher than matches with only non-optional words.

<Info>
  When using optional words, Algolia performs ["double querying"](/doc/guides/managing-results/optimize-search-results/empty-or-insufficient-results#create-a-list-of-optional-words):
  one query with all terms, and another where optional words are removed.
  Results are merged and re-ranked.
</Info>

## Usage

* You can include multiple optional phrases or word sets.
* Each string is interpreted as a set of optional words.
  Don't separate words with commas.
* This feature increases the response size.
* There isn't a hard limit on the number of words,
  but using too many can slow down [`getSettings`](/doc/rest-api/search/get-settings) and the Algolia dashboard.

### Long queries

If the query contains **four or more optional words**,
the required number of matched words in a record increases for every 1,000 records:

* If `optionalWords` has up to 10 words, the required number of matched words increases by 1.
* If `optionalWords` has 10 or more words, the required number of matching words is based on the number of optional words divided by 5 (rounded down).
  For example:

  * For the first 1,000 results, 1 matched word is required.
  * For the next 1,000 results, 4 matched words are needed (the initial 1, plus the calculated increase of 3).

### Comparison with `removeWordsIfNoResults`

Use [`removeWordsIfNoResults`](/doc/api-reference/api-parameters/removeWordsIfNoResults) when you want optional behavior only if no results are found.
This is more adaptive for unpredictable, user-generated queries.

### Comparison with stop words

[Stop word removal](/doc/guides/managing-results/optimize-search-results/handling-natural-languages-nlp/in-depth/language-specific-configurations#remove-stop-words)
always ignores common words (words that add no value to a search query, such as "the", "on", and "it")

## Examples

### Set default list of optional words for all queries

<AccordionGroup>
  <Accordion title="Current API clients" defaultOpen="true">
    This example sets `"blue"` and `"iphone case"` as optional words for all queries.
    That means, a query for `blue iphone case` matches records that match *either* `blue`,
    *or* `iphone case`, or both.

    <CodeGroup>
      ```cs C# theme={"system"}
      var response = await client.SetSettingsAsync(
        "INDEX_NAME",
        new IndexSettings
        {
          OptionalWords = new OptionalWords(new List<string> { "blue", "iphone case" }),
        }
      );
      ```

      ```dart Dart theme={"system"}
      final response = await client.setSettings(
        indexName: "INDEX_NAME",
        indexSettings: IndexSettings(
          optionalWords: [
            "blue",
            "iphone case",
          ],
        ),
      );
      ```

      ```go Go theme={"system"}
      response, err := client.SetSettings(client.NewApiSetSettingsRequest(
        "INDEX_NAME",
        search.NewEmptyIndexSettings().SetOptionalWords(search.ArrayOfStringAsOptionalWords(
          []string{"blue", "iphone case"}))))
      if err != nil {
        // handle the eventual error
        panic(err)
      }
      ```

      ```java Java theme={"system"}
      UpdatedAtResponse response = client.setSettings(
        "INDEX_NAME",
        new IndexSettings().setOptionalWords(OptionalWords.of(Arrays.asList("blue", "iphone case")))
      );
      ```

      ```js JavaScript theme={"system"}
      const response = await client.setSettings({
        indexName: 'theIndexName',
        indexSettings: { optionalWords: ['blue', 'iphone case'] },
      });
      ```

      ```kotlin Kotlin theme={"system"}
      var response =
        client.setSettings(
          indexName = "INDEX_NAME",
          indexSettings =
            IndexSettings(optionalWords = OptionalWords.of(listOf("blue", "iphone case"))),
        )
      ```

      ```php PHP theme={"system"}
      $response = $client->setSettings(
          'INDEX_NAME',
          ['optionalWords' => [
              'blue',

              'iphone case',
          ],
          ],
      );
      ```

      ```python Python theme={"system"}
      response = client.set_settings(
          index_name="INDEX_NAME",
          index_settings={
              "optionalWords": [
                  "blue",
                  "iphone case",
              ],
          },
      )
      ```

      ```ruby Ruby theme={"system"}
      response = client.set_settings(
        "INDEX_NAME",
        Algolia::Search::IndexSettings.new(optional_words: ["blue", "iphone case"])
      )
      ```

      ```scala Scala theme={"system"}
      val response = Await.result(
        client.setSettings(
          indexName = "INDEX_NAME",
          indexSettings = IndexSettings(
            optionalWords = Some(OptionalWords(Seq("blue", "iphone case")))
          )
        ),
        Duration(100, "sec")
      )
      ```

      ```swift Swift theme={"system"}
      let response = try await client.setSettings(
          indexName: "INDEX_NAME",
          indexSettings: IndexSettings(optionalWords: SearchOptionalWords.arrayOfString(["blue", "iphone case"]))
      )
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Legacy API clients">
    This example sets `"blue"` and `"iphone case"` as optional words for all queries.
    That means, a query for `blue iphone case` matches records that match *either* `blue`,
    *or* `iphone case`, or both.

    <CodeGroup>
      ```cs C# theme={"system"}
      IndexSettings settings = new IndexSettings();
      settings.OptionalWords = new List
      {
        "blue",
        "iphone case"
      },

      index.SetSettings(settings);
      ```

      ```go Go theme={"system"}
      res, err := index.SetSettings(search.Settings{
      	OptionalWords: opt.OptionalWords(
      		"blue",
      		"iphone case",
      	),
      })
      ```

      ```java Java theme={"system"}
      index.setSettings(
        new IndexSettings()
          .setOptionalWords(
            Arrays.asList(
              "blue",
              "iphone case"
            )
          )
      );
      ```

      ```js JavaScript theme={"system"}
      index
        .setSettings({
          optionalWords: ["blue", "iphone case"],
        })
        .then(() => {
          // done
        });
      ```

      ```kotlin Kotlin theme={"system"}
      val settings = settings {
          optionalWords {
              +"blue"
              +"iphone case"
          }
      }

      index.setSettings(settings)
      ```

      ```php PHP theme={"system"}
      $index->setSettings([
        'optionalWords' => [
          'blue',
          'iphone case'
        ]
      ]);
      ```

      ```python Python theme={"system"}
      index.set_settings({"optionalWords": ["blue", "iphone case"]})
      ```

      ```ruby Ruby theme={"system"}
      index.set_settings(
        {
          optionalWords: [
            "blue",
            "iphone case"
          ]
        }
      )
      ```

      ```scala Scala theme={"system"}
      client.execute {
        setSettings of "myIndex" `with` IndexSettings(
          optionalWords = Some(Seq(
            "blue",
            "iphone case"
          ))
        )
      }
      ```

      ```swift Swift theme={"system"}
      let settings = Settings()
        .set(\.optionalWords, to: ["blue", "iphone case"])

      index.setSettings(settings) { result in
        if case .success(let response) = result {
          print("Response: \(response)")
        }
      }
      ```
    </CodeGroup>
  </Accordion>
</AccordionGroup>

### Override optional words for the current query

<AccordionGroup>
  <Accordion title="Current API clients" defaultOpen>
    <CodeGroup>
      ```cs C# theme={"system"}
      var response = await client.SearchSingleIndexAsync<Hit>(
        "INDEX_NAME",
        new SearchParams(
          new SearchParamsObject
          {
            Query = "query",
            OptionalWords = new OptionalWords(new List<string> { "toyota", "2020 2021" }),
          }
        )
      );
      ```

      ```dart Dart theme={"system"}
      final response = await client.searchSingleIndex(
        indexName: "INDEX_NAME",
        searchParams: SearchParamsObject(
          query: "query",
          optionalWords: [
            "toyota",
            "2020 2021",
          ],
        ),
      );
      ```

      ```go Go theme={"system"}
      response, err := client.SearchSingleIndex(client.NewApiSearchSingleIndexRequest(
        "INDEX_NAME").WithSearchParams(search.SearchParamsObjectAsSearchParams(
        search.NewEmptySearchParamsObject().SetQuery("query").SetOptionalWords(search.ArrayOfStringAsOptionalWords(
          []string{"toyota", "2020 2021"})))))
      if err != nil {
        // handle the eventual error
        panic(err)
      }
      ```

      ```java Java theme={"system"}
      SearchResponse response = client.searchSingleIndex(
        "INDEX_NAME",
        new SearchParamsObject().setQuery("query").setOptionalWords(OptionalWords.of(Arrays.asList("toyota", "2020 2021"))),
        Hit.class
      );
      ```

      ```js JavaScript theme={"system"}
      const response = await client.searchSingleIndex({
        indexName: 'indexName',
        searchParams: { query: 'query', optionalWords: ['toyota', '2020 2021'] },
      });
      ```

      ```kotlin Kotlin theme={"system"}
      var response =
        client.searchSingleIndex(
          indexName = "INDEX_NAME",
          searchParams =
            SearchParamsObject(
              query = "query",
              optionalWords = OptionalWords.of(listOf("toyota", "2020 2021")),
            ),
        )
      ```

      ```php PHP theme={"system"}
      $response = $client->searchSingleIndex(
          'INDEX_NAME',
          ['query' => 'query',
              'optionalWords' => [
                  'toyota',

                  '2020 2021',
              ],
          ],
      );
      ```

      ```python Python theme={"system"}
      response = client.search_single_index(
          index_name="INDEX_NAME",
          search_params={
              "query": "query",
              "optionalWords": [
                  "toyota",
                  "2020 2021",
              ],
          },
      )
      ```

      ```ruby Ruby theme={"system"}
      response = client.search_single_index(
        "INDEX_NAME",
        Algolia::Search::SearchParamsObject.new(query: "query", optional_words: ["toyota", "2020 2021"])
      )
      ```

      ```scala Scala theme={"system"}
      val response = Await.result(
        client.searchSingleIndex(
          indexName = "INDEX_NAME",
          searchParams = Some(
            SearchParamsObject(
              query = Some("query"),
              optionalWords = Some(OptionalWords(Seq("toyota", "2020 2021")))
            )
          )
        ),
        Duration(100, "sec")
      )
      ```

      ```swift Swift theme={"system"}
      let response: SearchResponse<Hit> = try await client.searchSingleIndex(
          indexName: "INDEX_NAME",
          searchParams: SearchSearchParams.searchSearchParamsObject(SearchSearchParamsObject(
              query: "query",
              optionalWords: SearchOptionalWords.arrayOfString(["toyota", "2020 2021"])
          ))
      )
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Legacy API clients">
    <CodeGroup>
      ```cs C# theme={"system"}
      index.Search(new Query("")
      {
          OptionalWords = new List
          {
            "toyota",
            "2020 2021"
          },
      });
      ```

      ```go Go theme={"system"}
      res, err := index.Search(
      "query",

        OptionalWords: opt.OptionalWords(
          "toyota",
          "2020 2021",
        },
      })
      ```

      ```java Java theme={"system"}
      index.search(
        new Query("query")
          .setOptionalWords(
            Arrays.asList(
              "toyota",
              "2020 2021"
            )
          )
      );
      ```

      ```js JavaScript theme={"system"}
      index
        .search("query", {
          optionalWords: ["toyota", "2020 2021"],
        })
        .then(({ hits }) => {
          console.log(hits);
        });
      ```

      ```kotlin Kotlin theme={"system"}
      val query = query("query") {
          optionalWords {
              +"toyota"
              +"2020 2021"
          }
      }

      index.search(query)
      ```

      ```php PHP theme={"system"}
      $results = $index->search('query', [
        'optionalWords' => [
          'toyota',
          '2020 2021'
        ]
      ]);
      ```

      ```python Python theme={"system"}
      results = index.search("query", {"optionalWords": ["toyota", "2020 2021"]})
      ```

      ```ruby Ruby theme={"system"}
      results = index.search(
        "query",
        {
          optionalWords: [
            "toyota",
            "2020 2021"
          ]
        }
      )
      ```

      ```scala Scala theme={"system"}
      client.execute {
        search into "myIndex" query Query(
          query = Some("query"),
          optionalWords = Some(Seq(
            "toyota",
            "2020 2021"
          ))
        )
      }
      ```

      ```swift Swift theme={"system"}
      let query = Query(query: "query")
      query.optionalWords = ["toyota", "2020 2021"]

      index.search(query, completionHandler: { (res, error) in
        print(res)
      })
      ```
    </CodeGroup>
  </Accordion>
</AccordionGroup>
