Access the Lindorm vector engine with opensearch-py

Updated at:

The Lindorm vector engine supports scalar, vector, and full-text search via the Elasticsearch protocol. Use opensearch-py to connect, create vector indexes, write data, and run queries.

Prerequisites

Make sure you have:

Connect to LindormSearch

Connect to LindormSearch before creating a vector index.

from opensearchpy import OpenSearch, Object

import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# If you enable the logging module of Python, you must make the following modifications to prevent excessive opensearch info logs.
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  # in seconds
    )
    return search_client
Parameter Description
host The LindormSearch endpoint.
username The default username for LindormSearch.
password The password for the default username.

Get the endpoint and credentials from View connection information.

Choose an algorithm

Choose an algorithm based on data volume and resource needs.

Algorithm Data volume Resource usage Characteristics Usage notes
flat [0, 10,000) Pure memory Brute-force search for small datasets. Performance degrades as data grows.
hnsw [10,000, 1,000,000) Pure memory, high resource usage Online indexing for medium datasets. Set number_of_shards equal to the number of vector engine nodes. For many small indexes, set number_of_shards to 1.
ivfpq More than 1,000,000 Disk indexing with 1:8 default compression (memory = 1/8 of raw data). Offline indexing. Write sufficient data before building. Cost-effective for large datasets. Data must exceed 256 records and 30× the nlist value. Trigger the build after importing data. Once complete, kNN queries and writes are available. nlist configuration: Parameters.

Create a vector index

Configure vector1 (vector columns) and field1 (scalar columns) in the mappings structure. Specify vector columns and their parameters explicitly in the mappings structure when you create the index.

Create an HNSW index

index_body = {
  "settings": {
    "index": {
      "number_of_shards": 2,
      "knn": 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": 200
          }
        }
      },
      "field1": {
        "type": "long"
      }
    }
  }
}
response = client.indices.create(index='vector_test', body=index_body)

Create an IVFPQ index

# Set the m field to the same value as that of the dimension field for the IVFPQ index.
dim = 3
index_body = {
  "settings": {
    "index": {
      "number_of_shards": 4,
      "knn": True,
      "knn.offline.construction": True
    }
  },
  "mappings": {
    "_source": {"excludes": ["vector1"]},
    "properties": {
      "vector1": {
        "type": "knn_vector",
        "dimension": dim,
        "data_type": "float",
        "method": {
          "engine": "lvector",
          "name": "ivfpq",
          "space_type": "cosinesimil",
          "parameters": {
            "m": dim,
            "nlist": 10000,
            "centroids_use_hnsw": True,
            "centroids_hnsw_m": 48,
            "centroids_hnsw_ef_construct": 500,
            "centroids_hnsw_ef_search": 200
          }
        }
      },
      "field1": {
        "type": "long"
      }
    }
  }
}
response = client.indices.create(index='vector_ivfpq_test', body=index_body)
Important
  • Set knn.offline.construction to True. Write a sufficient amount of data before triggering the index build.

  • Replace the dimension value with your actual vector dimension and set m to the same value as dimension.

Create a sparse vector index

