API client / Methods / Search
Required API Key: any key with the search ACL
Method signature
$index->search(string query)

$index->search(string query, [
  // any searchParameters
  // any requestOptions
])

We released a new version of the PHP API client in public beta. Read the beta documentation for more information.

We released a new version of the JavaScript API client in public beta. Read the beta documentation for more information.

We released a new version of the Java API client in public beta. Read the beta documentation for more information.

You’re currently reading the JavaScript API client v4 documentation. Check the migration guide to learn how to upgrade from v3 to v4. You can still access the v3 documentation.

You’re currently reading the Ruby API client v2 documentation. Check the migration guide to learn how to upgrade from v1 to v2. You can still access the v1 documentation.

About this method

Method used for querying an index.

The search query only allows for the retrieval of up to 1000 hits. If you need to retrieve more than 1000 hits (e.g. for SEO), you can either leverage the Browse index method or increase the paginationLimitedTo parameter.

Examples

Read the Algolia CLI documentation for more information.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$index = $client->initIndex('contacts');

// Search for "query string" in the index "contacts"
$res = $index->search('query string');

// Perform the same search but only retrieve 50 results
// Return only the attributes "firstname" and "lastname"
$res = $index->search('query string', [
  'attributesToRetrieve' => [
    'firstname',
    'lastname',
  ],
  'hitsPerPage' => 50
]);

Search and send an extra header

1
2
3
4
5
6
$index = $client->initIndex('your_index_name');

$res = $index->search('query string', [
  'hitsPerPage' => 10, // search parameter
  'X-Algolia-UserToken' => 'user123' // extra header
]);

Parameters

Parameter Description
query
type: string
Required

The query used to search. Accepts every character, and every character entered will be used in the search. There’s a hard limit of 512 characters per query. If a search query is longer, the API will return an error.

An empty query can be used to fetch all records.

searchParameters
type: key/value mapping
default: No search parameters
Optional

A mapping of search parameters to send along with the query.

requestOptions
type: key/value mapping
default: No request options
Optional

A mapping of requestOptions to send along with the query. In addition to sending extra HTTP headers or setting timeouts, you can use requestOptions to specify search parameters when using this method.

Response

This section shows the JSON response returned by the API. Each API client encapsulates this response inside objects specific to the programming language, so that the actual response might be different. You can view the response by using the getLogs method. Don’t rely on the order of attributes in the response, as JSON doesn’t guarantee the ordering of keys in objects.

JSON format

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
{
  "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"
}
Field Description
hits
list

The hits returned by the search.

Hits are ordered according to the ranking or sorting of the index being queried.

Hits are made of the schemaless JSON objects that you stored in the index.

However, Algolia does enrich them with a few additional fields, such as _highlightResult, _snippetResult, _rankingInfo, and _distinctSeqID.

hits: [
  {
    field1 : "",
    field2 : "",
    [...],

    _highlightResult: {
      [...]
    },
    _snippetResult: {
      [...]
    },
    _rankingInfo: {
      [...]
    },
    _distinctSeqID:
  },
  [...]
]
nbHits
integer

The number of hits matched by the query.

page
integer

Index of the current page (zero-based). See the page search parameter.

Not returned if you use offset/length for pagination.

hitsPerPage
integer

The maximum number of hits returned per page. See the hitsPerPage search parameter.

Not returned if you use offset & length for pagination.

userData
array

Array of userData object.

Only returned if at least one Rule containing a custom userData consequence was applied.

nbPages
integer

The number of returned pages. Calculation is based on the total number of hits (nbHits) divided by the number of hits per page (hitsPerPage), rounded up to the nearest integer.

Not returned if you use offset & length for pagination.

nbSortedHits
integer

The number of hits selected and sorted by the relevant sort algorithm.

Only returned when searching on a virtual replica.

processingTimeMS
integer

Time the server took to process the search request, in milliseconds. This doesn’t include network time.

serverTimeMS
integer

Time the server took to process the complete request, in milliseconds. This does not include network time.

processingTimingsMS
key/value mapping

List of processing steps and their times, in milliseconds. You can use this list to investigate performance issues.

This parameter is experimental. Fields may change without further notice and may be different for different Algolia servers. The list of steps is not exhaustive.

