Android

Search

Search an index - searchAsync

To perform a search, you only need to initialize the index and perform a call to the search function.

The search query allows only to retrieve 1000 hits. If you need to retrieve more than 1000 hits (e.g. for SEO), you can use Backup / Export an index.

Index index = client.initIndex("contacts");
Query query = new Query("query string")
    .setAttributesToRetrieve(Arrays.asList("firstname", "lastname"))
    .setNbHitsPerPage(50);
index.searchAsync(query, new CompletionHandler() {
    @Override
    public void requestCompleted(JSONObject content, AlgoliaException error) {
        // [...]
    }
});

Search Response Format

Sample

The server response will look like:

{
  "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"
}

Fields

  • hits (array): The hits returned by the search, sorted according to the ranking formula.

    Hits are made of the JSON objects that you stored in the index; therefore, they are mostly schema-less. However, Algolia does enrich them with a few additional fields:

    • _highlightResult (object, optional): Highlighted attributes. Note: Only returned when attributesToHighlight is non-empty.

      • ${attribute_name} (object): Highlighting for one attribute.

        • value (string): Markup text with occurrences highlighted. The tags used for highlighting are specified via highlightPreTag and highlightPostTag.

        • matchLevel (string, enum) = {none | partial | full}: Indicates how well the attribute matched the search query.

        • matchedWords (array): List of words from the query that matched the object.

        • fullyHighlighted (boolean): Whether the entire attribute value is highlighted.

    • _snippetResult (object, optional): Snippeted attributes. Note: Only returned when attributesToSnippet is non-empty.

      • ${attribute_name} (object): Snippeting for the corresponding attribute.

        • value (string): Markup text with occurrences highlighted and optional ellipsis indicators. The tags used for highlighting are specified via highlightPreTag and highlightPostTag. The text used to indicate ellipsis is specified via snippetEllipsisText.

        • matchLevel (string, enum) = {none | partial | full}: Indicates how well the attribute matched the search query.

    • _rankingInfo (object, optional): Ranking information. Note: Only returned when getRankingInfo is true.

      • 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 numerical value. Conceptually, it’s what the position of the object would be in the list of all objects sorted by custom ranking. Corresponds to the custom criterion in the ranking formula.

      • 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 computed the geo distance, in meters. All distances will be floored to a multiple of this precision.

      • nbExactWords (integer): Number of exactly matched words. If alternativeAsExact is set, it may include plurals and/or synonyms.

      • 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 (object): Geo location that matched the query. Note: Only returned for a geo search.

        • lat (float): Latitude of the matched location.

        • lng (float): Longitude of the matched location.

        • distance (integer): Distance between the matched location and the search location (in meters). Caution: Contrary to geoDistance, this value is not divided by the geo precision.

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

  • nbHits (integer): Number of hits that the search query matched.

  • page (integer): Index of the current page (zero-based). See the page search parameter. Note: Not returned if you use offset/length for pagination.

  • hitsPerPage (integer): Maximum number of hits returned per page. See the hitsPerPage search parameter. Note: Not returned if you use offset/length for pagination.

  • nbPages (integer): Number of pages corresponding to the number of hits. Basically, ceil(nbHits / hitsPerPage). Note: Not returned if you use offset/length for pagination.

  • processingTimeMS (integer): Time that the server took to process the request, in milliseconds. Note: This does not include network time.

  • exhaustiveNbHits (boolean): Whether the nbHits is exhaustive (true) or approximate (false). Note: An approximation is done when the query takes more than 50ms to be processed (this can happen when doing complex filters on millions on records).

  • query (string): An echo of the query text. See the query search parameter.

  • queryAfterRemoval (string, optional): Note: Only returned when removeWordsIfNoResults is set to lastWords or firstWords. 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.

  • params (string, URL-encoded): An echo of all search parameters.

  • message (string, optional): Used to return warnings about the query.

  • aroundLatLng (string, optional): Note: Only returned when aroundLatLngViaIP is set. 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.

  • automaticRadius (integer, optional): Note: Only returned for geo queries without an explicitly specified radius (see aroundRadius). The automatically computed radius. Warning: for legacy reasons, this parameter is a string and not an integer.

When getRankingInfo is set to true, the following additional fields are returned:

  • 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.)

  • 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).

  • timeoutCounts (boolean) - DEPRECATED: Please use exhaustiveFacetsCount in remplacement.

  • timeoutHits (boolean) - DEPRECATED: Please use exhaustiveFacetsCount in remplacement.

… and ranking information is also added to each of the hits (see above).