index_body = {
  "settings": {
    "index": {
      "number_of_shards": 2,
      "knn": 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_sparse_test', body=index_body)
Important

For sparse vector indexes, set data_type to sparse_vector, name to sparse_hnsw, and space_type to innerproduct.

Index parameters

General parameters

Parameter Required Description
type Yes The index column type. Set to knn_vector for vector columns.
dimension Yes The number of vector dimensions. Valid values: 1 to 32768.
data_type No The vector data type. Valid values: float, float16, sparse_vector (sparse vector indexes only).
method.name Yes The index algorithm. Valid values: flat, hnsw, ivfpq, sparse_hnsw (sparse vector indexes only).
method.space_type No The distance algorithm. Valid values: l2 (default) for Euclidean distance, cosinesimil for cosine similarity, innerproduct for inner product.

HNSW algorithm parameters

Parameter Required Description
method.parameters.m No The maximum number of outgoing edges per layer in the graph. Valid values: 1 to 100. Default value: 16.
method.parameters.ef_construction No The dynamic list length during index building. Valid values: 1 to 1000. Default value: 100.

IVFPQ algorithm parameters

Parameter Required Description
method.parameters.m No The number of sub-spaces in quantization. Valid values: 2 to 32768. Default value: 16.
Important

For IVFPQ indexes, this value must equal the dimension parameter.

method.parameters.nlist No The number of cluster centroids. Valid values: 2 to 1,000,000. Default value: 10000.
method.parameters.centroids_use_hnsw No Whether to use HNSW for cluster centroid search. Valid values: true (default), false.
method.parameters.centroids_hnsw_m No The maximum outgoing edges per layer when HNSW is used for cluster centroid search. Valid values: 1 to 100. Default value: 16.
method.parameters.centroids_hnsw_ef_construct No The dynamic list length during HNSW index building for cluster centroid search. Valid values: 1 to 1000. Default value: 100.
method.parameters.centroids_hnsw_ef_search No The dynamic list length during HNSW queries for cluster centroid search. Valid values: 1 to 1000. Default value: 100.

Build an IVFPQ index

Important
  • For non-IVFPQ indexes, index.knn.offline.construction defaults to false, and indexing runs online automatically.

  • For IVFPQ, set index.knn.offline.construction to true. Before building, ensure data exceeds 256 records and 30× the nlist value.

  • After the build completes, data can be written and queried. No rebuild is needed.

Trigger an index build

Trigger the build with client.transport.perform_request:

body_build = {
      "indexName": "vector_ivfpq_test",
      "fieldName": "vector1",
      "removeOldIndex": "true"
  }

build_response = client.transport.perform_request(
      method="POST",
      url='/_plugins/_vector/index/build',
      body=body_build
  )
Parameter Required Description
indexName Yes The index name. Example: vector_ivfpq_test.
fieldName Yes The field to build the index for. Example: vector1.
removeOldIndex Yes Whether to delete the existing index data when building. Valid values: true (recommended; deletes existing data; kNN queries are unavailable until the build completes), false (default; retains the existing index, which may affect search performance).

Sample response:

{
  "payload": ["default_vector_ivfpq_test_vector1"]
}

The response contains the build task ID.

Check index build status

build_query = {
      "indexName": "vector_ivfpq_test",
      "fieldName": "vector1",
      "taskIds": "[\"default_vector_ivfpq_test_vector1\"]"
  }

response = client.transport.perform_request(
      method='GET',
      url='/_plugins/_vector/index/tasks',
      body=build_query
  )

Pass the taskIds from the build response. An empty array ("taskIds": "[]") returns the same results.

Sample response:

{
  "payload": ["task: default_vector_ivfpq_test_vector1, stage: FINISH, innerTasks: xxx, info: finish building"]
}

The stage field indicates the build status: START, TRAIN, BUILDING, ABORT, FINISH, or FAIL.

Call the /index/abort API to stop an index build. After a successful call, the index enters the ABORT state.

Stop an index build

An index in the FINISH state cannot be stopped.

abort_body = {
      "indexName": "vector_ivfpq_test",
      "fieldName": "vector1",
      "taskIds": "[\"default_vector_ivfpq_test_vector1\"]"
  }

response = client.transport.perform_request(
      method='POST',
      url='/_plugins/_vector/index/tasks/abort',
      body=abort_body
)

Sample response:

{
  "payload":["Task: default_vector_ivfpq_test_vector1 remove success"]
}

Write data

Vector indexes use the same write methods as standard indexes.

Write a single document

Overwrite data

Creates or overwrites the document. If a write contains only scalar fields, existing vector fields are deleted.

doc = {
  "field1": 1,
  "vector1": [1.2, 1.3, 1.4]
}
response = client.index(index='vector_test', body=doc, id=1)

Insert data

Use CREATE to insert a new document. Fails if the document already exists.

doc = {
  "field1": 2,
  "vector1": [2.2, 2.3, 2.4]
}
response = client.create(index='vector_test', body=doc, id=2)

Each request requires an index name, an id (auto-generated if omitted), and a body. The id uniquely identifies the document. The body contains the document's fields: each property name is a field name and its value is the field value. For example, field1 is a field name and 2 is its value. Vector values are arrays.

Sample response:

{
  "_index" : "vector_test",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 1,
  "result" : "created",
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 0,
  "_primary_term" : 1
}
Field Description
_index The target index name.
_id The document ID.
_version The document version number. Increments with each update.
result The operation result. created indicates a new document; updated indicates an existing document was updated.
_shards.total The total number of shards involved in the operation.
_shards.successful The number of shards where data was written successfully.
_shards.failed The number of shards where data failed to be written.

Batch write

Generic batch write

operations = """
{ "index" : { "_index" : "vector_test", "_id" : "2" } }
{ "field1" : 1, "vector1": [2.2, 2.3, 2.4]}
{ "create" : { "_index" : "vector_test", "_id" : "3" } }
{ "field1" : 2, "vector1": [1.2, 1.3, 4.4]}
{ "delete" : { "_index" : "vector_test", "_id" : "2" } }
{ "update" : {"_id" : "1", "_index" : "vector_test"} }
{ "doc" : {"field1" : 3, "vector1": [2.2, 3.3, 4.4]} }
"""
response=client.bulk (operations)


# Encapsulate bulk data write operations
def write_docs(self, index_name: str) -> None:
    operations = []
    for i in range(0, 1000):
        id = self.random.randint(-2 ** 63, 2 ** 63 - 1)
        operations.append(json.dumps({"index": {"_index": index_name, "_id": id}}))
        operations.append("\n")
        vector1 = []
        for j in range(0, 5):
            vector1.append(self.random.random())
        operations.append(json.dumps({"field1": self.random.random(), "vector1": vector1}))
        operations.append("\n")
    response = self.client.bulk("".join(operations))

Batch write sparse vectors

Sparse vectors use the same batch methods with a different vector1 format: JSON STRING (better performance) or JSON Object (more readable).

JSON STRING

doc = {
  "field1": 2,
  "vector1": "{\"indices\": [10, 14, 16], \"values\": [0.5, 0.5, 0.2]}"
}
response = client.index(index='vector_sparse_test', body=doc, id=1)

JSON Object

doc = {
  "field1": 1,
  "vector1": {"indices": [10, 12, 16], "values": [0.5, 0.5, 0.2]}
}
response = client.index(index='vector_sparse_test', body=doc, id=1)

Query data

Pure vector queries

Search vector data with the kNN query structure.

Basic kNN query

Find the 10 nearest vectors in vector1 of vector_test to [2.3, 3.3, 4.4], with minimum score 0.1:

query = {
  "size": 10,
  "query": {
    "knn": {
      "vector1": {
        "vector": [2.3, 3.3, 4.4],
        "k": 10
      }
    }
  },
  "ext": {"lvector": {"min_score": "0.1"}}
}
response = client.search(index='vector_test', body=query)

Sample response:

{
  "took" : 30,
  "timed_out" : false,
  "terminated_early" : false,
  "num_reduce_phases" : 0,
  "_shards" : {
    "total" : 2,
    "successful" : 2,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 3,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "vector_test",
        "_id" : "2",
        "_score" : 1.0
      },
      {
        "_index" : "vector_test",
        "_id" : "1",
        "_score" : 0.25
      },
      {
        "_index" : "vector_test",
        "_id" : "3",
        "_score" : 0.14285715
      }
    ]
  }
}

Query parameters

Parameter structure Parameter Required Description
knn vector Yes The query vector.
k Yes The number of nearest neighbors to return.
Important

For pure vector search, set size and k to the same value.

ext lvector.min_score No The minimum similarity threshold. Only results with scores above this value are returned. Score range: [0, +inf]. Default value: 0.
lvector.filter_type No The filter mode for combined queries. Valid values: pre_filter (filter scalar data, then search vectors), post_filter (search vectors, then filter scalar data), efficient_filter (automatically selects pre_filter or post_filter based on cost estimation; requires LindormSearch 3.9.10 or later). Empty by default.
lvector.ef_search No The dynamic list length during search. Applies only to HNSW. Valid values: 1 to 1000. Default value: 100.
lvector.nprobe No The number of cluster units to search. Higher values increase recall rate but reduce performance. Minimum: 1. Maximum: the method.parameters.nlist value. No default value.
Important

Applies only to IVFPQ.

lvector.reorder_factor No Reorders search results using original vectors. IVFPQ uses quantized distances, which may lose precision. The reorder proportion is k * reorder_factor. Valid values: 1 to 200. Default value: 10.
Important

Applies only to IVFPQ. If k is small, set this to 5. If k is greater than 100, set this to 1.

lvector.client_refactor No Whether to perform reordering at the upper layer instead of within each shard, for improved performance. Valid values: true, false (default).
lvector.k_expand_scope No When efficient_filter automatically selects post_filter, use this parameter instead of k for better performance. Default value: 1000.

Return specific fields

Set "_source": ["field1", "field2"] to return specific fields, or "_source": true for all non-vector fields.

query = {
  "size": 10,
  "_source": ["field1"],
  "query": {
    "knn": {
      "vector1": {
        "vector": [2.3, 3.3, 4.4],
        "k": 10
      }
    }
  },
  "ext": {"lvector": {"min_score": "0.1"}}
}
response = client.search(index='vector_test', body=query)

Sample response:

{
  "took" : 35,
  "timed_out" : false,
  "terminated_early" : false,
  "num_reduce_phases" : 0,
  "_shards" : {
    "total" : 2,
    "successful" : 2,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 3,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "vector_test",
        "_id" : "2",
        "_score" : 1.0,
        "_source" : {
          "field1" : 1
        }
      },
      {
        "_index" : "vector_test",
        "_id" : "1",
        "_score" : 0.25,
        "_source" : {
          "field1" : 1
        }
      },
      {
        "_index" : "vector_test",
        "_id" : "3",
        "_score" : 0.14285715,
        "_source" : {
          "field1" : 2
        }
      }
    ]
  }
}