exhaustive
object

Whether certain properties of the search response are calculated exhaustive (exact) or approximated.

List of fields:

  • facetsCount: Whether the facet count is exhaustive (true) or approximate (false). See the related discussion.
  • facetValues: The value is false if not all facet values are retrieved.
  • nbHits: Whether the nbHits is exhaustive (true) or approximate (false). When the query takes more than 50ms to be processed, the engine makes an approximation. This can happen when using complex filters on millions of records, when typo-tolerance was not exhaustive, or when enough hits have been retrieved (for example, after the engine finds 10,000 exact matches). nbHits is reported as non-exhaustive whenever an approximation is made, even if the approximation didn’t, in the end, impact the exhaustivity of the query.
  • rulesMatch: Rules matching exhaustivity. The value is false if rules were enable for this query, and could not be fully processed due a timeout. This is generally caused by the number of alternatives (such as typos) which is too large.
  • typo: Whether the typo search was exhaustive (true) or approximate (false). An approximation is done when the typo search query part takes more than 10% of the query budget (ie. 5ms by default) to be processed (this can happen when a lot of typo alternatives exist for the query). This field will not be included when typo-tolerance is entirely disabled.
exhaustiveNbHits
boolean

Deprecated. See the nbHits field of the exhaustive object in the response.

exhaustiveTypo
boolean

Deprecated. See the typo field of the exhaustive object in the response.

exhaustiveFacetsCount
boolean

Deprecated. See the facetsCount field of the exhaustive object in the response.

query
string

An echo of the query text. See the query search parameter.

queryAfterRemoval
string

A markup text indicating which parts of the original query have been removed in order to retrieve a non-empty result set.

The removed parts are surrounded by <em> tags.

Only returned when removeWordsIfNoResults is set to lastWords or firstWords.

params
string

A url-encoded string of all search parameters.

message
string
optional

Used to return warnings about the query.

aroundLatLng
string

The computed geo location. Warning: for legacy reasons, this parameter is a string and not an object. Format: ${lat},${lng}, where the latitude and longitude are expressed as decimal floating point numbers.

Only returned when aroundLatLngViaIP or aroundLatLng is set.

automaticRadius
string

The automatically computed radius. For legacy reasons, this parameter is a string and not an integer.

Only returned for geo queries without an explicitly specified radius (see aroundRadius).

serverUsed
string

Actual host name of the server that processed the request. Our DNS supports automatic failover and load balancing, so this may differ from the host name used in the request.

Returned only if getRankingInfo is set to true.

indexUsed
string

Index name used for the query. In the case of an A/B test, the targeted index isn’t always the index used by the query.

Returned only if getRankingInfo is set to true.

abTestID
integer

If a search encounters an index that is being A/B tested, abTestID reports the ongoing A/B test ID.

Returned only if getRankingInfo is set to true.

abTestVariantID
integer

If a search encounters an index that is being A/B tested, abTestVariantID reports the variant ID of the index used (note, this is the ID not the name). The variant ID is the position in the array of variants (starting at 1).

For example, abTestVariantID=1 is variant A (the main index), abTestVariantID=2 is variant B (the replica you chose when creating the A/B test, or the queries with the changed query parameters if the A/B test is based on query parameters).

Returned only if getRankingInfo is set to true.

parsedQuery
string

The query string that will be searched, after normalization. Normalization includes removing stop words (if removeStopWords is enabled), and transforming portions of the query string into phrase queries (see advancedSyntax).

Returned only if getRankingInfo is set to true.

timeoutCounts DEPRECATED
boolean

Use the facetsCount field of the exhaustive object in the response.

Returned only if getRankingInfo is set to true.

timeoutHits DEPRECATED
boolean

Please use exhaustiveHitsCount instead.

Returned only if getRankingInfo is set to true.

facets
key/value mapping

A mapping of each facet name to the corresponding facet counts.

${facet_name} => ${facet_value}

Returned only if facets is non-empty.

facets_stats
key/value mapping

Statistics for numerical facets.

${facet_name} (object): The statistics for a given facet:

  • min (integer | float): The minimum value in the result set.
  • max (integer | float): The maximum value in the result set.
  • avg (integer | float): The average facet value in the result set.
  • sum (integer | float): The sum of all values in the result set.

