You can specify IndexSort when you create a search index and specify a sorting method when you query data. You can use limit and offset or tokens for pagination.

Index presorting

By default, data in a search index is sorted based on the presorting settings that are specified by the IndexSort parameter. When you use a search index to query data, the presorting settings that are specified by the IndexSort parameter determine the default order in which the matched data is returned.

When you create a search index, you can specify presorting settings by configuring the IndexSort parameter. If you do not specify presorting settings by configuring the IndexSort parameter, data in the search index is sorted by primary key. If you do not specify presorting settings by configuring the IndexSort parameter and use the search index to query data, the matched data is returned in the order of the primary key by default.

Notice
  • You can specify PrimaryKeySort or FieldSort as the presorting method for a search index. PrimaryKeySort indicates sorting by primary key and FieldSort indicates sorting by field value.
  • Search indexes that contain fields of the Nested type do not support index presorting.

Specify a sorting method

Sorting can be enabled only for fields for which enableSortAndAgg is set to true.

You can specify a sorting method for each query. Search index-based queries support the following sorting methods. You can also specify multiple sorting methods based on different priorities.

  • ScoreSort
    You can use ScoreSort to sort the query results based on the BM25-based keyword relevance score. ScoreSort is suitable for scenarios such as full-text search.
    Notice You must specify a value for ScoreSort to sort the matched data by keyword relevance score. Otherwise, the matched data is sorted based on the presorting settings that are specified by the IndexSort parameter.
    SearchQuery searchQuery = new SearchQuery();
    searchQuery.setSort(new Sort(Arrays.asList(new ScoreSort())));
  • PrimaryKeySort

    You can use PrimaryKeySort to sort the query results based on the value of the primary key.

    SearchQuery searchQuery = new SearchQuery();
    searchQuery.setSort(new Sort(Arrays.asList(new PrimaryKeySort()))); // Sort the query results in the ascending order. 
    //searchQuery.setSort(new Sort(Arrays.asList(new PrimaryKeySort(SortOrder.DESC)))); // Sort the query results in the descending order. 
  • FieldSort

    You can use FieldSort to sort the query results based on the values of a specified column.

    SearchQuery searchQuery = new SearchQuery();
    searchQuery.setSort(new Sort(Arrays.asList(new FieldSort("col", SortOrder.ASC))));

    You can also sort values in two columns in specified orders to determine the order in which the matched data is returned.

    SearchQuery searchQuery = new SearchQuery();
    searchQuery.setSort(new Sort(Arrays.asList(
        new FieldSort("col1", SortOrder.ASC), new FieldSort("col2", SortOrder.ASC))));
  • GeoDistanceSort

    You can use GeoDistanceSort to sort the query results by geographical location.

    SearchQuery searchQuery = new SearchQuery();
    // Sort the results based on the distance from the value in the GEOPOINT geo column to the coordinate pairs (0, 0). 
    Sort.Sorter sorter = new GeoDistanceSort("geo", Arrays.asList("0, 0"));
    searchQuery.setSort(new Sort(Arrays.asList(sorter)));

Specify a pagination method

You can use the limit and offset parameters or use tokens to paginate the returned rows.

  • Use the limit and offset parameters
    When the total number of returned rows to obtain is smaller than 50,000, you can configure the limit and offset parameters to paginate the rows. The sum of the limit and offset parameter values cannot exceed 50,000. The maximum value of the limit parameter is 100.

    If you use the limit and offset parameters to paginate the rows but do not specify values, the default values are used. The default value of the limit parameter is 10. The default value of the offset parameter is 0.

    SearchQuery searchQuery = new SearchQuery();
    searchQuery.setQuery(new MatchAllQuery());
    searchQuery.setLimit(100);
    searchQuery.setOffset(100);
  • Use a token

    We recommend that you use a token for deep pagination because this method has no limits on the pagination depth.

    If Tablestore cannot read all data that meets the query conditions, Tablestore returns nextToken. You can use nextToken to continue to read the subsequent data.

    By default, you can only page backward when you use a token. However, you can cache and use the previous token to page forward because a token is valid during the query.

    Notice If you need to persist nextToken or transfer nextToken to the frontend page, you can use Base64 to encode nextToken into a string. Tokens are not strings. If you use new String(nextToken) to encode a token into a string, information about the token is lost.

    When you use a token for pagination, the sorting method is the same as the method that is used in the previous request. Therefore, you cannot specify the sorting method if you use a token. You cannot set the offset parameter when a token is used. Data is returned page by page in sequence, which results in a slow query.

    Notice Search indexes that contain fields of the Nested type do not support IndexSort. If you use a search index that contains fields of the Nested type to query data and require pagination, you must specify the sorting method in the query conditions to return data in the specified order. Otherwise, Tablestore does not return nextToken when only part of data that meets the query conditions is returned.
    private static void readMoreRowsWithToken(SyncClient client) {
        SearchQuery searchQuery = new SearchQuery();
        searchQuery.setQuery(new MatchAllQuery());
        searchQuery.setGetTotalCount(true);// Specify that the total number of matched rows is returned. 
    
        SearchRequest searchRequest = new SearchRequest("sampleTable", "sampleSearchIndex", searchQuery);
    
        SearchResponse resp = client.search(searchRequest);
        if (!resp.isAllSuccess()) {
            throw new RuntimeException("not all success");
        }
        List<Row> rows = resp.getRows();
        while (resp.getNextToken()!=null) { // If nextToken is null in the response, all data is read. 
            // Query the nextToken value. 
            byte[] nextToken = resp.getNextToken();
    
            {
                // If you need to persist nextToken or transfer nextToken to the frontend page, you can use Base64 to encode nextToken into a string. 
                // Tokens are not strings. If you use new String(nextToken) to encode a token into a string, information about the token is lost. 
                String tokenAsString = Base64.toBase64String(nextToken);
                // Decode the string into bytes. 
                byte[] tokenAsByte = Base64.fromBase64String(tokenAsString);
            }
    
            // Set the token in this request to the nextToken value in the previous response. 
            searchRequest.getSearchQuery().setToken(nextToken);
            resp = client.search(searchRequest);
            if (!resp.isAllSuccess()) {
                throw new RuntimeException("not all success");
            }
            rows.addAll(resp.getRows());
        }
        System.out.println("RowSize: " + rows.size());
        System.out.println("TotalCount: " + resp.getTotalCount());// Specify that the total number of matched rows instead of the number of returned rows is displayed. 
    }