Query with the HNSW algorithm

query = {
  "size": 10,
  "query": {
    "knn": {
      "vector1": {
        "vector": [2.3, 3.3, 4.4],
        "k": 10
      }
    }
  },
  "ext": {"lvector": {"ef_search": "100"}}
}
response = client.search(index='vector_test', body=query)

Query with the IVFPQ algorithm

query = {
  "size": 10,
  "query": {
    "knn": {
      "vector1": {
        "vector": [2.3, 3.3, 4.4],
        "k": 10
      }
    }
  },
  "ext": {"lvector": {"nprobe": "60", "reorder_factor": "5"}}
}
response = client.search(index='vector_ivfpq_test', body=query)
Important
  • If k is greater than 100, set reorder_factor to 1.

  • When nlist is 10000, start with nprobe set to 60. To increase the recall rate, try higher values such as 80, 100, 120, 140, or 160. Increasing nprobe has significantly less performance overhead than increasing reorder_factor. Avoid excessively large nprobe values.

Query a sparse vector index

Sparse vectors use the same query structure with a different vector1 format: JSON STRING (better performance) or JSON Object (more readable).

JSON STRING

query = {
  "size": 10,
  "query": {
    "knn": {
      "vector1": {
        "vector": "{\"indices\": [10, 45, 16], \"values\": [0.5, 0.5, 0.2]}",
        "k": 10
      }
    }
  }
}
response = client.search(index='vector_sparse_test', body=query)

