Constant score query

Updated at:

Use constant score queries in Tablestore SDK for Java to wrap a subquery as a filter and return a fixed relevance score of 1.0 for every matching row.

Prerequisites

Install the Tablestore SDK for Java and initialize a client.

Feature description

A constant score query wraps a subquery as a filter. It checks only whether a row matches the subquery and does not calculate the subquery's relevance score based on algorithms such as BM25. Every matching row has a relevance score of 1.0.

Set the query type to ConstScoreQuery and use filter to specify the subquery to wrap. filter supports any Query type.

The following example wraps a match query in a constant score query, queries rows in which the description field contains tablestore, and sorts the rows by relevance score.

String tableName = "example_table";
String indexName = "example_index";

MatchQuery matchQuery = new MatchQuery();
matchQuery.setFieldName("description");
matchQuery.setText("tablestore");

ConstScoreQuery constScoreQuery = new ConstScoreQuery();
constScoreQuery.setFilter(matchQuery);

SearchQuery searchQuery = new SearchQuery();
searchQuery.setQuery(constScoreQuery);
searchQuery.setSort(new Sort(Collections.singletonList(new ScoreSort())));
searchQuery.setLimit(10);
searchQuery.setTrackTotalCount(SearchQuery.TRACK_TOTAL_COUNT);

SearchRequest request = new SearchRequest(tableName, indexName, searchQuery);
SearchRequest.ColumnsToGet columnsToGet = new SearchRequest.ColumnsToGet();
columnsToGet.setReturnAll(true);
request.setColumnsToGet(columnsToGet);

SearchResponse response = client.search(request);
for (SearchHit hit : response.getSearchHits()) {
    System.out.println(hit.getRow());
    System.out.println(hit.getScore());
}

Parameters

Search request

request is a SearchRequest object that contains the following parameters.

Name

Type

Description

tableName (required)

String

The name of the data table.

indexName (required)

String

The name of the search index.

searchQuery (required)

SearchQuery

The query condition and common query settings.

columnsToGet (optional)

SearchRequest.ColumnsToGet

The returned columns. If you omit this parameter, only primary key columns are returned.

timeoutInMillisecond (optional)

int

The request-level query timeout in milliseconds. The default value is -1, which specifies that no separate query timeout is configured.

routingValues (optional)

List<PrimaryKey>

The primary key values that correspond to the custom routing fields. If custom routing is not configured, you do not need to set this parameter.

Query settings

request.searchQuery is a SearchQuery object that contains the following parameters.

Name

Type

Description

query (required)

Query

The query condition. Set this parameter to a ConstScoreQuery object for a constant score query.

offset (optional)

Integer

The start position of this query.

limit (optional)

Integer

The maximum number of rows to return. If you set this parameter to 0, no rows are returned.

highlight (optional)

Highlight

The summary and highlight settings used when the subquery matches a Text field. For more information, see Summary and highlight.

collapse (optional)

Collapse

The result collapse settings used to deduplicate returned rows based on a specified column. For more information, see Collapse (distinct).

sort (optional)

Sort

The sort settings for the returned rows. For more information, see Sorting and pagination.

trackTotalCount (optional)

int

The maximum number of matching rows to count. The default value is TRACK_TOTAL_COUNT_DISABLED, which specifies that matching rows are not counted. Set this parameter to TRACK_TOTAL_COUNT to count all matching rows. A smaller value provides better query performance.

filter (optional)

SearchFilter

The filter applied to the results of query.

aggregationList (optional)

List<Aggregation>

The aggregation settings. For more information, see Aggregations.

groupByList (optional)

List<GroupBy>

The group-by settings. For more information, see Aggregations.

token (optional)

byte[]

The pagination token. Set this parameter to nextToken from the previous response to read the next page. When you set token, the SDK clears sort because the pagination token already contains the sort settings.

Constant score query condition

request.searchQuery.query is a ConstScoreQuery object that contains the following parameter.

Name

Type

Description

filter (required)

Query

The subquery to wrap. This parameter supports any Query type. The query checks only whether a row matches the subquery. Every matching row has a relevance score of 1.0.

Returned columns

request.columnsToGet is a SearchRequest.ColumnsToGet object that contains the following parameters.

Name

Type

Description

columns (optional)

List<String>

The attribute columns to return. Set this parameter only if returnAll and returnAllFromIndex are both false. If you omit this parameter, only primary key columns are returned.

returnAll (optional)

boolean

Specifies whether to return all attribute columns from the data table. The default value is false.

