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

# Search for facet values

> Search for a set of values within a given facet attribute. Can be combined with a query.

export const Legacy = ({title, href}) => {
  return <Note>

    This page documents an earlier version of the API client.
    For the latest version, see <a href={href}>{title}</a>.

    </Note>;
};

<Legacy title="Search for facet values" href="/doc/libraries/sdk/methods/search/search-for-facet-values" />

**Required ACL:** `search`

This method lets you search through the values of a facet attribute and select a **subset of those values that meet a given criteria**.

Facet-searching only affects facet values, not the index search.
For a facet attribute to be searchable,
it must have been declared in the [`attributesForFaceting`](/doc/api-reference/api-parameters/attributesForFaceting) index setting with the `searchable` modifier.

By default:

* Results are **sorted by decreasing count**.
  You can adjust with [`sortFacetValuesBy`](/doc/api-reference/api-parameters/sortFacetValuesBy).
* A maximum of **10 results are returned**.
  You can adjust with [`maxFacetHits`](/doc/api-reference/api-parameters/maxFacetHits).

This method is often used in combination with a user's current search with [search parameters](/doc/api-reference/search-api-parameters).
By combining facet and query searches, you control the number of facet values a user sees.
When you have **thousands of different values** for a given facet attribute,
it's impossible to display them all on a user interface.
With [`search_for_facet_values`](/doc/libraries/sdk/v1/methods/search-for-facet-values),
you allow your users to search within a specific faceted attribute
(for example, brands, authors, or categories) without needing to create a separate index.
You can still display the most common occurrences for each facet at the top,
but also enable users to search for a specific value for filtering.

<Info>
  Search for facet values doesn't work if you have **more than 65 searchable facets and searchable attributes combined**:
  any such search results in an empty list of facet values.
</Info>

## Examples

### Search for facet values

<CodeGroup>
  ```cs C# theme={"system"}
  // Search the values of the "category" facet matching "phone".
  index.SearchForFacetValue(new SearchForFacetRequest
  {
      FacetName = "phone",
      FacetQuery = "category"
  });
  ```

  ```go Go theme={"system"}
  // Search the values of the "category" facet matching "phone".
  index.SearchForFacetValues("category", "phone")
  ```

  ```java Java theme={"system"}
  // Search the values of the "category" facet matching "phone".

  // Sync version
  SearchForFacetResponse result = index.searchForFacetValues(
      new SearchForFacetRequest().setFacetName("phone").setFacetQuery("category"));

  // Async version
  CompletableFuture<SearchForFacetResponse> result = index.searchForFacetValuesAsync(
      new SearchForFacetRequest().setFacetName("phone").setFacetQuery("category"));
  ```

  ```js JavaScript theme={"system"}
  // Search the "category" facet for values matching "phone" in records
  index.searchForFacetValues('category', 'phone').then(({ facetHits }) => {
    console.log(facetHits);
  });
  ```

  ```kotlin Kotlin theme={"system"}
  val attribute = Attribute("category")

  index.searchForFacets(attribute, "phone")
  ```

  ```php PHP theme={"system"}
  # Search the values of the "category" facet matching "phone".
  $index->searchForFacetValues("category", "phone");
  ```

  ```python Python theme={"system"}
  # Search the values of the "category" facet matching "phone".
  index.search_for_facet_values('category', 'phone')
  ```

  ```ruby Ruby theme={"system"}
  # Search the values of the "category" facet matching "phone".
  index.search_for_facet_values('category', 'phone')
  ```

  ```scala Scala theme={"system"}
  client.execute {
    search into "myIndex" facet "category" values "phone"
  }
  ```

  ```swift Swift theme={"system"}
  index.searchForFacetValues(of: "category", matching: "phone") { result in
    if case .success(let response) = result {
      print("Response: \(response)")
    }
  }
  ```
</CodeGroup>

### Search for facet values with additional search parameters