JSON Object

query = {
  "size": 10,
  "query": {
    "knn": {
      "vector1": {
        "vector": {"indices": [10, 45, 16], "values": [0.5, 0.5, 0.2]},
        "k": 10
      }
    }
  }
}
response = client.search(index='vector_sparse_test', body=query)

Combined queries with filters

Combine vector and scalar conditions. In practice, post-filter approximate queries generally return more similar results.

Pre-filter approximate query

Add a filter to the kNN query and set filter_type to pre_filter. Scalar filtering runs before vector search.

The pre-filter is limited to 10,000 data records.
query = {
  "size": 10,
  "query": {
    "knn": {
      "vector1": {
        "vector": [2.3, 3.3, 4.4],
        "filter": {
          "range": {
            "field1": {
              "gte": 0
            }
          }
        },
        "k": 10
      }
    }
  },
  "ext": {"lvector": {"filter_type": "pre_filter"}}
}
response = client.search(index='vector_test', body=query)

Post-filter approximate query

Add a filter to the kNN query and set filter_type to post_filter. Vector search runs before scalar filtering.

When using post_filter mode, set k to a larger value to search more vector data before filtering.
query = {
  "size": 10,
  "query": {
    "knn": {
      "vector1": {
        "vector": [2.3, 3.3, 4.4],
        "filter": {
          "range": {
            "field1": {
              "gte": 0
            }
          }
        },
        "k": 10
      }
    }
  },
  "ext": {"lvector": {"filter_type": "post_filter"}}
}
response = client.search(index='vector_test', body=query)

