Best practices for text vectorization retrieval

Updated at:
Important

This document applies only to traditional instances of OpenSearch Retrieval Engine Edition that were created before June 2024. For instances created after this date, refer to Best practices for text vectorization retrieval (New Version).

Purchase an OpenSearch Retrieval Engine Edition instance

For more information about how to purchase an instance, see Purchase an OpenSearch Retrieval Engine Edition instance.

Configure an instance

The system automatically deploys an empty cluster that matches the number and specifications of your purchased query nodes and data nodes. Before you can search, you must configure a data source, define an index schema, and trigger index rebuilding. To begin, click Configure in the Actions column.

Configure a data source

This example uses a MaxCompute data source. Click Add Data Source and select MaxCompute as the data source type. Set the project, AccessKey ID, AccessKey Secret, Table, and partition key. Optionally, enable Automatic index rebuilding.

After the verification is successful, click OK to add the data source.

Configure the index schema

After you configure the data source, click Next to configure the index schema.

Click Add Index Table to configure an index table. Specify the index table name, select the data source you configured in the previous step, and set the number of data shards. The default value is 1. If you use a MaxCompute data source, the fields from the data source are automatically mapped.

In the Field Settings section, configure the following three required fields. Text vectorization converts text into vectors, which are then used to retrieve data. You can customize the field names.

  1. A primary key field, such as id: The type can be STRING or an integer type. You must select the primary key option for this field.

    Set the field type to INT64. Select attribute field and Display in Search Results. For data compression, keep the default value equal.

  2. A field to store the source text, such as vector_source_text:

    Set the field type to STRING. Select attribute field and Display in Search Results. For data compression, select uniq.

  3. A vector field. If you select Existing Vector Data, leave the advanced configurations for this field empty. To have the system convert text to vectors, apply the following advanced configurations:

    Set the field type to FLOAT. Select multi-value (with the separator as ^]). For data compression, select uniq.

    {
      "vector_model": "ops-text-embedding-000",
      "vector_modal": "text",
      "vector_source_field": "vector_source_text"
    }
    1. vector_model: The vector model. The platform currently supports two models for Chinese and English text conversion.

      1. ops-text-embedding-000: A model for converting short Chinese text to vectors. The dimension is fixed at 768.

      2. ops-text-embedding-en-000: A model for converting short English text to vectors. The dimension is fixed at 768.

    2. vector_modal: The modal type. For text vectors, the value is text.

    3. vector_source_field: The field containing the text to be vectorized. In this example, the field is vector_source_text.

    Important

    Attribute and field content compression

    • You can choose whether to compress an attribute field. By default, compression is disabled. To enable compression, select a compressor such as file_compressor.

    • You can choose whether to compress field content. By default, compression is disabled. The default compression type is uniq for multi-value and STRING fields, and equal for single-value numeric fields.

    • For vector retrieval, you must define fields in a specific order: create the primary key field, the tag field (optional), and then the vector field.

    • The data in the vector_source_text field must not exceed 128 bytes. If the data exceeds this limit, the system truncates it and uses only the first 128 bytes for vector prediction.

    • If you use a MaxCompute data source, the system displays the synchronized fields below the predefined fields after synchronization.

    • The primary key field does not support compression.

    • Enabling field and attribute compression saves storage space but may decrease query performance.

  4. Index settings. The primary key index and vector index are required.

    1. Primary key index: Specify a custom name. Select PRIMARYKEY64 as the index type. For the indexed field, select the field that you configured as the primary key. In this example, the field is id.

    2. Vector index: Specify a custom name. Select CUSTOMIZED as the index type. You can include up to three fields. While a tag field is optional, both the primary key and vector fields are mandatory.

      In the advanced configurations for the vector index, you must set the dimension to 768. This value is fixed. We recommend that you keep the default values for other parameters.

      The default values are: distance_type is SquaredEuclidean, vector_index_type is Qc, enable_rt_build is true, and rt_index_params is {"proxima.oswg.streamer.segment_size":2048}.

  5. Schema example:

    {
      "file_compress": [
        {
          "name": "file_compressor",
          "type": "zstd"
        },
        {
          "name": "no_compressor",
          "type": ""
        }
      ],
      "table_name": "xiaoming001",
      "summarys": {
        "summary_fields": [
          "id",
          "vector_source_text",
          "cate_id",
          "vector"
        ],
        "parameter": {
          "file_compressor": "zstd"
        }
      },
      "indexs": [
        {
          "index_name": "id",
          "index_type": "PRIMARYKEY64",
          "index_fields": "id",
          "has_primary_key_attribute": true,
          "is_primary_key_sorted": false
        },
        {
          "index_name": "vector",
          "index_type": "CUSTOMIZED",
          "index_fields": [
            {
              "boost": 1,
              "field_name": "id"
            },
            {
              "boost": 1,
              "field_name": "vector"
            }
          ],
          "indexer": "aitheta2_indexer",
          "parameters": {
            "enable_rt_build": "true",
            "min_scan_doc_cnt": "20000",
            "vector_index_type": "Qc",
            "major_order": "col",
            "builder_name": "QcBuilder",
            "distance_type": "SquaredEuclidean",
            "embedding_delimiter": ",",
            "enable_recall_report": "true",
            "ignore_invalid_doc": "true",
            "is_embedding_saved": "false",
            "linear_build_threshold": "5000",
            "dimension": "768",
            "rt_index_params": "{\"proxima.oswg.streamer.segment_size\":2048}",
            "search_index_params": "{\"proxima.qc.searcher.scan_ratio\":0.01}",
            "searcher_name": "QcSearcher",
            "build_index_params": "{\"proxima.qc.builder.quantizer_class\":\"Int8QuantizerConverter\",\"proxima.qc.builder.quantize_by_centroid\":true,\"proxima.qc.builder.optimizer_class\":\"BruteForceBuilder\",\"proxima.qc.builder.thread_count\":10,\"proxima.qc.builder.optimizer_params\":{\"proxima.linear.builder.column_major_order\":true},\"proxima.qc.builder.store_original_features\":false,\"proxima.qc.builder.train_sample_count\":3000000,\"proxima.qc.builder.train_sample_ratio\":0.5}"
          }
        }
      ],
      "attributes": [
        {
          "field_name": "id",
          "file_compress": "no_compressor"
        },
        {
          "field_name": "vector_source_text",
          "file_compress": "no_compressor"
        },
        {
          "field_name": "cate_id",
          "file_compress": "no_compressor"
        },
        {
          "field_name": "vector",
          "file_compress": "no_compressor"
        }
      ],
      "fields": [
        {
          "user_defined_param": {},
          "field_name": "id",
          "field_type": "INT64",
          "compress_type": "equal"
        },
        {
          "field_name": "vector_source_text",
          "field_type": "STRING",
          "compress_type": "uniq"
        },
        {
          "field_name": "cate_id",
          "field_type": "STRING",
          "compress_type": "uniq"
        },
        {
          "user_defined_param": {
            "vector_model": "ops-text-embedding-000",
            "vector_modal": "text",
            "vector_source_field": "vector_source_text"
          },
          "field_name": "vector",
          "field_type": "FLOAT",
          "compress_type": "uniq",
          "multi_value": true
        }
      ]
    }
  6. After you configure the index table, click Publish version.

    After the index table is created, click Next.