Regardless of the number of requested facet values (as per maxValuesPerFacet), statistics are always computed on at most 1,000 distinct values (starting with the most frequent ones). If there are more than 1,000 distinct values, statistics may therefore not be 100% accurate.

Returned only if facets is non-empty and at least one of the returned facets contains numerical values.

queryID
string

Unique identifier of the search query, to be sent in Insights methods. This identifier links events back to the search query it represents.

Returned only if clickAnalytics is true.

hits ➔ _highlightResult

Highlighted attributes. Each attribute contains an object or an array of objects (if the attribute in question is an array) with the following attributes. Only returned when attributesToHighlight is non-empty.

{
  hits: [
    {
      "${attribute_name}": "Jimmie",
      "_highlightResult": {
        "${attribute_name}": {
          "value": "<em>Jimmie</em>",
          "matchLevel": "partial",
          "matchedWords": ["Jimmie"],
          "fullyHighlighted": true
      }
    }
  ]
}
Field Description
value
string

Markup text with occurrences highlighted. The tags used for highlighting are specified via highlightPreTag and highlightPostTag.

matchLevel
string

Indicates how well the attribute matched the search query. Can be:

  • none (0)
  • partial (some)
  • full (all)

The matching relates to the words in the query string not in the searched text of the records.

Removed stop words are not taken into account: if you match everything except stop words (and removeStopWords is enabled), the query is considered a full match.

This has nothing to do with prefixes, plurals, synonyms, or typos. No matter how “accurately” a word matches, if it matches, it counts as one.

matchedWords
list

List of words from the query that matched the object.

fullyHighlighted
boolean

Whether the entire attribute value is highlighted.

hits ➔ _snippetResult

Snippeted attributes. Only returned when attributesToSnippet is non-empty.

{
  hits: [
    {
      "${attribute_name}": "Jimmie is working remote for 2 weeks",
      "_snippetResult": {
        "${attribute_name}": {
          "value": "<em>Jimmie</em> is working remote ...",
          "matchLevel": "partial"
        }
    }
  ]
}
Field Description
value
string

Markup text with occurrences highlighted. The tags used for highlighting are specified via highlightPreTag and highlightPostTag. The text used to indicate ellipsis is specified via snippetEllipsisText.

matchLevel
string

Indicates how well the attribute matched the search query. Can be: none or partial or full. See highlightResult matchLevel for more details.

hits ➔ _rankingInfo

Ranking information. Only returned when getRankingInfo is true.

Field Description
promoted
boolean

Present and set to true if a Rule promoted the hit.

nbTypos
integer

Number of typos encountered when matching the record. Corresponds to the typos ranking criterion in the ranking formula

firstMatchedWord
integer

Position of the most important matched attribute in the attributes to index list. Corresponds to the attribute ranking criterion in the ranking formula.

proximityDistance
integer

When the query contains more than one word, the sum of the distances between matched words (in meters). Corresponds to the proximity criterion in the ranking formula.

userScore
integer

Custom ranking for the object, expressed as a single integer value. This field is internal to Algolia and shouldn’t be relied upon.

geoDistance
integer

Distance between the geo location in the search query and the best matching geo location in the record, divided by the geo precision (in meters).

geoPrecision
integer

Precision used when computing the geo distance, in meters. All distances will be floored to a multiple of this precision.

nbExactWords
integer

Number of exactly matched words. If alternativesAsExact is set, it may include plurals, synonyms, or both.

words
integer

Number of matched words, including prefixes and typos.

filters
integer

This field is reserved for advanced usage. It will be zero in most cases.

matchedGeoLocation
key/value mapping

Geo location that matched the query.

  • lat: Latitude of the matched location.
  • lng: Longitude of the matched location.
  • distance: Distance between the matched location and the search location (in meters). Contrary to geoDistance, this value is not divided by the geo precision.

Only returned if aroundRadius is used.

{
  "lat": 51.148056
  "lng": -0.190278,
  "distance": 35
}

hits ➔ _distinctSeqID

Field Description
_distinctSeqID
integer

When two consecutive results have the same value for the attribute used for “distinct”, this field is used to distinguish between them. Only returned when distinct is non-zero.

Did you find this page helpful?