When facets is non-empty, the following additional fields are returned:

  • facets (object): Maps each facet name to the corresponding facet counts:

    • ${facet_name} (object): Facet counts for the corresponding facet name:

      • ${facet_value} (integer): Count for this facet value.
  • facets_stats (object, optional): Note: Only returned when at least one of the returned facets contains numerical values. 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.

  • exhaustiveFacetsCount (boolean): Whether the counts of the facet values are exhaustive (true) or approximate (false). Note: In some conditions, when a large number of results are matching, the facet counts may not always be exhaustive.

Search Parameters

Here is the list of parameters you can use with the search method (search scope): Parameters that can also be used in a setSettings also have the indexing scope

query
search

The text to search for in the index.

Attributes

attributesToRetrieve
settings search

List of object attributes you want to retrieve.

restrictSearchableAttributes
search

List of attributes to be considered for textual search.

Filtering / Faceting

filters
search

Filter the query with numeric, facet and/or tag filters.

facets
search

Facets to retrieve.

maxValuesPerFacet
settings search

Maximum number of facet values returned for each facet.

facetFilters
search

Filter hits by facet value.

facetingAfterDistinct
search

Force faceting to be applied after de-duplication.

Highlighting / Snippeting

attributesToHighlight
settings search

List of attributes to highlight.

attributesToSnippet
settings search

List of attributes to snippet, with an optional maximum number of words to snippet.

highlightPreTag
settings search

String inserted before highlighted parts in highlight and snippet results.

highlightPostTag
settings search

String inserted after highlighted parts in highlight and snippet results.

snippetEllipsisText
settings search

String used as an ellipsis indicator when a snippet is truncated.

restrictHighlightAndSnippetArrays
settings search

Restrict arrays in highlight and snippet results to items that matched the query.

Pagination

page
search

Number of the page to retrieve.

hitsPerPage
settings search

Maximum number of hits per page.

offset
search

Offset of the first hit to return (zero-based).

length
search

Maximum number of hits to return. (1000 is the maximum)

Typos

minWordSizefor1Typo
settings search

Minimum number of characters a word in the query string must contain to accept matches with one typo.

minWordSizefor2Typos
settings search

Minimum number of characters a word in the query string must contain to accept matches with two typos.

typoTolerance
settings search

Controls whether typo tolerance is enabled and how it is applied:

allowTyposOnNumericTokens
settings search

Whether to allow typos on numbers (“numeric tokens”) in the query string.

ignorePlurals
settings search

Consider singular and plurals forms a match without typo.

disableTypoToleranceOnAttributes
settings search

List of attributes on which you want to disable typo tolerance

aroundLatLng
search

Search for entries around a given location.

aroundLatLngViaIP
search

Search for entries around a given location automatically computed from the requester’s IP address.

aroundRadius
search

Maximum radius for geo search (in meters).

aroundPrecision
search

Precision of geo search (in meters).

minimumAroundRadius
search

Minimum radius (in meters) used for a geo search when aroundRadius is not set.

insideBoundingBox
search

Search inside a rectangular area (in geo coordinates).

insidePolygon
search

Search inside a polygon (in geo coordinates).

Query Strategy

queryType
search settings

Controls if and how query words are interpreted as prefixes.

removeWordsIfNoResults
settings search

Selects a strategy to remove words from the query when it doesn’t match any hits.

advancedSyntax
settings search

Enables the advanced query syntax.

optionalWords
settings search

List of words that should be considered as optional when found in the query.

removeStopWords
settings search

Remove stop words from the query before executing it.

disableExactOnAttributes
settings search

List of attributes on which you want to disable computation of the exact ranking criterion

exactOnSingleWordQuery
settings search

Controls how the exact ranking criterion is computed when the query contains only one word.

alternativesAsExact
setting search

List of alternatives that should be considered an exact match by the exact ranking criterion.

Advanced

distinct
settings search

Controls de-duplication of results.

getRankingInfo
search

Enables detailed ranking information.

numericFilters
search

Filter hits based on values of numeric attributes.

tagFilters
search

Filter hits by tags.

analytics
search

Whether the current query will be taken into account in the Analytics.

analyticsTags
search

List of tags to apply to the query in the Analytics.

synonyms
search

Whether to take into account synonyms defined for the targeted index.

replaceSynonymsInHighlight
settings search

Whether to replace words matched via synonym expansion by the matched synonym in highlight and snippet results.

minProximity
settings search

Precision of the proximity ranking criterion.

responseFields
settings search

Choose which fields the response will contain. Applies to search and browse queries.

maxFacetHits
settings search

Maximum number of facet hits to return during a search for facet values.

percentileComputation
search

Whether to include the query in processing time percentile computation.

Search multiple indices - multipleQueriesAsync

You can send multiple queries with a single API call using a batch of queries:

// perform 3 queries in a single API call:
//  - 1st query targets index `categories`
//  - 2nd and 3rd queries target index `products`

