Constant score query
Use a constant score query in the Tablestore SDK for Go to assign the same relevance score to all matched rows.
Prerequisites
Install the Tablestore Go SDK and initialize a client.
Description
A constant score query uses the query specified by Filter as a filter. It checks only whether a row matches and does not calculate BM25 or other relevance scores for the subquery. When a constant score query is the top-level query, every matched row has a relevance score of 1.0. When it is a subquery, this score is combined with the scores of other subqueries that participate in scoring.
func (client *tablestore.TableStoreClient) Search(request *tablestore.SearchRequest) (*tablestore.SearchResponse, error)
The following example wraps a match query in a constant score query to query rows whose title field contains go and sorts the results by relevance score. Because the constant score query is the top-level query, the score read from SearchHits[].Score is 1.0 for every hit.
tableName := "example_table"
indexName := "example_index"
query := &search.ConstScoreQuery{
Filter: &search.MatchQuery{
FieldName: "title",
Text: "go",
},
}
searchQuery := search.NewSearchQuery().
SetQuery(query).
SetLimit(10).
SetGetTotalCount(true).
SetSort(&search.Sort{Sorters: []search.Sorter{search.NewScoreSort()}})
response, err := client.Search(&tablestore.SearchRequest{
TableName: tableName,
IndexName: indexName,
SearchQuery: searchQuery,
ColumnsToGet: &tablestore.ColumnsToGet{
ReturnAllFromIndex: true,
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(response.TotalCount)
for _, hit := range response.SearchHits {
fmt.Println(hit.Row, *hit.Score)
}
Parameters
Query request
request is of the tablestore.SearchRequest type and 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) |
search.SearchQuery |
The query condition and common query configurations. |
|
ColumnsToGet (optional) |
*tablestore.ColumnsToGet |
The return-column configuration. If this parameter is omitted, only primary key columns are returned. |
|
RoutingValues (optional) |
[]*tablestore.PrimaryKey |
Primary key values for custom routing fields. Omit this parameter if custom routing is not configured. |
|
TimeoutMs (optional) |
*int32 |
The request timeout period in milliseconds. |
Query configuration
Create a query configuration by calling search.NewSearchQuery() and configure it by using the following methods.
|
Name |
Type |
Description |
|
SetQuery (required) |
search.Query |
Specifies the query condition. |
|
SetOffset (optional) |
int32 |
Specifies the start position. Default value: 0. For offset-based pagination, Offset + Limit cannot exceed 100,000. |
|
SetLimit (optional) |
int32 |
Specifies the maximum number of rows to return. Default value: 10. Maximum value: 100. A value of 0 returns no rows. |
|
SetHighlight (optional) |
*search.Highlight |
Configures summaries and highlighting for Text fields. For more information, see Summary and highlighting. |
|
SetCollapse (optional) |
*search.Collapse |
Collapses query results. For more information, see Collapse query results. |
|
SetSort (optional) |
*search.Sort |
Specifies the result sort order. For more information, see Sort and paginate results. |
|
SetGetTotalCount (optional) |
bool |
Specifies whether to count all matched rows. Default value: false. |
|
SetToken (optional) |
[]byte |
Specifies the NextToken value returned by the previous response. This method clears Sort because the token contains the previous-page sort conditions. Do not specify Offset when you use token-based pagination. |
|
SetSearchFilter (optional) |
*search.SearchFilter |
Applies a post-query filter. For more information, see Use post-query filters. |
|
Aggregation (optional) |
...search.Aggregation |
Configures aggregations. For more information, see Aggregation. |
|
GroupBy (optional) |
...search.GroupBy |
Configures grouping. For more information, see Aggregation. |
Query condition
The query is of the search.ConstScoreQuery type and contains the following parameter.
|
Name |
Type |
Description |
|
Filter (required) |
search.Query |
The subquery used to filter rows. |
Columns to return
request.ColumnsToGet is of the tablestore.ColumnsToGet type and contains the following parameters.
|
Name |
Type |
Description |
|
Columns (optional) |
[]string |
The attribute columns to return. This parameter takes effect only when ReturnAll and ReturnAllFromIndex are both false. |
|
ReturnAll (optional) |
bool |
Specifies whether to return all attribute columns in the data table. Default value: false. |
|
ReturnAllFromIndex (optional) |
bool |
Specifies whether to return all indexed attribute columns. Default value: false. Do not set this parameter and ReturnAll to true at the same time. |
Response
The Search method returns a tablestore.SearchResponse value. The following table describes the core business fields.
|
Name |
Type |
Description |
|
TotalCount |
int64 |
The total number of matched rows. The value depends on SetGetTotalCount. |
|
Rows |
[]*tablestore.Row |
The rows returned by the current query. The number does not exceed the value specified by SetLimit. |
|
SearchHits |
[]*tablestore.SearchHit |
The search hits. Read this field when you use highlighting, nested inner hits, or relevance scores. |
|
SearchHits[].Score |
*float64 |
The relevance score. If ScoreSort is used and the constant score query is the top-level query, the value is 1.0. If the constant score query is a subquery, the final score also includes the scores of other subqueries that participate in scoring. |
|
NextToken |
[]byte |
The token for the next page. If the value is not empty, pass it to the next query. |
|
IsAllSuccess |
bool |
Indicates whether all index partitions were queried. If the value is false, partial results are returned and TotalCount may be less than the actual number of matched rows. |
|
AggregationResults |
search.AggregationResults |
The aggregation results. |
|
GroupByResults |
search.GroupByResults |
The grouping results. |
Examples
Combine with a Boolean query
Add a constant score query to BoolQuery.MustQueries to make the subquery contribute the fixed relevance score 1.0 to each hit. Other subqueries calculate relevance scores based on their own rules. The final score is the sum of the subquery scores.
query := &search.BoolQuery{
MustQueries: []search.Query{
&search.ConstScoreQuery{
Filter: &search.MatchQuery{
FieldName: "title",
Text: "go",
},
},
&search.MatchQuery{
FieldName: "title",
Text: "guide",
},
},
}
searchQuery := search.NewSearchQuery().
SetQuery(query).
SetLimit(10).
SetSort(&search.Sort{Sorters: []search.Sorter{search.NewScoreSort()}})
response, err := client.Search(&tablestore.SearchRequest{
TableName: "example_table",
IndexName: "example_index",
SearchQuery: searchQuery,
})
if err != nil {
log.Fatal(err)
}
for _, hit := range response.SearchHits {
fmt.Println(hit.Row, *hit.Score)
}
Use with parallel scan
If parallel scan does not need to sort rows by relevance score, wrap the filter condition in a constant score query so that the scan checks only whether rows match and does not calculate BM25 or other relevance scores for the subquery. The following example sets a constant score query as the ScanQuery condition for one worker. For the complete worker and pagination workflow, see Parallel scan.
query := &search.ConstScoreQuery{
Filter: &search.MatchQuery{
FieldName: "title",
Text: "go",
},
}
splits, err := client.ComputeSplits(
(&tablestore.ComputeSplitsRequest{}).
SetTableName("example_table").
SetSearchIndexSplitsOptions(tablestore.SearchIndexSplitsOptions{
IndexName: "example_index",
}),
)
if err != nil {
log.Fatal(err)
}
scanQuery := search.NewScanQuery().
SetQuery(query).
SetLimit(1000).
SetMaxParallel(splits.SplitsSize).
SetCurrentParallelID(0)
request := (&tablestore.ParallelScanRequest{}).
SetTableName("example_table").
SetIndexName("example_index").
SetScanQuery(scanQuery).
SetSessionId(splits.SessionId).
SetColumnsToGet(&tablestore.ColumnsToGet{
ReturnAllFromIndex: true,
})
response, err := client.ParallelScan(request)
if err != nil {
log.Fatal(err)
}
fmt.Println(response.Rows)