<CodeGroup>
  ```cs C# theme={"system"}
  // Search the "category" facet for values matching "phone" in records
  // having "Apple" in their "brand" facet.
  var queryParams = new Query
  {
    Filters = "brand:Apple"
  };

  index.SearchForFacetValue(new SearchForFacetRequest
  {
      FacetName = "phone",
      FacetQuery = "category",
      SearchParameters = queryParams
  });
  ```

  ```go Go theme={"system"}
  // Search the "category" facet for values matching "phone" in records
  // having "Apple" in their "brand" facet.
  index.SearchForFacetValues("category", "phone", opt.Filters("brand:Apple"))
  ```

  ```java Java theme={"system"}
  Query query = new Query().setFilters("brand:Apple");

  // Search the "category" facet for values matching "phone" in records
  // having "Apple" in their "brand" facet.

  //Sync version
  SearchFacetResult result =
    index.searchForFacetValues("category", "phone", query);

  //Async version
  CompletableFuture<SearchFacetResult> result =
    index.searchForFacetValues("category", "phone", query);
  ```

  ```js JavaScript theme={"system"}
  // Search the "category" facet for values matching "phone" in records
  // having "Apple" in their "brand" facet.
  index.searchForFacetValues('category', 'phone', {
    filters: 'brand:apple'
  }).then(({ facetHits }) => {
    console.log(facetHits);
  });
  ```

  ```kotlin Kotlin theme={"system"}
  val attribute = Attribute("category")

  index.searchForFacets(attribute, "phone", Query(filters = "brand:Apple"))
  ```

  ```php PHP theme={"system"}
  // Search the "category" facet for values matching "phone"
  // in records having "Apple" in their "brand" facet.
  $index->searchForFacetValues("category", "phone", [
    'filters' => 'brand:Apple'
  ]);
  ```

  ```python Python theme={"system"}
  query = {
      'filters': 'brand:Apple'
  }
  # Search the values of the "category" facet matching "phone" for the records
  # having "Apple" in their "brand" facet.
  index.search_for_facet_values('category', 'phone', query)
  ```

  ```ruby Ruby theme={"system"}
  # Search the "category" facet for values matching "phone" in records
  # having "Apple" in their "brand" facet.
  index.search_for_facet_values('category', 'phone', {
    params: {
      filters: 'brand:Apple'
    }
  })
  ```

  ```scala Scala theme={"system"}
  client.execute {
    search into "myIndex" facet "category" values "phone" query Query(
        filters = Some(Seq("brand:Apple"))
    )
  }
  ```

  ```swift Swift theme={"system"}
  // Search the "category" facet for values matching "phone" in records
  // having "Apple" in their "brand" facet.
  var query = Query()
  query.filters = "brand:Apple"
  index.searchForFacetValues(of: "category",
                             matching: "phone",
                             applicableFor: query) { result in
    if case .success(let response) = result {
      print("Response: \(response)")
    }
  }
  ```
</CodeGroup>

### Search for facet values and send extra HTTP headers

<CodeGroup>
  ```cs C# theme={"system"}
  // Search the "category" facet for values matching "phone" in records
  // having "Apple" in their "brand" facet.

  var queryParams = new Query
  {
    Filters = "brand:Apple"
  };

  var requestOptions = new RequestOptions
  {
      Headers = new Dictionary<string,string>{ { "X-Algolia-User-ID", "user123" } }
  };

  index.SearchForFacetValue(new SearchForFacetRequest
  {
      FacetName = "phone",
      FacetQuery = "category",
      SearchParameters = queryParams
  }, requestOptions);
  ```

  ```go Go theme={"system"}
  extraHeaders := opt.ExtraHeader(map[string]string{
      "X-Forwarded-For": "94.228.178.246",
  })

  index.SearchForFacetValues("category", "phone", extraHeaders)
  ```

  ```java Java theme={"system"}
  Query query = new Query().setFilters("brand:Apple");

  // Search the "category" facet for values matching "phone" in records
  // having "Apple" in their "brand" facet.

  //Sync version
  SearchFacetResult result = index.searchForFacetValues(
    "category",
    "phone",
    query,
    new RequestOptions().addExtraHeader("X-Algolia-User-ID", "user123")
  );

  //Async version
  CompletableFuture<SearchFacetResult> result = index.searchForFacetValues(
    "category",
    "phone",
    query,
    new RequestOptions().addExtraHeader("X-Algolia-User-ID", "user123")
  );
  ```

  ```js JavaScript theme={"system"}
  // Search the "category" facet for values matching "phone" in records
  // having "Apple" in their "brand" facet.
  // only for the user123

  index.searchForFacetValues('category', 'phone', {
    filters: 'brand:apple',
    headers: {
      'X-Algolia-User-ID': 'user123'
    }
  }).then(({ facetHits }) => {
    console.log(facetHits);
  });
  ```

  ```kotlin Kotlin theme={"system"}
  val attribute = Attribute("category")
  val requestOptions = requestOptions {
      header("X-Algolia-User-ID", "user123")
  }

  index.searchForFacets(attribute, "phone", Query(filters = "brand:Apple"), requestOptions)
  ```

  ```php PHP theme={"system"}
  # Search the "category" facet for values matching "phone" in records
  $index->searchForFacetValues("category", "phone", [
    'X-Algolia-User-ID' => 'user123'
  ]);
  ```

  ```python Python theme={"system"}
  # Search the values of the 'category' facet matching 'phone' for the records
  index.search_for_facet_values('category', 'phone', {
      'X-Algolia-User-ID': 'user123'
  })
  ```

  ```ruby Ruby theme={"system"}
  # Search the "category" facet for values matching "phone" in records
  index.search_for_facet_values('category', 'phone', {
    headers: {
      'X-Algolia-User-ID': 'user123'
    }
  })
  ```

  ```scala Scala theme={"system"}
  client.execute {
    search into "myIndex" facet "category" values "phone" query Query(
        filters = Some(Seq("brand:Apple"))
    ) options RequestOptions(extraHeaders = Some(Map("X-Algolia-User-ID" => "user123")))
  }
  ```

  ```swift Swift theme={"system"}
  // Search the "category" facet for values matching "phone" in records
  // having "Apple" in their "brand" facet.
  var query = Query()
  query.filters = "brand:Apple"

  var requestOptions = RequestOptions()
  requestOptions.headers["X-Algolia-UserToken"] = "user123"

  index.searchForFacetValues(of: "category",
                             matching: "phone",
                             applicableFor: query,
                             requestOptions: requestOptions) { result in
    if case .success(let response) = result {
      print("Response: \(response)")
    }
  }
  ```