Index rebuilding

After the index table is created, click Next.

Select the data source name, data partition, and timestamp, and then click Next.

After the instance is configured, click OK.

On the Change history > Data source changes page, wait for the full data import you manually triggered to complete.

Test retrieval

Syntax

vector:'kettle&modal=text&n=10&search_params={}'&&config=start:0,hit:10,format:json&&kvpairs=formula:proxima_score(vector)&&sort=+RANK
  • modal: Specifies the modal type. Set modal to text.

  • n: Specifies the number of top results to return from the vector retrieval.

  • The text content must be Base64-encoded.

To test the query in the console:

On the Search test page of the OpenSearch console, select the HA query mode. Enter the preceding query in the query input box and click Search. The matching results appear at the bottom of the page. The results include the document ID, text content, and ranking score.

Retrieve data by using an SDK

Add the dependency:

pip install alibabacloud-ha3engine

Search demo:

# -*- coding: utf-8 -*-

from alibabacloud_ha3engine import models, client
from alibabacloud_tea_util import models as util_models
from Tea.exceptions import TeaException, RetryError
def search():
    Config = models.Config(
        endpoint="Your instance endpoint. You can find it on the 'API Endpoints' tab of the instance details page.",
        instance_id="",
        protocol="http",
        access_user_name="The username you set when purchasing the instance",
        access_pass_word="The password you set when purchasing the instance"

    )

    # If requests take a long time, you can increase the request timeout period in milliseconds.
    # This parameter can be used in the search_with_options method.
    runtime = util_models.RuntimeOptions(
        connect_timeout=5000,
        read_timeout=10000,
        autoretry=False,
        ignore_ssl=False,
        max_idle_conns=50
    )

    # Initialize the Ha3Engine client.
    ha3EngineClient = client.Client(Config)

    optionsHeaders = {}

    try:
        # Example 1: Search directly by using an HA query string.
        # =====================================================
        query_str = "config=hit:4,format:json,fetch_summary_type:pk,qrs_chain:search&&query=text_index:'text content&modal=text&n=10&search_params={}'&&cluster=general"
        haSearchQuery = models.SearchQuery(query=query_str)
        haSearchRequestModel = models.SearchRequestModel(optionsHeaders, haSearchQuery)
        hastrSearchResponseModel = ha3EngineClient.search(haSearchRequestModel)
        print(hastrSearchResponseModel)
    except TeaException as e:
        print(f"send request with TeaException : {e}")
    except RetryError as e:
        print(f"send request with Connection Exception  : {e}")
Note

For other SDK demos, see the Developer Guide.

Notes

  • If you have strict latency requirements for vector retrieval, we recommend that you lock the vector index in memory.

  • The field that stores text content must be of the STRING type.

  • The vector index type must be set to CUSTOMIZED.

  • This scenario supports the HA syntax and RESTful APIs, but does not support SQL.