> ## 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 multiple indices

> Perform a search on several indices at the same time, with one method call.

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 multiple indices" href="/doc/libraries/sdk/methods/search/search" />

**Required ACL:** `search`

The returned results are broken down by query.
You can use up to 50 queries in a multiple queries request.
You can use this method for a search query or facet search by specifying the `type` parameter to be `default` or `facet`.

This method can be useful in these scenarios:

1. You have **multiple indices that serve different purposes**.
   This is typical when you want to search your main index
   as well as an index that contains a history of searches.

2. You want to target **one index** and send it multiple queries,
   where, for example, each query contains **different settings or filters**,
   or the **query itself is slightly adjusted**.
   Use the `stopIfNotEnoughMatches` strategy to stop the search early.

<Info>
  When using the method `multiQueries`, the request isn't tied to any specific index.
  As a result, when retrieving logs for a specific index, `multiQueries` logs won't be retrieved.
</Info>

## Examples

### Multiple queries

<CodeGroup>
  ```cs C# theme={"system"}
  // Perform three queries in a single API call:
  //  First query targets index `categories`
  //  Second and third queries target index `products`
  var indexQueries = new List<MultipleQueries>
  {
      new MultipleQueries
      {
        IndexName = "categories",
        Params = new Query(myQueryString) { HitsPerPage = 3 }
      },
      new MultipleQueries
      {
        IndexName = "products",
        Params = new Query(myQueryString) { HitsPerPage = 3, Filters = "_tags:promotion" }
      },
      new MultipleQueries
      {
        IndexName = "products",
        Params = new Query(myQueryString) { HitsPerPage = 10 }
      },
  };

  MultipleQueriesRequest request = new MultipleQueriesRequest
  {
      Requests = indexQueries
  };

  var res = client.MultipleQueries<object>(request);

  // Asynchronous
  var res = await client.MultipleQueriesAsync<object>(request);
  ```

  ```go Go theme={"system"}
  // Perform three queries in a single API call:
  //  First query targets the `categories` index
  //  Second and third queries target the `products` index
  queries := []search.IndexedQuery{
    search.NewIndexedQuery("categories", opt.Query("computer"), opt.HitsPerPage(3)),
    search.NewIndexedQuery("products", opt.Query("computer"), opt.HitsPerPage(3), opt.Filters("_tags:promotion")),
    search.NewIndexedQuery("products", opt.Query("computer"), opt.HitsPerPage(10)),
  }
  res, err := client.MultipleQueries(queries, "")
  ```

  ```java Java theme={"system"}
  //Sync version

  // Perform three queries in a single API call:
  //  First query targets index `categories`
  //  Second and third queries target index `products`

  List<MultipleQueries> queries = Arrays.asList(
      new MultipleQueries("categories", 
        new Query(myQueryString)
        .setHitsPerPage(3)),
      new MultipleQueries("products", 
        new Query(myQueryString)
        .setHitsPerPage(3)
        .setFilters("_tags:promotion")),
      new MultipleQueries("products", 
        new Query(myQueryString)
        .setHitsPerPage(10))
    );

  MultipleQueriesResponse<Object> search = 
      client.multipleQueries(new MultipleQueriesRequest(queries), Contact.class);

  //Async version
  CompletableFuture<MultipleQueriesResponse<Object>> search = 
      client.multipleQueriesAsync(queries, Contact.class);
  ```

  ```js JavaScript theme={"system"}
  const queries = [{
    indexName: 'categories',
    query: 'search in categories index',
    params: {
      hitsPerPage: 3
    }
  }, {
    indexName: 'products',
    query: 'first search in products',
    params: {
      hitsPerPage: 3,
      filters: '_tags:promotion'
    }
  }, {
    indexName: 'products',
    query: 'another search in products',
    params: {
      hitsPerPage: 10
    }
  }];

  // Perform three queries in a single API call:
  //  First query targets index `categories`
  //  Second and third queries target index `products`
  client.multipleQueries(queries).then(({ results }) => {
    console.log(results);
  });
  ```

  ```kotlin Kotlin theme={"system"}
  val queries = listOf(
      IndexQuery(
          IndexName("categories"),
          Query(query = "query string", hitsPerPage = 3)
      ),
      IndexQuery(
          IndexName("products"),
          Query(query = "query string", hitsPerPage = 3, filters = "_tags:promotion")
      ),
      IndexQuery(
          IndexName("products"),
          Query(query = "query string", hitsPerPage = 10)
      )
  )

  client.multipleQueries(queries)
  ```

  ```php PHP theme={"system"}
  // Perform three queries in a single API call:
  //  First query targets index `categories`
  //  Second and third queries target index `products`

  $queries = [
    [
      'indexName' => 'categories',
      'query' => $myQueryString,
      'hitsPerPage' => 3
    ],
    [
      'indexName' => 'products',
      'query' => $myQueryString,
      'hitsPerPage' => 3,
      'facetFilters' => 'promotion'
    ],
    [
      'indexName' => 'products',
      'query' => $myQueryString,
      'hitsPerPage' => 10
    ]
  ];

  $results = $client->multipleQueries($queries);

  var_dump($results['results']);
  ```

  ```python Python theme={"system"}
  # Perform three queries in a single API call:
  # First query targets index `categories`
  # Second and third queries target index `products`
  results = client.multiple_queries([
      {'indexName': 'categories', 'query': myQueryString, 'hitsPerPage': 3},
      {'indexName': 'products', 'query': myQueryString, 'filters': '_tags:promotion'},
      {'indexName': 'products', 'query': myQueryString, 'hitsPerPage': 3},
  ])

  print(results['results'])
  ```

  ```ruby Ruby theme={"system"}
  # Perform three queries in a single API call:
  # First query targets index `categories`
  # Second and third queries target index `products`
  res = client.multiple_queries([
    { indexName: 'categories', query: my_query_string, hitsPerPage: 3 },
    { indexName: 'products', query: my_query_string, filters: '_tags:promotion' },
    { indexName: 'products', query: my_query_string, hitsPerPage: 10 }
  ])

  puts res['results']
  ```

  ```scala Scala theme={"system"}
  // Perform three queries in a single API call:
  //  First query targets index `categories`
  //  Second and third queries target index `products`

  client.execute {
    multiQueries(
      search into "categories" query Query(
        query = myQueryString,
        hitsPerPage = Some(3)
      ),
      search into "products" query Query(
        query = myQueryString,
        hitsPerPage = Some(3),
        filters = Some("_tags:promotion")
      ),
      search into "products" query Query(
        query = myQueryString,
        hitsPerPage = Some(10)
      )
    ) strategy MultiQueries.Strategy.stopIfEnoughMatches
  }
  ```

  ```swift Swift theme={"system"}
  // Perform three queries in a single API call:
  //    First query target index `categories`
  //    Second and third queries target index `products`
  let queries: [IndexedQuery] = [
    .init(indexName: "categories", query: Query("electronics").set(\.hitsPerPage, to: 3)),
    .init(indexName: "products", query: Query("iPhone").set(\.hitsPerPage, to: 3).set(\.filters, to: "_tags:promotions")),
    .init(indexName: "products", query: Query("Galaxy").set(\.hitsPerPage, to: 10)),
  ]

  client.multipleQueries(queries: queries) { result in
    if case .success(let response) = result {
      print("Response: \(response)")
    }
  }
  ```
