This topic describes how to create indexes for scalar fields in Milvus. Scalar fields are non-vector properties, such as integers and strings. An index on a scalar field works like an index in a traditional relational database. It speeds up queries that filter on these properties and improves data retrieval efficiency.
Prerequisites
You have installed the PyMilvus library on your local client and updated it to the latest version.
If you have not installed the PyMilvus library or need to update it, run the following command.
pip install --upgrade pymilvusYou have created a Milvus instance. For more information, see Create a Milvus instance.
Create an index
Automatic indexing
Omit the index_type parameter to use auto indexing. Milvus automatically selects a suitable index type based on the data type of the scalar field, such as integer or string.
from pymilvus import MilvusClient
client = MilvusClient(
uri="http://c-xxxx.milvus.aliyuncs.com:19530", # The public endpoint of the Milvus instance.
token="<yourUsername>:<yourPassword>", # The username and password to log on to the Milvus instance.
db_name="default" # The name of the database to connect to. This example uses the default database.
)
index_params = client.prepare_index_params()
index_params.add_index(
field_name="scalar_field_1", # The scalar field on which to create an index.
index_name="default_index"
)
client.create_index(
collection_name="<yourCollectionname>", # The collection to which the index belongs.
index_params=index_params
)
Custom indexing
Specify the index_type parameter to use custom indexing.
from pymilvus import MilvusClient
client = MilvusClient(
uri="http://c-xxxx.milvus.aliyuncs.com:19530", # The public endpoint of the Milvus instance.
token="<yourUsername>:<yourPassword>", # The username and password to log on to the Milvus instance.
db_name="default" # The name of the database to connect to. This example uses the default database.
)
index_params = client.prepare_index_params()
index_params.add_index(
field_name="scalar_field_2", # The scalar field for which to create an index.
index_type="STL_SORT", # The index type. Valid values are INVERTED, STL_SORT, and Trie.
index_name="stl_sort_index" # The name of the index.
)
client.create_index(
collection_name="<yourCollectionname>",
index_params=index_params
)
List indexes
Use the list_indexes() function to list scalar indexes.
client.list_indexes(
collection_name="<yourCollectionname>"
)