List<IndexQuery> queries = new ArrayList<>();

queries.add(new IndexQuery("categories", new Query(myQueryString).setHitsPerPage(3)));
queries.add(new IndexQuery("products", new Query(myQueryString).setHitsPerPage(3).set("filters", "_tags:promotion"));
queries.add(new IndexQuery("products", new Query(myQueryString).setHitsPerPage(10)));

client.multipleQueriesAsync(queries, new CompletionHandler() {
    @Override
    public void requestCompleted(JSONObject content, AlgoliaException error) {
        // [...]
    }
});

You can specify a strategy parameter to optimize your multiple queries:

  • none: Execute the sequence of queries until the end.
  • stopIfEnoughMatches: Execute the sequence of queries until the number of hits is reached by the sum of hits.

Response

The resulting JSON contains the following fields:

  • results (array): The results for each request, in the order they were submitted. The contents are the same as in Search an index. Each result also includes the following additional fields:

    • index (string): The name of the targeted index.
    • processed (boolean, optional): Note: Only returned when strategy is stopIfEnoughmatches. Whether the query was processed.

Get Objects - getObjectsAsync

You can easily retrieve an object using its objectID and optionally specify a comma separated list of attributes you want:

// Retrieves all attributes
index.getObjectAsync("myID", new CompletionHandler() {
    @Override
    public void requestCompleted(JSONObject content, AlgoliaException error) {
        // [...]
    }
});
// Retrieves only the firstname attribute
index.getObjectAsync("myID", Arrays.asList("firstname"), new CompletionHandler() {
    @Override
    public void requestCompleted(JSONObject content, AlgoliaException error) {
        // [...]
    }
});

You can also retrieve a set of objects:

index.getObjectsAsync(Arrays.asList("myID1", "myID2"), new CompletionHandler() {
    @Override
    public void requestCompleted(JSONObject content, AlgoliaException error) {
        // [...]
    }
});

Search for facet values - searchForFacetValues

When there are many facet values for a given facet, it may be useful to search within them. For example, you may have dozens of ‘brands’ for a given index of ‘clothes’. Rather than displaying all of the brands, it is often best to only display the most popular and add a search input to allow the user to search for the brand that they are looking for.

Searching on facet values is different than a regular search because you are searching only on facet values, not objects.

The results are sorted by decreasing count. By default, maximum 10 results are returned. This can be adjusted via maxFacetHits. No pagination is possible.

The facet search can optionally take regular search query parameters. In that case, it will return only facet values that both:

  1. match the facet query
  2. are contained in objects matching the regular search query.

For a facet to be searchable, it must have been declared with the searchable() modifier in the attributesForFaceting index setting.

Example

Let’s imagine we have objects similar to this one:

{
    "name": "iPhone 7 Plus",
    "brand": "Apple",
    "category": [
        "Mobile phones",
        "Electronics"
    ]
}

Then:

# Search the values of the "category" facet matching "phone".
index.searchForFacetValues("category", "phone", new CompletionHandler() {
    @Override
    public void requestCompleted(JSONObject content, AlgoliaException error) {
        // [...]
    }
});

… could return:

{
    "facetHits": [
        {
            "value": "Mobile phones",
            "highlighted": "Mobile <em>phone</em>s",
            "count": 507
        },
        {
            "value": "Phone cases",
            "highlighted": "<em>Phone</em> cases",
            "count": 63
        }
    ]
}

Let’s filter with an additional, regular search query:

// Search the "category" facet for values matching "phone" in records
// having "Apple" in their "brand" facet.
Query query = new Query().setFilters("brand:Apple");
index.searchForFacetValues("category", "phone", query, new CompletionHandler() {
    @Override
    public void requestCompleted(JSONObject content, AlgoliaException error) {
        // [...]
    }
});

… could return:

{
    "facetHits": [
        {
            "value": "Mobile phones",
            "highlighted": "Mobile <em>phone</em>s",
            "count": 41
        }
    ]
}

Building your search implementation in Javascript? Look at the Filtering & Faceting guide to see how to use Search for facet values from the front-end.

Search cache

You can easily cache the results of the search queries by enabling the search cache. The results will be cached during a defined amount of time (default: 2 min). There is no pre-caching mechanism but you can simulate it by making a preemptive search query.

By default, the cache is disabled.

// Enable the search cache with default settings.
index.enableSearchCache();

… or:

// Enable the search cache with a TTL of 5 minutes and maximum 20 requests in the cache.
index.enableSearchCache(300, 20);

Did you find this page helpful?

We're always looking for advice to help improve our documentation! Please let us know what's working (or what's not!) - we're constantly iterating thanks to the feedback we receive.

Send us your suggestions!