</CodeGroup>

### Multiple queries and send extra HTTP headers

<CodeGroup>
  ```cs C# theme={"system"}
  // Perform three queries in a single API call:
  //  First query targets index `categories`
  //  Second and third queries target index `products`
  var indexQueries = new List<MultipleQueries>
  {
      new MultipleQueries
      {
        IndexName = "categories",
        Params = new Query(myQueryString) { HitsPerPage = 3 }
      },
      new MultipleQueries
      {
        IndexName = "products",
        Params = new Query(myQueryString) { HitsPerPage = 3, Filters = "_tags:promotion" }
      },
      new MultipleQueries
      {
        IndexName = "products",
        Params = new Query(myQueryString) { HitsPerPage = 10 }
      },
  };

  var requestOptions = new RequestOptions
  {
      Headers = new Dictionary<string,string>{ { "X-Forwarded-For", "94.228.178.246" } }
  };

  MultipleQueriesRequest request = new MultipleQueriesRequest
  {
      Requests = indexQueries
  };

  var res = client.MultipleQueries<object>(request, requestOptions);

  // Asynchronous
  var res = await client.MultipleQueriesAsync<object>(request, requestOptions);
  ```

  ```go Go theme={"system"}
  // Perform three queries in a single API call:
  //  First query targets the `categories` index
  //  Second and third queries target the `products` index
  queries := []search.IndexedQuery{
  	search.NewIndexedQuery("categories", opt.Query("computer"), opt.HitsPerPage(3)),
  	search.NewIndexedQuery("products", opt.Query("computer"), opt.HitsPerPage(3), opt.Filters("_tags:promotion")),
  	search.NewIndexedQuery("products", opt.Query("computer"), opt.HitsPerPage(10)),
  }

  extraHeaders := opt.ExtraHeaders(map[string]string{
    "X-Forwarded-For": "94.228.178.246",
  })
  res, err := client.MultipleQueries(queries, "", extraHeaders)
  ```

  ```java Java theme={"system"}
  //Sync version

  // Perform three queries in a single API call:
  //  First query targets index `categories`
  //  Second and third queries target index `products`

  List<IndexQuery> queries = Arrays.asList(
     new IndexQuery(
       "categories",
       new Query(myQueryString).setHitsPerPage(3)
     ),
     new IndexQuery(
       "products",
       new Query(myQueryString).setHitsPerPage(3).setFilters("_tags:promotion")
     ),
     new IndexQuery(
       "products",
       new Query(myQueryString).setHitsPerPage(10)
     )
  );

  MultiQueriesResult search = client.multipleQueries(
    queries,
    Contact.class,
    new RequestOptions().addExtraHeader("X-Forwarded-For", "94.228.178.246")
  );



  //Async version

  // Perform three queries in a single API call:
  //  First query targets index `categories`
  //  Second and third queries target index `products`

  List<IndexQuery> queries = Arrays.asList(
    new IndexQuery(
     "categories",
     new Query(myQueryString).setHitsPerPage(3)
    ),
    new IndexQuery(
     "products",
     new Query(myQueryString).setHitsPerPage(3).setFilters("_tags:promotion")
    ),
    new IndexQuery(
     "products",
     new Query(myQueryString).setHitsPerPage(10)
    )
  );

  CompletableFuture<MultiQueriesResult> search = client.multipleQueries(
    queries,
    Contact.class,
    new RequestOptions().addExtraHeader("X-Forwarded-For", "94.228.178.246")
  );
  ```

  ```js JavaScript theme={"system"}
  const queries = [/* queries */];

  client.multipleQueries(queries, {
    headers: {
      "X-Forwarded-For": "94.228.178.246"
    }
  }).then(({ results }) => {
    console.log(results);
  });
  ```

  ```kotlin Kotlin theme={"system"}
  val queries = listOf(
      IndexQuery(
          IndexName("categories"),
          Query(query = "query string", hitsPerPage = 3)
      ),
      IndexQuery(
          IndexName("products"),
          Query(query = "query string", hitsPerPage = 3, filters = "_tags:promotion")
      ),
      IndexQuery(
          IndexName("products"),
          Query(query = "query string", hitsPerPage = 10)
      )
  )
  val requestOptions = requestOptions {
      header("X-Forwarded-For", "94.228.178.246")
  }

  client.multipleQueries(queries, requestOptions = requestOptions)
  ```

  ```php PHP theme={"system"}
  $queries = [/* queries */];

  $results = $client->multipleQueries($queries, [
    'X-Forwarded-For' => '94.228.178.246'
  ]);

  var_dump($results['results']);
  ```

  ```python Python theme={"system"}

  # Perform three queries in a single API call:
  # First query targets index `categories`
  # Second and third queries target index `products`
  results = client.multiple_queries(
      [
          {'indexName': 'categories', 'query': my_query_string, 'hitsPerPage': 3},
          {'indexName': 'products', 'query': my_query_string, 'filters': '_tags:promotion'},
          {'indexName': 'products', 'query': my_query_string, 'hitsPerPage': 10}
      ],
      {
          'X-Forwarded-For': '94.228.178.246'
      }
  )

  print(results['results'])
  ```

  ```ruby Ruby theme={"system"}
  queries = [
    { index_name: 'categories', query: my_query_string, hitsPerPage: 3 },
    { index_name: 'products', query: my_query_string, filters: '_tags:promotion' },
  ]

  res = client.multiple_queries(queries, {
    headers: {
      'X-Forwarded-For': '94.228.178.246'
    }
  })

  puts res['results']
  ```

  ```scala Scala theme={"system"}
  // Perform three queries in a single API call:
  //  First query targets index `categories`
  //  Second and third queries target index `products`

  client.execute {
    multiQueries(
      search into "categories" query Query(
        query = myQueryString,
        hitsPerPage = Some(3)
      ),
      search into "products" query Query(
        query = myQueryString,
        hitsPerPage = Some(3),
        filters = Some("_tags:promotion")
      ),
      search into "products" query Query(
        query = myQueryString,
        hitsPerPage = Some(10)
      )
    ) strategy MultiQueries.Strategy.stopIfEnoughMatches options RequestOptions(
      extraHeaders = Some(Map("X-Forwarded-For" => "94.228.178.246"))
    )
  }
  ```

  ```swift Swift theme={"system"}
  // Perform three queries in a single API call:
  //    First query target index `categories`
  //    Second and third queries target index `products`
  let queries: [IndexedQuery] = [
    .init(indexName: "categories", query: Query("electronics").set(\.hitsPerPage, to: 3)),
    .init(indexName: "products", query: Query("iPhone").set(\.hitsPerPage, to: 3).set(\.filters, to: "_tags:promotions")),
    .init(indexName: "products", query: Query("Galaxy").set(\.hitsPerPage, to: 10)),
  ]

  var requestOptions = RequestOptions()
  requestOptions.headers["X-Forwarded-For"] = "94.228.178.246"
  client.multipleQueries(queries: queries, requestOptions: requestOptions) { result in
    if case .success(let response) = result {
      print("Response: \(response)")
    }
  }
  ```