returnAllFromIndex (optional)

boolean

Specifies whether to return all indexed attribute columns. The default value is false. Do not set both returnAll and returnAllFromIndex to true.

Return values

Search response

search returns a SearchResponse object. The following table describes the core fields.

Name

Type

Description

totalCount

long

The number of matching rows. Call getTotalCount() to obtain the value. The returned value depends on the trackTotalCount setting.

rows

List<Row>

The rows returned by this query. Call getRows() to obtain the value. The number of rows does not exceed limit.

searchHits

List<SearchHit>

The query hits. Call getSearchHits() to obtain the value. Read relevance scores and summary and highlight results from this field.

nextToken

byte[]

The next-page token. Call getNextToken() to obtain the value. If the value is not null, set it as token in the next request to continue reading rows.

isAllSuccess

boolean

Indicates whether all index partitions were queried successfully. Call isAllSuccess() to obtain the value. If the value is false, the response contains partial results and totalCount may be less than the actual number of matching rows.

Search hit

response.searchHits[] is a SearchHit object that contains the following core fields.

Name

Type

Description

row

Row

The matching row. Call getRow() to obtain the value.

score

Double

The relevance score. Call getScore() to obtain the value. When you use ScoreSort and a constant score query is the top-level query condition, this field is 1.0 for every matching row. If the constant score query is a subquery, the final score also includes scores from other scoring subqueries.

highlightResultItem

HighlightResultItem

The summary and highlight result. Call getHighlightResultItem() to obtain the value.

Scenario examples

Combine with a Boolean query

Add a constant score query to BoolQuery.mustQueries to make the subquery contribute a fixed relevance score of 1.0 to each matching row. Other subqueries continue to calculate relevance scores based on their own rules. The final score is the sum of the scores of the subqueries.

The following example queries rows in which the category field is book and the description field contains tablestore.

TermQuery categoryQuery = new TermQuery();
categoryQuery.setFieldName("category");
categoryQuery.setTerm(ColumnValue.fromString("book"));

ConstScoreQuery constScoreQuery = new ConstScoreQuery();
constScoreQuery.setFilter(categoryQuery);

MatchQuery descriptionQuery = new MatchQuery();
descriptionQuery.setFieldName("description");
descriptionQuery.setText("tablestore");

BoolQuery boolQuery = new BoolQuery();
boolQuery.setMustQueries(Arrays.asList(constScoreQuery, descriptionQuery));

SearchQuery searchQuery = new SearchQuery();
searchQuery.setQuery(boolQuery);
searchQuery.setSort(new Sort(Collections.singletonList(new ScoreSort())));

SearchRequest request = new SearchRequest(
        "example_table", "example_index", searchQuery);
SearchResponse response = client.search(request);
System.out.println(response.getRows());

For more information about Boolean queries, see Boolean query.

Use in a parallel scan

If a parallel scan does not need to sort rows by relevance score, wrap the query condition in a constant score query. The query then checks only whether a row matches and does not calculate the subquery's relevance score based on algorithms such as BM25.

The following example uses a constant score query to filter rows in which the description field contains tablestore and reads the results from all parallel tasks.

String tableName = "example_table";
String indexName = "example_index";

MatchQuery matchQuery = new MatchQuery();
matchQuery.setFieldName("description");
matchQuery.setText("tablestore");

ConstScoreQuery constScoreQuery = new ConstScoreQuery();
constScoreQuery.setFilter(matchQuery);

ComputeSplitsRequest splitsRequest = new ComputeSplitsRequest();
splitsRequest.setTableName(tableName);
splitsRequest.setSplitsOptions(new SearchIndexSplitsOptions(indexName));
ComputeSplitsResponse splitsResponse = client.computeSplits(splitsRequest);

for (int parallelId = 0;
        parallelId < splitsResponse.getSplitsSize();
        parallelId++) {
    ScanQuery scanQuery = new ScanQuery();
    scanQuery.setQuery(constScoreQuery);
    scanQuery.setLimit(2000);
    scanQuery.setMaxParallel(splitsResponse.getSplitsSize());
    scanQuery.setCurrentParallelId(parallelId);

    ParallelScanRequest request = new ParallelScanRequest();
    request.setTableName(tableName);
    request.setIndexName(indexName);
    request.setScanQuery(scanQuery);
    request.setSessionId(splitsResponse.getSessionId());

    RowIterator iterator = client.createParallelScanIterator(request);
    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }
}

For more information about parallel scans, see Export data in parallel.