</CodeGroup>

## Parameters

<ParamField body="facetName" type="string" required>
  Attribute name.

  For this to work, you must declare the attribute with
  [`attributesForFaceting`](/doc/api-reference/api-parameters/attributesForFaceting) using the `searchable()` modifier.
</ParamField>

<ParamField body="facetQuery" type="string" required>
  The search query used to search the facet attribute.

  <Info>
    Facet queries only match [prefixes](/doc/guides/managing-results/optimize-search-results/override-search-engine-defaults/in-depth/prefix-searching), [typos](/doc/guides/managing-results/optimize-search-results/typo-tolerance), and [exact](/doc/guides/managing-results/optimize-search-results/override-search-engine-defaults/in-depth/adjust-exact-settings).
  </Info>
</ParamField>

<ParamField body="requestOptions" type="object">
  A mapping of request options with this method.
</ParamField>

<ParamField body="searchParameters" type="object">
  The mapping of [search parameters](/doc/api-reference/search-api-parameters) used to search the underlying index.

  If set, the method will return facet values that both:

  * Match the facet query
  * Are contained in the records matching the regular search query

  Using this parameter aligns the **count** of each facet value to current search results. Without it, the count is based on the whole index.

  <Info>
    **`page`, `hitsPerPage`, `offset`, and `length` parameters don't affect the count**, as the count value represents the whole set of results, not just the current page. **[maxFacetHits](/doc/api-reference/api-parameters/maxFacetHits) and [sortFacetValuesBy](/doc/api-reference/api-parameters/sortFacetValuesBy) do affect the returned facet values**.
  </Info>
</ParamField>

## Response

<ResponseField name="count" type="integer">
  The number of times the value is present in the dataset.
</ResponseField>

<ResponseField name="exhaustiveFacetsCount" type="boolean">
  Whether the count returned for each facetHit is exhaustive.
</ResponseField>

<ResponseField name="facetHits" type="object[]" />

<ResponseField name="highlighted" type="string">
  Highlighted value.
</ResponseField>

<ResponseField name="processingTimeMS" type="integer">
  Processing time.
</ResponseField>

<ResponseField name="value" type="string">
  Facet value.
</ResponseField>

### Response as JSON

This section shows the JSON response returned by the API.
Each API client wraps this response in language-specific objects, so the structure may vary.
To view the response, use the `getLogs` method.
Don't rely on the order of properties—JSON objects don't preserve key order.

```jsonc JSON icon=braces theme={"system"}
{
    "facetHits": [
        {
            "value": "Mobile phones",
            "highlighted": "Mobile <em>phone</em>s",
            "count": 507
        },
        {
            "value": "Phone cases",
            "highlighted": "<em>Phone</em> cases",
            "count": 63
        }
    ],
    "exhaustiveFacetsCount": true,
    "exhaustive": {
      "facetsCount": true
    },
    "processingTimeMS": 1
}
```