</CodeGroup>

## Parameters

<ParamField body="queries" type="object[]" required>
  A list of [queries](#param-query-object) to execute.

  <Expandable>
    <ParamField body="indexName" type="string" required>
      Name of the index to target.
    </ParamField>

    <ParamField body="query" type="string" required>
      The query to search in the index.
    </ParamField>

    <ParamField body="params" type="object">
      A key/value mapping of any [search parameters](/doc/api-reference/search-api-parameters)
    </ParamField>

    <ParamField body="type" type="string" default="default">
      The type of query to perform. Can be either `default` for a regular search, or `facet` for a [facet value search](/doc/libraries/sdk/v1/methods/search-for-facet-values).
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="requestOptions" type="object">
  A mapping of request options to send along with the query.
</ParamField>

<ParamField body="strategy" type="string">
  The *strategy* of the query.

  Can be one of the following values:

  * `none`: Execute the sequence of queries until the end.
    This is recommended when each query is of equal importance, meaning all
    records of all queries need to be returned.

  * `stopIfEnoughMatches`: Execute queries one by one, but stop as soon
    as the cumulated number of hits is at least `hitsPerPage`.
    This is recommended when each query is an alternative,
    and where, if the first returns enough records,
    there is no need to perform the remaining queries.
</ParamField>

## Response

<ResponseField name="results" type="object[]">
  List of #{result} in the order they were submitted, one element for each query.

  **Example:**

  ```jsonc JSON icon=braces theme={"system"}
  {
    "results": [
      {
        [...],
        index: 'indexName'
        processed: true
      },
      [...]
    ]
  }
  ```

  <Expandable>
    <ResponseField name="index" type="string">
      The name of the targeted index.
    </ResponseField>

    <ResponseField name="processed" type="boolean">
      Whether the query was processed.
      Only returned when `strategy` = `stopIfEnoughmatches`.
    </ResponseField>
  </Expandable>
</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"}
{
  "results": [
    {
      "hits": [
        {
          "firstname": "Jimmie",
          "lastname": "Barninger",
          "objectID": "433",
          "_highlightResult": {
            "firstname": {
              "value": "<em>Jimmie</em>",
              "matchLevel": "partial"
            },
            "lastname": {
              "value": "Barninger",
              "matchLevel": "none"
            },
            "company": {
              "value": "California <em>Paint</em> & Wlpaper Str",
              "matchLevel": "partial"
            }
          }
        }
        ],
        "page": 0,
        "nbHits": 1,
        "nbPages": 1,
        "hitsPerPage": 20,
        "processingTimeMS": 1,
        "query": "jimmie paint",
        "params": "query=jimmie+paint&attributesToRetrieve=firstname,lastname&hitsPerPage=50"
        "index": "people"
    },
    {
      "hits": [
        {
          "firstname": "Jimmie",
          "lastname": "Barninger",
          "objectID": "433",
          "_highlightResult": {
            "firstname": {
              "value": "<em>Jimmie</em>",
              "matchLevel": "partial"
            },
            "lastname": {
              "value": "Barninger",
              "matchLevel": "none"
            },
            "company": {
              "value": "California <em>Paint</em> & Wlpaper Str",
              "matchLevel": "partial"
            }
          }
        }
        ],
        "page": 0,
        "nbHits": 1,
        "nbPages": 1,
        "hitsPerPage": 20,
        "processingTimeMS": 1,
        "query": "jimmie paint",
        "params": "query=jimmie+paint&attributesToRetrieve=firstname,lastname&hitsPerPage=50"
        "index": "famous_people"
    }
  ]
}
```
