AppSearchSession

public interface AppSearchSession extends Closeable


Provides a connection to a single AppSearch database.

An AppSearchSession instance provides access to database operations such as setting a schema, adding documents, and searching.

Instances of this interface are usually obtained from a storage implementation, e.g. LocalStorage.createSearchSessionAsync() or PlatformStorage.createSearchSessionAsync().

All implementations of this interface must be thread safe.

Summary

Public methods

abstract void

Closes the AppSearchSession to persist all schema and document updates, additions, and deletes to disk.

abstract @NonNull ListenableFuture<AppSearchBatchResult<StringGenericDocument>>

Gets GenericDocument objects by document IDs in a namespace from the AppSearchSession database.

abstract @NonNull Features

Returns the Features to check for the availability of certain features for this session.

abstract @NonNull ListenableFuture<Set<String>>

Retrieves the set of all namespaces in the current database with at least one document.

abstract @NonNull ListenableFuture<GetSchemaResponse>

Retrieves the schema most recently successfully provided to setSchemaAsync.

abstract @NonNull ListenableFuture<StorageInfo>

Gets the storage info for this AppSearchSession database.

abstract @NonNull ListenableFuture<AppSearchBatchResult<StringVoid>>

Indexes documents into the AppSearchSession database.

abstract @NonNull ListenableFuture<AppSearchBatchResult<StringVoid>>

Removes GenericDocument objects by document IDs in a namespace from the AppSearchSession database.

abstract @NonNull ListenableFuture<Void>
removeAsync(
    @NonNull String queryExpression,
    @NonNull SearchSpec searchSpec
)

Removes GenericDocuments from the index by Query.

abstract @NonNull ListenableFuture<Void>

Reports usage of a particular document by namespace and ID.

abstract @NonNull ListenableFuture<Void>

Flush all schema and document updates, additions, and deletes to disk if possible.

abstract @NonNull SearchResults
search(@NonNull String queryExpression, @NonNull SearchSpec searchSpec)

Retrieves documents from the open AppSearchSession that match a given query string and type of search provided.

abstract @NonNull ListenableFuture<List<SearchSuggestionResult>>
searchSuggestionAsync(
    @NonNull String suggestionQueryExpression,
    @NonNull SearchSuggestionSpec searchSuggestionSpec
)

Retrieves suggested Strings that could be used as queryExpression in search API.

abstract @NonNull ListenableFuture<SetSchemaResponse>

Sets the schema that represents the organizational structure of data within the AppSearch database.

Public methods

close

Added in 1.1.0-alpha04
abstract void close()

Closes the AppSearchSession to persist all schema and document updates, additions, and deletes to disk.

getByDocumentIdAsync

Added in 1.1.0-alpha04
abstract @NonNull ListenableFuture<AppSearchBatchResult<StringGenericDocument>> getByDocumentIdAsync(@NonNull GetByDocumentIdRequest request)

Gets GenericDocument objects by document IDs in a namespace from the AppSearchSession database.

Parameters
@NonNull GetByDocumentIdRequest request

a request containing a namespace and IDs to get documents for.

Returns
@NonNull ListenableFuture<AppSearchBatchResult<StringGenericDocument>>

A ListenableFuture which resolves to an AppSearchBatchResult. The keys of the AppSearchBatchResult represent the input document IDs from the GetByDocumentIdRequest object. The values are either the corresponding GenericDocument object for the ID on success, or an AppSearchResult object on failure. For example, if an ID is not found, the value for that ID will be set to an AppSearchResult object with result code: RESULT_NOT_FOUND.

getFeatures

Added in 1.1.0-alpha04
abstract @NonNull Features getFeatures()

Returns the Features to check for the availability of certain features for this session.

getNamespacesAsync

Added in 1.1.0-alpha04
abstract @NonNull ListenableFuture<Set<String>> getNamespacesAsync()

Retrieves the set of all namespaces in the current database with at least one document.

Returns
@NonNull ListenableFuture<Set<String>>

The pending result of performing this operation.

