Custom routing keys
In multi-tenant scenarios with large indexes, custom routing keys provide user-level data isolation and precise queries. You can bind a user identity, such as an ID, to a routing key. This ensures that each query targets only that user's data, which improves data security and query performance. This topic describes how to use custom routing keys.
Prerequisites
Python 3.6 or later is installed.
opensearch-py 2.6.0 or later is installed.
The Lindorm Vector Engine is enabled.
The Lindorm Search Engine is enabled.
The IP address of the client is added to the Lindorm whitelist.
Preparation
Before creating and using a vector index, you need to connect to the search engine using opensearch-py. The connection method is as follows:
from opensearchpy import OpenSearch, Object
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logging.getLogger('opensearch').setLevel(logging.WARN)
def get_client() -> OpenSearch:
search_client = OpenSearch(
hosts=[{"host": "ld-t4n5668xk31ui****.lindorm.aliyuncs.com", "port": 30070}],
http_auth=("<username>", "<password>"),
http_compress=False,
use_ssl=False,
pool_maxsize=128,
timeout=30
)
return search_clienthost, username, and password refer to the search engine's connection address, default username, and default password, respectively. For instructions on how to obtain these, please refer to View connection information.
Create an index
For vector-only queries
If the data volume in the index is less than 10,000, use a flat index. If the data volume is in the tens or hundreds of thousands, use an hnsw index. If the data volume reaches millions, use an ivfpq index. You can also use a sparse vector index as needed.
In custom routing key scenarios, the primary key `_id` must be globally unique.
When you create the index, specify
"knn_routing": trueto enable the custom routing key feature. For an ivfpq index, also set"meta": {"offline.construction": "true"}.
The following examples show how to create four types of indexes.
flat routing index
def create_ugc_flat():
index_body = {
"settings": {
"index": {
"number_of_shards": 2,
"knn": True,
"knn_routing": True
}
},
"mappings": {
"_source": {
"excludes": ["vector1"]
},
"properties": {
"vector1": {
"type": "knn_vector",
"dimension": 3,
"data_type": "float",
"method": {
"engine": "lvector",
"name": "flat",
"space_type": "l2",
"parameters": {}
}
},
"field1": {
"type": "long"
}
}
}
}
response = client.indices.create(index='vector_routing_flat_test', body=index_body)hnsw routing index
def create_ugc_hnsw():
index_body = {
"settings" : {
"index": {
"number_of_shards": 2,
"knn": True,
"knn_routing": True
}
},
"mappings": {
"_source": {
"excludes": ["vector1"]
},
"properties": {
"vector1": {
"type": "knn_vector",
"dimension": 3,
"method": {
"engine": "lvector",
"name": "hnsw",
"space_type": "l2",
"parameters": {
"m": 24,
"ef_construction": 500
}
}
},
"field1": {
"type": "long"
}
}
}
}
response = client.indices.create(index='vector_routing_hnsw_test', body=index_body)sparse_hnsw routing sparse vector index
def create_ugc_sparse_hnsw():
index_body = {
"settings" : {
"index": {
"number_of_shards": 2,
"knn": True,
"knn_routing": True
}
},
"mappings": {
"_source": {
"excludes": ["vector1"]
},
"properties": {
"vector1": {
"type": "knn_vector",
"data_type": "sparse_vector",
"method": {
"engine": "lvector",
"name": "sparse_hnsw",
"space_type": "innerproduct",
"parameters": {
"m": 24,
"ef_construction": 200
}
}
},
"field1": {
"type": "long"
}
}
}
}
response = client.indices.create(index='vector_routing_sparse_test', body=index_body)ivfpq routing index
In custom routing key scenarios, the data volume for a single routing key is usually small, such as hundreds of thousands of records or fewer. The ivfpq parameter settings for these scenarios differ from the general policies for data volumes in the tens or hundreds of millions. For example, when you set the nlist parameter, which defines the number of clusters, follow the principle that each cluster should contain 1,000 to 30,000 records. If the data volume for each routing key is a few thousand records, set nlist to 2.
def create_ugc_ivfpq():
index_body = {
"settings": {
"index": {
"number_of_shards": 4,
"knn": True,
"knn_routing": True
}
},
"mappings": {
"_source": {
"excludes": ["vector1"]
},
"properties": {
"vector1": {
"type": "knn_vector",
"dimension": 3,
"data_type": "float",
"meta": {"offline.construction": "true"},
"method": {
"engine": "lvector",
"name": "ivfpq",
"space_type": "cosinesimil",
"parameters": {
"m": 3, # Set the same value as the dimension.
"nlist": 2,
"centroids_use_hnsw": False,
"centroids_hnsw_m": 48,
"centroids_hnsw_ef_construct": 500,
"centroids_hnsw_ef_search": 200
}
}
},
"field1": {
"type": "long"
}
}
}
}
response = client.indices.create(index='vector_routing_ivfpq_test', body=index_body)For vector-only and hybrid queries
To perform a hybrid query, specify a full-text index field when you create the index. To do this, add the following parameter:
def create_ugc_hybrid_search():
index_body = {
"settings" : {
"index": {
"number_of_shards": 2,
"knn": True,
"knn_routing": True
}
},
"mappings": {
"_source": {
"excludes": ["vector1"]
},
"properties": {
"vector1": {
"type": "knn_vector",
"dimension": 3,
"data_type": "float",
"method": {
"engine": "lvector",
"name": "hnsw",
"space_type": "l2",
"parameters": {
"m": 24,
"ef_construction": 500
}
}
},
"text_field": {
"type": "text",
"analyzer": "ik_max_word"
},
"field1": {
"type": "long"
}
}
}
}
response = client.indices.create(index='vector1_routing_hnsw_hybridSearch', body=index_body)Write data
Write a single entry
The following example shows how to write data to the flat index vector_routing_flat_test and specify the routing value for the tenant user123.
def write_ugc_index():
doc = {
"field1": 1,
"vector1": [1.2, 1.3, 1.4]
}
response = client.index(index='vector_routing_flat_test', body=doc, id=1, routing='user123')Write data in batches
The following example shows how to write data in batches to the hnsw index vector_routing_hnsw_test and specifies the routing values 1 and 2.
def bulk_write_ugc_index():
operations = """
{ "index" : { "_index" : "vector_routing_hnsw_test", "_id" : "2", "routing": "1"} }
{ "field1" : 2, "vector1": [2.2, 2.3, 2.4]}
{ "index" : { "_index" : "vector_routing_hnsw_test", "_id" : "3", "routing": "2" } }
{ "field1" : 3, "vector1": [3.2, 3.3, 3.4]}
"""
response = client.bulk(body=operations)Build an index
Build an ivfpq index
Only ivfpq indexes must be built manually. In the build statement, you must set "meta": {"offline.construction": "true"}. This setting indicates an offline index.
Before you start the build, ensure that a sufficient amount of data has been written to the index. The number of records must be greater than 256 and more than 30 times the value of nlist.
def build_ugc_index():
# For real-world services, make sure that enough data is written to the index before you start the build.
body_build = {
"indexName": "vector_routing_ivfpq_test",
"fieldName": "vector1",
"removeOldIndex": "true",
"ivf_train_only": "false"
}
response = client.transport.perform_request(
method="POST",
url='/_plugins/_vector/index/build',
body=body_build
)Parameters
Parameter | Required | Description |
ivf_train_only | Yes |
Regardless of whether this parameter is set to |
Clear training data and retain the index codebook
You must perform this step only if you set ivf_train_only to true. This operation uses the existing data to train the codebook but does not generate an index for the existing data.
The reserve_codebook=true parameter is required. This parameter specifies that the index codebook is saved. After you clear the training data, you must write the data again before you can perform pure vector data queries (k-NN searches).
If you set ivf_train_only to false, an index is generated for the existing data based on the trained codebook, and the existing data is retained. You can skip this step.
def truncate_reserve_codebook():
method = 'POST'
url = '/_truncate/vector_routing_ivfpq_test'
params = {
'reserve_codebook': 'true'
}
body = None
headers = {
'Content-Type': 'application/json'
}
response = client.transport.perform_request(
method=method,
url=url,
params=params,
body=body,
headers=headers
)Query data
Query vector-only data
You can query pure vector data using the knn structure.
flat routing index
def query_ugc_flat():
query = {
"size": 20,
"query": {
"knn": {
"vector1": {
"vector": [2.3, 3.3, 4.4],
"k": 20
}
}
}
}
response = client.search(index='vector_routing_flat_test', body=query, routing='user123')hnsw routing index
def query_ugc_hnsw():
query = {
"size": 10,
"query": {
"knn": {
"vector1": {
"vector": [2.2, 2.3, 2.4],
"k": 10
}
}
},
"ext": {"lvector": {"ef_search": "100"}}
}
response = client.search(index='vector_routing_hnsw_test', body=query, routing='1')sparse_hsnw routing sparse vector index
def query_ugc_sparse_hnsw():
query = {
"size": 10,
"query": {
"knn": {
"vector1": {
"vector": {"indices": [10, 45, 16], "values": [0.5, 0.5, 0.2]},
"k": 10
}
}
},
"ext": {"lvector": {"ef_search": "100"}}
}
response = client.search(index='vector_routing_sparse_test', body=query, routing='1')ivfpq routing index
def query_ugc_ivfpq():
query = {
"size": 10,
"query": {
"knn": {
"vector1": {
"vector": [2.2, 2.3, 2.4],
"k": 10
}
}
},
"ext": {"lvector": {"nprobe": "2", "reorder_factor": "2","client_refactor":"true"}}
}
response = client.search(index='vector_routing_ivfpq_test', body=query, routing='1')Perform a hybrid query
Before you perform a hybrid query, ensure that your index supports vector-only and hybrid queries.
Full-text and vector hybrid search
def query_ugc_hybrid():
query = {
"size": 10,
"_source": False,
"query": {
"knn": {
"vector1": {
"vector": [2.8, 2.3, 2.4],
"filter": {
"bool": {
"must": [{
"bool": {
"must": [{
"match": {
"text_field": { # Replace this with the full-text field you want to search.
"query": "test1 test2"
}
}
},
{
"term": {
"_routing": "user123" # Replace this with the routing value specified in the connection statement.
}
}]
}
}]
}
},
"k": 10
}
}
},
"ext": {
"lvector": {
"hybrid_search_type": "filter_rrf",
"rrf_rank_constant": "60",
"rrf_knn_weight_factor": "0.5"
}
}
}
response = client.search(index='vector_text_hybridSearch', body=query, routing='user123')Vector, full-text, and property filtering
def query_ugc_hybrid_filter():
query = {
"size": 10,
"_source": False,
"query": {
"knn": {
"vector1": {
"vector": [2.8, 2.3, 2.4],
"filter": {
"bool": {
"must": [{
"bool": {
"must": [{
"match": {
"text_field": { # Replace this with the full-text field you want to search.
"query": "test1 test2"
}
}
},
{
"term": {
"_routing": "user123" # Replace this with the routing value specified in the connection statement.
}
}]
}
},
{
"bool": {
"filter": [{
"range": {
"field1": {
"gt": 2
}
}
}]
}
}]
}
},
"k": 10
}
}
},
"ext": {
"lvector": {
"hybrid_search_type": "filter_rrf",
"rrf_rank_constant": "60",
"rrf_knn_weight_factor": "0.5",
"filter_type": "efficient_filter"
}
}
}
response = client.search(index='vector_text_hybridSearch', body=query, routing='user123')