For post-filter queries, increase k. The following example uses post_filter on an HNSW index.

If you also use the IVFPQ algorithm, adjust reorder_factor based on your requirements.
query = {
  "size": 10,
  "query": {
    "knn": {
      "vector1": {
        "vector": [2.3, 3.3, 4.4],
        "filter": {
          "range": {
            "field1": {
              "gte": 0
            }
          }
        },
        "k": 1000
      }
    }
  },
  "ext": {"lvector": {"filter_type": "post_filter","nprobe": "60", "reorder_factor": "1"}}
}
response = client.search(index='vector_test', body=query)
Important
  • For post_filter queries, increase k as needed. If k is large, set reorder_factor to 1.

  • When nlist is 10000, start with nprobe set to 60. To improve recall, increase nprobe to values such as 80, 100, 120, 140, or 160. Increasing nprobe has significantly less performance overhead than increasing reorder_factor. Avoid excessively large nprobe values.

Alternatively, use the top-level post_filter parameter:

query = {
  "size": 10,
  "query": {
    "knn": {
      "vector1": {
        "vector": [2.3, 3.3, 4.4],
        "k": 10
      }
    }
  },
  "post_filter": {
    "range": {
      "field1": {
        "gte": 0
      }
    }
  }
}
response = client.search(index='vector_test', body=query)

Manage indexes and documents

Common operations on the vector_test index:

List all indexes and their data volumes

info = client.cat.indices(v=True)

Sample output:

health status index        uuid        pri rep docs.count docs.deleted store.size pri.store.size
green  open   vector_test  vector_test 2   0          2            0      6.8kb          6.8kb

Get the document count for a specific index

client.count(index="vector_test", pretty=True)

Sample output:

{
  "count" : 2,
  "_shards" : {
    "total" : 2,
    "successful" : 2,
    "skipped" : 0,
    "failed" : 0
  }
}

View index metadata

client.indices.get(index="vector_test", pretty=True)

Sample output:

{
  "vector_test" : {
    "aliases" : { },
    "mappings" : {
      "_source" : {
        "excludes" : [
          "vector1"
        ]
      },
      "properties" : {
        "field1" : {
          "type" : "long"
        },
        "vector1" : {
          "type" : "knn_vector",
          "dimension" : 3,
          "data_type" : "float",
          "method" : {
            "engine" : "lvector",
            "space_type" : "l2",
            "name" : "hnsw",
            "parameters" : {
              "ef_construction" : 200,
              "m" : 24
            }
          }
        }
      }
    },
    "settings" : {
      "index" : {
        "search" : {
          "slowlog" : {
            "level" : "DEBUG",
            "threshold" : {
              "fetch" : {
                "warn" : "1s",
                "trace" : "200ms",
                "debug" : "500ms",
                "info" : "800ms"
              },
              "query" : {
                "warn" : "10s",
                "trace" : "500ms",
                "debug" : "1s",
                "info" : "5s"
              }
            }
          }
        },
        "indexing" : {
          "slowlog" : {
            "level" : "DEBUG",
            "threshold" : {
              "index" : {
                "warn" : "10s",
                "trace" : "500ms",
                "debug" : "2s",
                "info" : "5s"
              }
            }
          }
        },
        "number_of_shards" : "2",
        "provided_name" : "vector_test",
        "knn" : "true",
        "creation_date" : "1727169417350",
        "number_of_replicas" : "0",
        "uuid" : "vector_test",
        "version" : {
          "created" : "136287927"
        }
      }
    }
  }
}

Delete an index

client.indices.delete(index="vector_test")

Delete documents by query

delete_query = {
    "query": {
        "term": {
            "field1": 1 # Delete the document whose field1 values are 1.
        }
    }
}

# Perform a delete_by_query operation.
response = client.delete_by_query(
    index='vector_test',
    body=delete_query
)