getSchemaAsync

Added in 1.1.0-alpha04
abstract @NonNull ListenableFuture<GetSchemaResponsegetSchemaAsync()

Retrieves the schema most recently successfully provided to setSchemaAsync.

Returns
@NonNull ListenableFuture<GetSchemaResponse>

The pending GetSchemaResponse of performing this operation.

getStorageInfoAsync

Added in 1.1.0-alpha04
abstract @NonNull ListenableFuture<StorageInfogetStorageInfoAsync()

Gets the storage info for this AppSearchSession database.

This may take time proportional to the number of documents and may be inefficient to call repeatedly.

Returns
@NonNull ListenableFuture<StorageInfo>

a ListenableFuture which resolves to a StorageInfo object.

putAsync

Added in 1.1.0-alpha04
abstract @NonNull ListenableFuture<AppSearchBatchResult<StringVoid>> putAsync(@NonNull PutDocumentsRequest request)

Indexes documents into the AppSearchSession database.

Each GenericDocument object must have a schemaType field set to an AppSearchSchema type that has been previously registered by calling the setSchemaAsync method.

Parameters
@NonNull PutDocumentsRequest request

containing documents to be indexed.

Returns
@NonNull ListenableFuture<AppSearchBatchResult<StringVoid>>

a ListenableFuture which resolves to an AppSearchBatchResult. The keys of the returned AppSearchBatchResult are the IDs of the input documents. The values are either null if the corresponding document was successfully indexed, or a failed AppSearchResult otherwise.

removeAsync

Added in 1.1.0-alpha04
abstract @NonNull ListenableFuture<AppSearchBatchResult<StringVoid>> removeAsync(@NonNull RemoveByDocumentIdRequest request)

Removes GenericDocument objects by document IDs in a namespace from the AppSearchSession database.

Removed documents will no longer be surfaced by search or getByDocumentIdAsync calls.

Once the database crosses the document count or byte usage threshold, removed documents will be deleted from disk.

Parameters
@NonNull RemoveByDocumentIdRequest request

RemoveByDocumentIdRequest with IDs in a namespace to remove from the index.

Returns
@NonNull ListenableFuture<AppSearchBatchResult<StringVoid>>

a ListenableFuture which resolves to an AppSearchBatchResult. The keys of the AppSearchBatchResult represent the input IDs from the RemoveByDocumentIdRequest object. The values are either null on success, or a failed AppSearchResult otherwise. IDs that are not found will return a failed AppSearchResult with a result code of RESULT_NOT_FOUND.

removeAsync

Added in 1.1.0-alpha04
abstract @NonNull ListenableFuture<VoidremoveAsync(
    @NonNull String queryExpression,
    @NonNull SearchSpec searchSpec
)

Removes GenericDocuments from the index by Query. Documents will be removed if they match the queryExpression in given namespaces and schemaTypes which is set via addFilterNamespaces and addFilterSchemas.

An empty queryExpression matches all documents.

An empty set of namespaces or schemaTypes matches all namespaces or schemaTypes in the current database.

Parameters
@NonNull String queryExpression

Query String to search.

@NonNull SearchSpec searchSpec

Spec containing schemaTypes, namespaces and query expression indicates how document will be removed. All specific about how to scoring, ordering, snippeting and resulting will be ignored.

Returns
@NonNull ListenableFuture<Void>

The pending result of performing this operation.

Throws
java.lang.IllegalArgumentException

if the SearchSpec contains a JoinSpec. JoinSpec lets you join docs that are not owned by the caller, so the semantics of failures from this method would be complex.

reportUsageAsync

Added in 1.1.0-alpha04
abstract @NonNull ListenableFuture<VoidreportUsageAsync(@NonNull ReportUsageRequest request)

Reports usage of a particular document by namespace and ID.

A usage report represents an event in which a user interacted with or viewed a document.

For each call to reportUsageAsync, AppSearch updates usage count and usage recency * metrics for that particular document. These metrics are used for ordering search results by the RANKING_STRATEGY_USAGE_COUNT and RANKING_STRATEGY_USAGE_LAST_USED_TIMESTAMP ranking strategies.

