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

# optionalFilters

> Promote or demote records in the search results.

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="list<string>" default="[]" scope="search" />

Optional filters use the same syntax as [`facetFilters`](/doc/api-reference/api-parameters/facetFilters), but they behave differently:\
**They don't exclude records.** Instead, they influence the record's ranking.

Use them to promote or demote results without filtering them out. For example:

* To **promote** books by John Doe: `["category:Book", "author:John Doe"]`
* To **demote** items from the `Books` category: `["category:-Books"]`

## Usage

* Optional filters only have an effect if the [Filters ranking criterion](/doc/guides/managing-results/relevance-overview/in-depth/ranking-criteria) is present in your ranking formula (default behavior).
* They're applied **after** any sorting criteria ([sorting by attribute](/doc/guides/managing-results/refine-results/sorting/how-to/sort-by-attribute))
* On virtual replicas, optional filters are applied **after** the replica's [relevant sort](/doc/guides/managing-results/refine-results/sorting/in-depth/relevant-sort).
* Numeric comparisons aren't supported.
* If the Filters ranking criterion is applied before custom ranking (default), the optional filters take precedence over the custom ranking in the tie-breaking algorithm.
* To use an attribute as an optional filter, it must be included in the [`attributesForFaceting`](/doc/api-reference/api-parameters/attributesForFaceting) setting.

### Escape minus signs

If a facet value starts with `-` and isn't a negative filter, escape it: `category:\-movie`.

## Example

<AccordionGroup>
  <Accordion title="Current API clients" defaultOpen="true">
    <CodeGroup>
      ```cs C# theme={"system"}
      var response = await client.SearchSingleIndexAsync<Hit>(
        "INDEX_NAME",
        new SearchParams(
          new SearchParamsObject
          {
            OptionalFilters = new OptionalFilters(
              new List<OptionalFilters> { new OptionalFilters("can_deliver_quickly:true") }
            ),
          }
        )
      );
      ```

      ```dart Dart theme={"system"}
      final response = await client.searchSingleIndex(
        indexName: "INDEX_NAME",
        searchParams: SearchParamsObject(
          optionalFilters: [
            "can_deliver_quickly:true",
          ],
        ),
      );
      ```

      ```go Go theme={"system"}
      response, err := client.SearchSingleIndex(client.NewApiSearchSingleIndexRequest(
        "INDEX_NAME").WithSearchParams(search.SearchParamsObjectAsSearchParams(
        search.NewEmptySearchParamsObject().SetOptionalFilters(search.ArrayOfOptionalFiltersAsOptionalFilters(
          []search.OptionalFilters{*search.StringAsOptionalFilters("can_deliver_quickly:true")})))))
      if err != nil {
        // handle the eventual error
        panic(err)
      }
      ```

      ```java Java theme={"system"}
      SearchResponse response = client.searchSingleIndex(
        "INDEX_NAME",
        new SearchParamsObject().setOptionalFilters(OptionalFilters.of(Arrays.asList(OptionalFilters.of("can_deliver_quickly:true")))),
        Hit.class
      );
      ```

      ```js JavaScript theme={"system"}
      const response = await client.searchSingleIndex({
        indexName: 'indexName',
        searchParams: { optionalFilters: ['can_deliver_quickly:true'] },
      });
      ```

      ```kotlin Kotlin theme={"system"}
      var response =
        client.searchSingleIndex(
          indexName = "INDEX_NAME",
          searchParams =
            SearchParamsObject(
              optionalFilters =
                OptionalFilters.of(listOf(OptionalFilters.of("can_deliver_quickly:true")))
            ),
        )
      ```

      ```php PHP theme={"system"}
      $response = $client->searchSingleIndex(
          'INDEX_NAME',
          ['optionalFilters' => [
              'can_deliver_quickly:true',
          ],
          ],
      );
      ```

      ```python Python theme={"system"}
      response = client.search_single_index(
          index_name="INDEX_NAME",
          search_params={
              "optionalFilters": [
                  "can_deliver_quickly:true",
              ],
          },
      )
      ```

      ```ruby Ruby theme={"system"}
      response = client.search_single_index(
        "INDEX_NAME",
        Algolia::Search::SearchParamsObject.new(optional_filters: ["can_deliver_quickly:true"])
      )
      ```

      ```scala Scala theme={"system"}
      val response = Await.result(
        client.searchSingleIndex(
          indexName = "INDEX_NAME",
          searchParams = Some(
            SearchParamsObject(
              optionalFilters = Some(OptionalFilters(Seq(OptionalFilters("can_deliver_quickly:true"))))
            )
          )
        ),
        Duration(100, "sec")
      )
      ```

      ```swift Swift theme={"system"}
      let response: SearchResponse<Hit> = try await client.searchSingleIndex(
          indexName: "INDEX_NAME",
          searchParams: SearchSearchParams
              .searchSearchParamsObject(SearchSearchParamsObject(optionalFilters: SearchOptionalFilters
                      .arrayOfSearchOptionalFilters([SearchOptionalFilters.string("can_deliver_quickly:true")])))
      )
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Legacy API clients">
    <CodeGroup>
      ```cs C# theme={"system"}
      var query = new Query()
      {
        SearchQuery = "query",
        OptionalFilters = new List>
        {
          new List { "category:Book", "author:John Doe" }
        }
      };
      ```

      ```go Go theme={"system"}
      res, err := index.Search(
      	"query",
      	opt.OptionalFilterAnd("category:Book", "author:John Doe"),
      )
      ```

      ```java Java theme={"system"}
      index.search(
        new Query("query").setOptionalFilters(
          Collections.singletonList(Arrays.asList(
            "category:Book",
            "author:John Doe")))
      );
      ```

      ```js JavaScript theme={"system"}
      index
        .search("query", {
          optionalFilters: ["category:Book", "author:John Doe"],
        })
        .then(({ hits }) => {
          console.log(hits);
        });
      ```

      ```kotlin Kotlin theme={"system"}
      val query = query("query") {
          optionalFilters {
              and {
                  facet("category", "Book")
                  facet("author", "John Doe")
              }
          }
      }

      index.search(query)
      ```

      ```php PHP theme={"system"}
      $results = $index->search('query', [
        'optionalFilters' => [
          "category:Book",
          "author:John Doe"
        ]
      ]);
      ```

      ```python Python theme={"system"}
      results = index.search(
          "query", {"optionalFilters": ["category:Book", "author:John Doe"]}
      )
      ```

      ```ruby Ruby theme={"system"}
      results = index.search(
        "query",
        {
          optionalFilters: [
            "category:Book",
            "author:John Doe"
          ]
        }
      )
      ```

      ```scala Scala theme={"system"}
      client.execute {
        search into "myIndex" query Query(
          customParameters = Some(
            Map(
              "optionalFilters" -> Some(Seq(
                "category:Book",
                "author:John Doe"
              ))
            )
          )
      }
      ```

      ```swift Swift theme={"system"}
      let query = Query()
        .set(\.optionalFilters, to: ["category:Book", "author:John Doe"])

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