Create a search index

更新时间: 2026-04-30 16:11:32

Creates one or more search indexes for a data table using the CreateSearchIndex method. When creating a search index, specify the fields to query and optionally configure advanced options such as custom routing keys and pre-sorting.

Prerequisites

Before you begin, make sure that:

  • The Tablestore client is initialized. For more information, see Initialize the Tablestore Client.

  • A data table is created and meets the following conditions. For more information, see Create a data table.

    • The maximum number of versions is set to 1.

    • The time to live (TTL) is set to -1, or the data table has updates disabled.

Field type compatibility

The data type of each field in the search index must match the data type of the corresponding field in the data table.

Parameters

To create a search index, specify the table name (TableName), search index name (IndexName), and index schema (IndexSchema). The IndexSchema contains FieldSchemas (field settings), IndexSetting (index settings), and IndexSort (pre-sorting settings).

Parameter

Description

TableName

The name of the data table.

IndexName

The name of the search index.

FieldSchemas

A list of FieldSchema objects. Each FieldSchema object contains the following parameters:

  • FieldName (Required): The name of the field in the search index, corresponding to a column name. Type: String. The field can be a primary key column or an attribute column.

  • FieldType (Required): The data type of the field. Type: FieldType.XXX.

  • Array (Optional): Specifies whether the field stores array data. Type: Boolean. When set to true, write data in JSON array format, such as ["a","b","c"]. The Nested type is inherently an array—do not set this parameter when FieldType is Nested.

  • Index (Optional): Specifies whether to enable indexing for the field. Type: Boolean. Default: true. When enabled, an inverted index or spatial index is created for the column. Set to false to skip indexing.

  • Analyzer (Optional): The tokenizer type. Applies only when FieldType is Text. Default: single-word tokenization.

  • EnableSortAndAgg (Optional): Specifies whether to enable sorting and aggregation for the field. Type: Boolean. Only fields with this set to true support sorting. The Nested type does not support sorting and aggregation; however, sub-columns within a Nested field do.

  • IsVirtualField (Optional): Specifies whether the field is a virtual column. Type: Boolean. Default: false. Set this parameter only for virtual columns.

  • SourceFieldNames (Optional): The source column names in the data table. Type: String. Required when IsVirtualField is true.

  • DateFormats (Optional): The date formats. Type: String. Required when FieldType is Date. For more information, see Date and time types.

IndexSetting

Index settings. Contains the following parameter:

RoutingFields (Optional): Custom routing fields. Select one or more primary key columns as routing fields. In most cases, one routing field is sufficient—if you set multiple routing keys, the system concatenates their values into a single value. Records with the same routing field values are indexed to the same data partition.

IndexSort

Pre-sorting settings for the index. If not specified, data is sorted by primary key by default. Indexes that contain Nested fields do not support IndexSort.

Sorters (Required): The pre-sorting method. Supports sorting by primary key or by field value. For more information, see Sorting and pagination.

  • PrimaryKeySort: Sorts by primary key. Set the Order parameter to specify ascending or descending order. Default: ascending (DataModel.Search.Sort.SortOrder.ASC).

  • FieldSort: Sorts by field value. Only indexed fields with sorting and aggregation enabled can be used for pre-sorting. Contains the following settings:

    • FieldName: The name of the field to sort by.

    • Order: The sort order. Default: ascending (DataModel.Search.Sort.SortOrder.ASC).

    • Mode: The sort mode when a field contains multiple values.

TimeToLive

Optional. The time-to-live (TTL) of data in the search index, in seconds. Default: -1 (data never expires). Minimum value: 86400 seconds (one day). Expired data is automatically cleaned up when the retention period exceeds the configured TTL.

Examples

Create a search index with default configurations

Create a search index with three fields: Keyword_type_col (Keyword), Long_type_col (Long), and Text_type_col (Text), with sorting and aggregation enabled on the Keyword and Long fields.

/// <summary>
/// Creates a search index with three attribute columns: Keyword_type_col, Long_type_col, and Text_type_col.
/// Field types: Keyword (non-tokenized string), Long (integer), and Text (tokenized string).
/// </summary>
/// <param name="otsClient"></param>
public static void CreateSearchIndex(OTSClient otsClient)
{
    // Set the table name and search index name.
    CreateSearchIndexRequest request = new CreateSearchIndexRequest(TableName, IndexName);
    List<FieldSchema> FieldSchemas = new List<FieldSchema>() {
        new FieldSchema(Keyword_type_col, FieldType.KEYWORD) {
            index = true,            // Enable indexing.
            EnableSortAndAgg = true  // Enable sorting and aggregation.
        },
        new FieldSchema(Long_type_col, FieldType.LONG) { index = true, EnableSortAndAgg = true },
        new FieldSchema(Text_type_col, FieldType.TEXT) { index = true }
    };
    request.IndexSchame = new IndexSchema()
    {
        FieldSchemas = FieldSchemas
    };
    // Create the search index.
    CreateSearchIndexResponse response = otsClient.CreateSearchIndex(request);
    Console.WriteLine("Searchindex is created: " + IndexName);
}