Reporting usage of a document is optional.

Parameters
@NonNull ReportUsageRequest request

The usage reporting request.

Returns
@NonNull ListenableFuture<Void>

The pending result of performing this operation which resolves to null on success.

requestFlushAsync

Added in 1.1.0-alpha04
abstract @NonNull ListenableFuture<VoidrequestFlushAsync()

Flush all schema and document updates, additions, and deletes to disk if possible.

The request is not guaranteed to be handled and may be ignored by some implementations of AppSearchSession.

Returns
@NonNull ListenableFuture<Void>

The pending result of performing this operation. androidx.appsearch.exceptions.AppSearchException with RESULT_INTERNAL_ERROR will be set to the future if we hit error when save to disk.

search

Added in 1.1.0-alpha04
abstract @NonNull SearchResults search(@NonNull String queryExpression, @NonNull SearchSpec searchSpec)

Retrieves documents from the open AppSearchSession that match a given query string and type of search provided.

Query strings can be empty, contain one term with no operators, or contain multiple terms and operators.

For query strings that are empty, all documents that match the SearchSpec will be returned.

For query strings with a single term and no operators, documents that match the provided query string and SearchSpec will be returned.

The following operators are supported:

  • AND (implicit)

    AND is an operator that matches documents that contain all provided terms.

    NOTE: A space between terms is treated as an "AND" operator. Explicitly including "AND" in a query string will treat "AND" as a term, returning documents that also contain "AND".

    Example: "apple AND banana" matches documents that contain the terms "apple", "and", "banana".

    Example: "apple banana" matches documents that contain both "apple" and "banana".

    Example: "apple banana cherry" matches documents that contain "apple", "banana", and "cherry".

  • OR

    OR is an operator that matches documents that contain any provided term.

    Example: "apple OR banana" matches documents that contain either "apple" or "banana".

    Example: "apple OR banana OR cherry" matches documents that contain any of "apple", "banana", or "cherry".

  • Exclusion (-)

    Exclusion (-) is an operator that matches documents that do not contain the provided term.

    Example: "-apple" matches documents that do not contain "apple".

  • Grouped Terms

    For queries that require multiple operators and terms, terms can be grouped into subqueries. Subqueries are contained within an open "(" and close ")" parenthesis.

    Example: "(donut OR bagel) (coffee OR tea)" matches documents that contain either "donut" or "bagel" and either "coffee" or "tea".

  • Property Restricts

    For queries that require a term to match a specific AppSearchSchema property of a document, a ":" must be included between the property name and the term.

    Example: "subject:important" matches documents that contain the term "important" in the "subject" property.

The above description covers the query operators that are supported on all versions of AppSearch. Additional operators and their required features are described below.

