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

      • 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 are exhaustive (true) or approximate (false). Note: In some conditions when distinct is greater than 1 and an empty query without refinement is sent, 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

Search

Attributes

Filtering / Faceting

Highlighting / Snippeting

Pagination

Typos

Geo-Search

Query Strategy

Advanced

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
        }
    ]
}

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);