Prerequisites

  • A Tablestore client is initialized. For more information, see Initialization.
  • A data table is created for which the value of the TimeToLive parameter is set to -1 and the value of the MaxVersions parameter is set to 1.

Parameters

When you create a search index, you must configure the TableName, IndexName, and IndexSchema parameters. You must also configure the FieldSchemas, IndexSetting, and IndexSort parameters in IndexSchema. The following table describes the parameters.
Parameter Description
TableName The name of the data table.
IndexName The name of the search index.
FieldSchemas The list of field schemas. You can configure the following parameters for each field schema:
  • FieldName: This parameter is required and specifies the name of the field in the search index. The value is used as the column name. Type: String.

    A field in a search index can be a primary key column or an attribute column.

  • FieldType: This parameter is required and specifies the type of the field. Use tablestore.FieldType_XXX to set the type. For more information, see Data type mappings.
  • Array: This parameter is optional and specifies whether the value is an array. Type: Boolean.

    If you set this parameter to true, the column stores data as an array. Data written to the column must be a JSON array. Example: ["a","b","c"].

    Nested values are an array. If you set FieldType to Nested, skip this parameter.

  • Index: This parameter is optional and specifies whether to enable indexing for the column. Type: Boolean.

    Default value: true. A value of true indicates that Tablestore indexes the column with an inverted indexing schema or a spatio-temporal indexing schema. A value of false indicates that Tablestore does not enable indexing for the column.

  • Analyzer: This parameter is optional and specifies the type of the analyzer that you want to use. If fieldType is set to Text, you can configure this parameter. Otherwise, the default analyzer type single-word tokenization is used. For more information about tokenization, see Tokenization.
  • EnableSortAndAgg: This parameter is optional and specifies whether to enable sorting and aggregation. Type: Boolean.
    Sorting can be enabled only for fields for which EnableSortAndAgg is set to true. For more information about sorting, see Sorting and pagination.
    Important Fields of the Nested type do not support sorting and aggregation, but subcolumns of fields of the Nested type support sorting and aggregation.
  • Store: This parameter is optional and specifies whether to store the value of the field in the search index. Type: Boolean.

    If you set store to true, you can read the value of the field from the search index without querying the data table. This improves query performance.

  • dateFormats: This parameter is optional and specifies the format of dates. Type: String. This parameter is required when fieldType is set to Date. For more information, see Types of date data.
IndexSetting The settings of the search index, including RoutingFields.

RoutingFields: This parameter is optional and specifies custom routing fields. You can specify some primary key columns as routing fields. Tablestore distributes data that is written to a search index across different partitions based on the specified routing fields. The data whose routing field values are the same is distributed to the same partition.

IndexSort The presorting settings for the search index, including Sorters. If no value is specified for the indexSort parameter, field values are sorted by primary key by default.
Note You can skip the presorting settings for the search indexes that contain the Nested field type.
Sorters: This parameter is required and specifies the presorting method for the search index. PrimaryKeySort and FieldSort are supported. For more information about sorting, see Sorting and pagination.
  • PrimaryKeySort: Data is sorted by primary key. You can configure the following parameter for PrimaryKeySort:

    Order: the sort order. Data can be sorted in ascending or descending order. By default, data is sorted in ascending order.

  • FieldSort: Data is sorted by field value. You can configure the following parameters for FieldSort:

    Only fields for which indexing is enabled and enableSortAndAgg is set to true can be presorted.

    • FieldName: the name of the field that is used to sort data.
    • Order: the sort order. Data can be sorted in ascending or descending order. By default, data is sorted in ascending order.
    • Mode: the sorting method that is used when the field contains multiple values.
TimeToLive This parameter is optional and specifies the retention period of data in the search index. Unit: seconds. Default value: -1.

If the retention period exceeds the TTL value, Tablestore automatically deletes expired data.

The minimum TimeToLive value is 86400, which is equal to one day. A value of -1 indicates that data never expires.

For more information about how to manage the TTL of search indexes, see TTL of search indexes.