LIST_FILTER_QUERY_LANGUAGE: This feature covers the expansion of the query language to conform to the definition of the list filters language (https://aip .dev/160). This includes:

  • addition of explicit 'AND' and 'NOT' operators
  • property restricts are allowed with groupings (ex. "prop:(a OR b)")
  • addition of custom functions to control matching

The newly added custom functions covered by this feature are:

  • createList(String...)
  • search(String, List)
  • propertyDefined(String)

createList takes a variable number of strings and returns a list of strings. It is for use with search.

search takes a query string that will be parsed according to the supported query language and an optional list of strings that specify the properties to be restricted to. This exists as a convenience for multiple property restricts. So, for example, the query `(subject:foo OR body:foo) (subject:bar OR body:bar)` could be rewritten as `search("foo bar", createList("subject", "bar"))`.

propertyDefined takes a string specifying the property of interest and matches all documents of any type that defines the specified property (ex. `propertyDefined("sender.name")`). Note that propertyDefined will match so long as the document's type defines the specified property. It does NOT require that the document actually hold any values for this property.

NUMERIC_SEARCH: This feature covers numeric search expressions. In the query language, the values of properties that have INDEXING_TYPE_RANGE set can be matched with a numeric search expression (the property, a supported comparator and an integer value). Supported comparators are <, <=, ==, >= and >.

Ex. `price <10` will match all documents that has a numeric value in its price property that is less than 10.

VERBATIM_SEARCH: This feature covers the verbatim string operator (quotation marks).

Ex. `"foo/bar" OR baz` will ensure that 'foo/bar' is treated as a single 'verbatim' token.

The availability of each of these features can be checked by calling isFeatureSupported with the desired feature.

Additional search specifications, such as filtering by AppSearchSchema type or adding projection, can be set by calling the corresponding SearchSpec.Builder setter.

This method is lightweight. The heavy work will be done in getNextPageAsync.

Parameters
@NonNull String queryExpression

query string to search.

@NonNull SearchSpec searchSpec

spec for setting document filters, adding projection, setting term match type, etc.

Returns
@NonNull SearchResults

a SearchResults object for retrieved matched documents.

searchSuggestionAsync

Added in 1.1.0-alpha04
abstract @NonNull ListenableFuture<List<SearchSuggestionResult>> searchSuggestionAsync(
    @NonNull String suggestionQueryExpression,
    @NonNull SearchSuggestionSpec searchSuggestionSpec
)

Retrieves suggested Strings that could be used as queryExpression in search API.

The suggestionQueryExpression can contain one term with no operators, or contain multiple terms and operators. Operators will be considered as a normal term. Please see the operator examples below. The suggestionQueryExpression must end with a valid term, the suggestions are generated based on the last term. If the input suggestionQueryExpression doesn't have a valid token, AppSearch will return an empty result list. Please see the invalid examples below.

Example: if there are following documents with content stored in AppSearch.

  • document1: "term1"
  • document2: "term1 term2"
  • document3: "term1 term2 term3"
  • document4: "org"

Search suggestions with the single term suggestionQueryExpression "t", the suggested results are:

  • "term1" - Use it to be queryExpression in search could get 3 SearchResults, which contains document 1, 2 and 3.
  • "term2" - Use it to be queryExpression in search could get 2 SearchResults, which contains document 2 and 3.
  • "term3" - Use it to be queryExpression in search could get 1 SearchResult, which contains document 3.

Search suggestions with the multiple term suggestionQueryExpression "org t", the suggested result will be "org term1" - The last token is completed by the suggested String.

Operators in search are supported.

NOTE: Exclusion and Grouped Terms in the last term is not supported.

example: "apple -f": This Api will throw an androidx.appsearch.exceptions.AppSearchException with RESULT_INVALID_ARGUMENT.

example: "apple (f)": This Api will return an empty results.

Invalid example: All these input suggestionQueryExpression don't have a valid last token, AppSearch will return an empty result list.

  • "" - Empty suggestionQueryExpression.
  • "(f)" - Ending in a closed brackets.
  • "f:" - Ending in an operator.
  • "f " - Ending in trailing space.
Parameters
@NonNull String suggestionQueryExpression

the non empty query string to search suggestions

@NonNull SearchSuggestionSpec searchSuggestionSpec

spec for setting document filters

Returns
@NonNull ListenableFuture<List<SearchSuggestionResult>>

The pending result of performing this operation which resolves to a List of SearchSuggestionResult on success. The returned suggestion Strings are ordered by the number of SearchResult you could get by using that suggestion in search.

See also
search

setSchemaAsync

Added in 1.1.0-alpha04
abstract @NonNull ListenableFuture<SetSchemaResponsesetSchemaAsync(@NonNull SetSchemaRequest request)

Sets the schema that represents the organizational structure of data within the AppSearch database.

Upon creating an AppSearchSession, setSchemaAsync should be called. If the schema needs to be updated, or it has not been previously set, then the provided schema will be saved and persisted to disk. Otherwise, setSchemaAsync is handled efficiently as a no-op call.

Parameters
@NonNull SetSchemaRequest request

the schema to set or update the AppSearch database to.