Best practices for text vectorization retrieval

Updated at:

Purchase an OpenSearch Retrieval Engine Edition instance

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

Configure a table

On the Instances page, find the newly purchased instance. Its status is "Pending Configuration". You must complete the table configuration before you can search as expected.

Click Configure in the Actions column of the instance to start the table configuration process.

1. Basic table information

Configuration description:

  • Table name: You can specify a custom name.

  • Number of data shards: Enter a positive integer that does not exceed 256. Shards are used to improve full index building speed and the performance of individual queries.

  • Number of data update resources: the number of resources for real-time data updates. Adjusting the resources can increase the concurrency of real-time data consumption and thereby improve TPS.

Note
  • By default, 2 free data update resources are provided. If the number exceeds 2, you are charged for n-2 resources, where n is the total number of data update resources for a single table.

2. Data synchronization

The supported data sources are "MaxCompute + API data source", "API data source", "OSS + API data source", and "Data Lake Formation (DLF)". This demonstration uses MaxCompute + API as the full data source. After you configure the parameters in sequence, the data source must also pass verification before you can proceed to the next step.

Parameter description:

  • AccessKey: the AccessKey ID of your Alibaba Cloud account or RAM user.

  • AccessKey Secret: the AccessKey secret that corresponds to the AccessKey ID.

  • Project: the name of the MaxCompute project to access.

  • Table: the name of the MaxCompute table to access.

  • Partition: You must specify a partition key for a MaxCompute data source. Example: ds=20170626.

  • Automatic Index Rebuilding: specifies whether to enable automatic index rebuilding tasks. If enabled, when a change to the current data source is detected, the index tables that reference the data source are automatically rebuilt.

3. Index schema

Because MaxCompute + API is selected as the data source, the data source fields are automatically mapped. You still need to configure the fields and indexes.

Configuration description:

  1. Field configuration: Text vectorization uses the system to convert text into vectors and then retrieves data by using the vectors. Therefore, you must configure the following 3 required fields (all names can be customized):

    • id (primary key field): The type can be STRING or an integer type, and you must select Primary Key. In this example, set the field type to INT64, select Primary Key, and set the data compression method to equal.

    • vector_source_text (stores the text content): Set the field type to STRING and the data compression method to uniq.

    • vector field: Leave the configuration of this field empty. The settings for the platform to convert text into vectors are configured in Advanced Configuration > Configure. In this example, set the field type of the vector field to STRING, select Multi-value, and set the delimiter to a comma (,). In the configuration panel that appears, specify the following vector parameters.

      • Field description:

        • vector_model: the vector model. Multiple Chinese and English models are supported (the dimension is fixed at 768). The following models are available.

          • ops-text-embedding-000: short text-to-vector model

          • ops-text-embedding-en-000: English short text-to-vector model

          • ops-text-embedding-1024-000-20231001: enhanced Chinese text-to-vector model, 1024

          • ops-text-embedding-512-000-20231001: enhanced Chinese text-to-vector model, 512

          • ops-text-embedding-128-000-20231001: enhanced Chinese text-to-vector model, 128

          • ops-text-embedding-512-en-000-20231001: enhanced English text-to-vector model, 512

          • ops-text-embedding-128-en-000-20231001: enhanced English text-to-vector model, 128

        • vector_modal: the vector type. For text vectors, set this parameter to text in this topic.

        • vector_source_field: the field to be vectorized. In this topic, set this parameter to vector_source_text.

          Important

          Attribute and field content compression:

          • You can choose whether to compress attribute fields. By default, attribute fields are not compressed. Select file_compressor to enable compression.

          • You can choose whether to compress field content. By default, field content is not compressed. By default, uniq is selected for multi-value fields and STRING fields, and equal is selected for single-value numeric fields.

          • For a MaxCompute or OSS data source, the fields synchronized from the data source are displayed below the preset fields.

          • Primary key fields do not support compression.

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

  2. Index settings: The required indexes are the primary key index and the vector index. Configure them as follows.

    • Primary key index: Specify a custom name, set the index type to PRIMARYKEY64, and select the field that is set as the primary key in the field settings as the included field. In this example, the field is id.

    • Vector index: Specify a custom name and set the index type to CUSTOMIZED. You can select up to 3 included fields. If you have no tag field, you can leave it empty, but the primary key field and the vector field are required.

    • In Advanced Configuration > View/Modify of the vector index, change dimension to 768. The dimension is fixed at 768 and cannot be changed to other values. We recommend that you keep the default values for other parameters.

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
    }
  ]
}

4. Confirm creation

Click Confirm Creation to create the table.

Return to the instance details page. You can view the creation progress in Feature Extensions > Change History. After the progress is complete, you can perform query tests.

Test the results

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 modality type. Set modal to text.

  • n specifies the number of top results returned by the vector retrieval.

  • If the text content contains special invisible characters, the text must be Base64-encoded.

Perform a query test in the console:

On the Query Test page of the console, select the HA Query mode, enter the preceding query syntax in the query field, and click Search. The system returns the results that are semantically most similar to the query text, including fields such as the document ID, content, and ranking score.

Retrieve data by using an SDK

Add dependencies:

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="The API domain name under API Endpoint on the instance details page",
        instance_id="",
        protocol="http",
        access_user_name="The username that you specified when you purchased the instance",
        access_pass_word="The password that you specified when you purchased the instance"

    )

    # If user requests take a long time, you can use this configuration to increase the request wait time. Unit: ms
    # 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 Developer guide

Usage notes

  • If you have strict requirements on vector retrieval latency, we recommend that you mmap loading policy.

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

  • The vector index must be of the CUSTOMIZED type.

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