Examples

  • Create a search index

    The following sample code shows how to create a search index. The search index contains the col1 and col2 columns. The type of the col1 column is Keyword, and the type of the col2 column is Long.

    func CreateSearchIndex(client *tablestore.TableStoreClient, tableName string, indexName string) {
        request := &tablestore.CreateSearchIndexRequest{}
        request.TableName = "exampletable" // Specify the name of the data table. 
        request.IndexName = "examplesearchindex" // Specify the name of the search index that you want to create. 
    
        schemas := []*tablestore.FieldSchema{}
        field1 := &tablestore.FieldSchema{
            FieldName: proto.String("Col_Keyword"), // Specify the field name by calling the proto.String method. This method is used to request a string pointer. 
            FieldType: tablestore.FieldType_KEYWORD, // Specify the field type. 
            Index:     proto.Bool(true), // Set Index to true. 
            EnableSortAndAgg: proto.Bool(true), // Enable sorting and aggregation. 
        }
        field2 := &tablestore.FieldSchema{
            FieldName: proto.String("Col_Long"),
            FieldType: tablestore.FieldType_LONG,
            Index:     proto.Bool(true),
            EnableSortAndAgg: proto.Bool(true),
        }
        schemas = append(schemas, field1, field2)
    
        request.IndexSchema = &tablestore.IndexSchema{
            FieldSchemas: schemas, // Specify the fields that are included in the search index. 
        }
        resp, err := client.CreateSearchIndex(request) // Call a client to create the search index. 
        if err != nil {
            fmt.Println("error :", err)
            return
        }
        fmt.Println("CreateSearchIndex finished, requestId:", resp.ResponseInfo.RequestId)
    }
  • Create a search index with indexSort specified

    The following sample code shows how to create a search index with IndexSort specified. The search index contains the col1 and col2 columns. The type of the col1 column is Keyword, and the type of the col2 column is Long.

    func createSearchIndex_withIndexSort(client *tablestore.TableStoreClient){
        request := &tablestore.CreateSearchIndexRequest{}
        request.TableName = "exampletable" // Specify the name of the data table. 
        request.IndexName = "examplesearchindex" // Specify the name of the search index that you want to create. 
    
        schemas := []*tablestore.FieldSchema{}
        field1 := &tablestore.FieldSchema{
            FieldName: proto.String("col1"), // Set the field name by calling the proto.String method. This method is used to request a string pointer. 
            FieldType: tablestore.FieldType_KEYWORD, // Specify the field type. 
            Index:     proto.Bool(true), // Set Index to true. 
            EnableSortAndAgg: proto.Bool(true), // Enable sorting and aggregation. 
        }
        field2 := &tablestore.FieldSchema{
            FieldName: proto.String("col2"),
            FieldType: tablestore.FieldType_LONG,
            Index:     proto.Bool(true),
            EnableSortAndAgg: proto.Bool(true),
        }
    
        schemas = append(schemas, field1, field2)
        request.IndexSchema = &tablestore.IndexSchema{
            FieldSchemas: schemas, // Specify the fields that are included in the search index. 
            IndexSort: &search. Sort{ // Specify the index pre-sorting settings. The values in the col2 column are sorted in ascending order, and the values in the col1 column are sorted in descending order. 
                Sorters: []search.Sorter{
                    &search.FieldSort{
                        FieldName: "col2",
                        Order:     search.SortOrder_ASC.Enum(),
                    },
                    &search.FieldSort{
                        FieldName: "col1",
                        Order:     search.SortOrder_DESC.Enum(),
                    },
                },
            },
        }
        resp, err := client.CreateSearchIndex(request) // Call a client to create the search index. 
        if err != nil {
            fmt.Println("error :", err)
            return
        }
        fmt.Println("CreateSearchIndex finished, requestId:", resp.ResponseInfo.RequestId)
    }
  • Create a search index with the TTL specified
    Important Make sure that updates to the data table are prohibited.
    func createIndexWithTTL(client *tablestore.TableStoreClient) {
        request := &tablestore.CreateSearchIndexRequest{}
        request.TableName = "TableName"
        request.IndexName = "IndexName"
        // In this example, other parameters are not configured. Configure other parameters based on your business requirements. 
        request.TimeToLive = proto.Int32(3600 * 24 * 7) // Set the TTL of the search index to 7 days. 
        resp, err := client.CreateSearchIndex(request)
        if err != nil {
           fmt.Println("error :", err)
           return
       }
        fmt.Println("createIndexWithTTL finished, requestId:", resp.ResponseInfo.RequestId)
    }