Create a search index and specify IndexSort

Create a search index with three fields: Keyword_type_col (Keyword), Long_type_col (Long), and Text_type_col (Text). Pre-sort results by the Long_type_col field in ascending order.

/// <summary>
/// Creates a search index with three attribute columns: Keyword_type_col, Long_type_col, and Text_type_col.
/// Field types: Keyword (non-tokenized string), Long (integer), and Text (tokenized string).
/// Pre-sorts results by Long_type_col in ascending order.
/// </summary>
/// <param name="otsClient"></param>
public static void CreateSearchIndexWithIndexSort(OTSClient otsClient)
{
    // Set the table name and search index name.
    CreateSearchIndexRequest request = new CreateSearchIndexRequest(TableName, IndexName);
    List<FieldSchema> FieldSchemas = new List<FieldSchema>() {
        new FieldSchema(Keyword_type_col, FieldType.KEYWORD) {
            index = true,
            EnableSortAndAgg = true
        },
        new FieldSchema(Long_type_col, FieldType.LONG) { index = true, EnableSortAndAgg = true },
        new FieldSchema(Text_type_col, FieldType.TEXT) { index = true }
    };
    request.IndexSchame = new IndexSchema()
    {
        FieldSchemas = FieldSchemas,
        // Pre-sort by Long_type_col (ascending). The field must have EnableSortAndAgg enabled.
        IndexSort = new DataModel.Search.Sort.Sort()
        {
            Sorters = new List<DataModel.Search.Sort.ISorter>
            {
                new DataModel.Search.Sort.FieldSort(Long_type_col, DataModel.Search.Sort.SortOrder.ASC)
            }
        }
    };

    CreateSearchIndexResponse response = otsClient.CreateSearchIndex(request);
    Console.WriteLine("Searchindex is created: " + IndexName);
}

Create a search index that contains a date column and a virtual column

Create a search index with five fields: pk0 (Keyword), pk1 (Long), date_col (Date), geo_col (Geo-point), and col0_v1 (Text). The virtual column col0_v1 maps to the source column col0. Results are pre-sorted by pk1 in ascending order.

/// <summary>
/// Creates a search index that includes a Date field and a virtual column.
/// The virtual column col0_v1 maps to the source column col0 in the data table.
/// </summary>
/// <param name="otsClient"></param>
public static void CreateSearchIndex(OTSClient otsClient)
{
    List<FieldSchema> fieldSchemas = new List<FieldSchema> {
        new FieldSchema("pk0", FieldType.KEYWORD)
        {
            index = true,
            EnableSortAndAgg = true
        },

        new FieldSchema("pk1", FieldType.LONG)
        {
            index = true,
            EnableSortAndAgg = true
        },

        new FieldSchema("date_col", FieldType.DATE)
        {
            index = true,
            DateFormats = new List<string>(){
                "yyyy-MM-dd'T'HH:mm:ss.SSSSSS",
                "yyyy-MM-dd'T'HH:mm:ss.SSS"
            }
        },

        new FieldSchema("geo_col", FieldType.GEO_POINT)
        {
            index = true,
            EnableSortAndAgg = true
        },

        new FieldSchema("col0_v1", FieldType.TEXT)
        {
            index = true,
            Analyzer = Analyzer.Split,
            AnalyzerParameter = new SingleWordAnalyzerParameter(true, true),
            IsVirtualField = true,
            SourceFieldNames = new List<string> { "col0" }  // Maps to source column col0.
        },
    };

    CreateSearchIndexRequest request = new CreateSearchIndexRequest(TableName, IndexName);
    request.IndexSchame = new IndexSchema()
    {
        FieldSchemas = fieldSchemas,
        IndexSort = new Sort(new List<ISorter> { new FieldSort("pk1", SortOrder.ASC) })
    };
    request.TimeToLive = -1;  // Data never expires.

    otsClient.CreateSearchIndex(request);
}

FAQ

What's next

上一篇: Manage search indexes 下一篇: List search indexes
阿里云首页 表格存储 相关技术圈