diff --git a/Directory.Packages.props b/Directory.Packages.props
index ede0ef8..89dddc9 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -17,7 +17,7 @@
-
+
diff --git a/MEVD/src/Milvus/ClientWrapper.cs b/MEVD/src/Milvus/ClientWrapper.cs
index 59370d8..f690c50 100644
--- a/MEVD/src/Milvus/ClientWrapper.cs
+++ b/MEVD/src/Milvus/ClientWrapper.cs
@@ -1,25 +1,25 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using Milvus.Client;
+using Milvus.Client.V2;
using Microsoft.Shared.Diagnostics;
namespace CommunityToolkit.VectorData.Milvus;
///
-/// The of a vector store or of a collection. A vector store shares it with the collections it returns,
-/// and the it owns is disposed when the last of them is disposed.
+/// The of a vector store or of a collection. A vector store shares it with the collections it returns,
+/// and the it owns is disposed when the last of them is disposed.
///
internal sealed class ClientWrapper : IDisposable
{
- private readonly MilvusClient? _ownedClient;
+ private readonly MilvusClientV2? _ownedClient;
private int _referenceCount = 1;
///
/// Gets the client.
///
- public MilvusClient Client { get; }
+ public MilvusClientV2 Client { get; }
///
/// Gets the database name for telemetry, or for a client created by the caller: the SDK does not
@@ -35,7 +35,7 @@ internal sealed class ClientWrapper : IDisposable
///
/// The database the SDK client connects to, for telemetry: known to the host-based registrations, which create the client.
///
- public ClientWrapper(MilvusClient milvusClient, bool ownsClient, string? databaseName = null)
+ public ClientWrapper(MilvusClientV2 milvusClient, bool ownsClient, string? databaseName = null)
{
Throw.IfNull(milvusClient);
diff --git a/MEVD/src/Milvus/Milvus.csproj b/MEVD/src/Milvus/Milvus.csproj
index c786b80..48ee643 100644
--- a/MEVD/src/Milvus/Milvus.csproj
+++ b/MEVD/src/Milvus/Milvus.csproj
@@ -1,7 +1,7 @@
- 1.0.0-preview
+ 1.1.0-previewCommunityToolkit.VectorData.Milvus$(AssemblyName)net10.0;net8.0;netstandard2.0;net462
@@ -16,7 +16,7 @@
-
+
diff --git a/MEVD/src/Milvus/MilvusCollection.cs b/MEVD/src/Milvus/MilvusCollection.cs
index 1fa882c..04442df 100644
--- a/MEVD/src/Milvus/MilvusCollection.cs
+++ b/MEVD/src/Milvus/MilvusCollection.cs
@@ -5,7 +5,12 @@
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
-using Milvus.Client;
+using Milvus.Client.V2;
+using Milvus.Client.V2.Requests.Collection;
+using Milvus.Client.V2.Requests.Dml;
+using Milvus.Client.V2.Requests.Dql;
+using Milvus.Client.V2.Responses.Dql;
+using Milvus.Client.V2.Types;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.VectorData;
using Microsoft.Extensions.VectorData.ProviderServices;
@@ -18,11 +23,9 @@ namespace CommunityToolkit.VectorData.Milvus;
///
/// The data type of the record key. Can be , or .
/// The data model to use for adding, updating and retrieving data from storage.
-#pragma warning disable CA1711 // Identifiers should not have incorrect suffix
public class MilvusCollection : VectorStoreCollection, IKeywordHybridSearchable
where TKey : notnull
where TRecord : class
-#pragma warning restore CA1711 // Identifiers should not have incorrect suffix
{
/// The default options for vector search.
private static readonly VectorSearchOptions s_defaultVectorSearchOptions = new();
@@ -35,9 +38,6 @@ public class MilvusCollection : VectorStoreCollectionMilvus client that can be used to manage the collections and records in a Milvus store.
private readonly ClientWrapper _clientWrapper;
- /// Milvus client of the records of the collection.
- private readonly global::Milvus.Client.MilvusCollection _records;
-
/// The model for this collection.
private readonly CollectionModel _model;
@@ -67,7 +67,7 @@ public class MilvusCollection : VectorStoreCollectionThrown for any misconfigured options.
[RequiresDynamicCode("This constructor is incompatible with NativeAOT. For dynamic mapping via Dictionary, instantiate MilvusDynamicCollection instead.")]
[RequiresUnreferencedCode("This constructor is incompatible with trimming. For dynamic mapping via Dictionary, instantiate MilvusDynamicCollection instead")]
- public MilvusCollection(MilvusClient milvusClient, string name, bool ownsClient, MilvusCollectionOptions? options = null)
+ public MilvusCollection(MilvusClientV2 milvusClient, string name, bool ownsClient, MilvusCollectionOptions? options = null)
: this(() => new ClientWrapper(milvusClient, ownsClient), name, options)
{
}
@@ -139,8 +139,6 @@ internal MilvusCollection(Func clientFactory, string name, Func
public override Task CollectionExistsAsync(CancellationToken cancellationToken = default)
- => RunOperationAsync("CollectionExists", () => _clientWrapper.Client.HasCollectionAsync(Name, cancellationToken: cancellationToken));
+ => RunOperationAsync("CollectionExists", () => HasCollectionAsync(cancellationToken));
+
+ private async Task HasCollectionAsync(CancellationToken cancellationToken)
+ => (await _clientWrapper.Client.HasCollectionAsync(new HasCollectionReq { CollectionName = Name }, cancellationToken).ConfigureAwait(false)).Has;
///
public override Task EnsureCollectionExistsAsync(CancellationToken cancellationToken = default)
@@ -170,40 +171,26 @@ public override Task EnsureCollectionExistsAsync(CancellationToken cancellationT
{
// The indexes are created with the collection. Those of an existing collection stay as they are: Milvus rejects
// an index with other settings on an indexed field, or on a field the collection does not have.
- if (!await _clientWrapper.Client.HasCollectionAsync(Name, cancellationToken: cancellationToken).ConfigureAwait(false))
+ if (!await HasCollectionAsync(cancellationToken).ConfigureAwait(false))
{
- await _clientWrapper.Client.CreateCollectionAsync(Name, MilvusCollectionCreateMapping.MapCollectionSchema(_model),
- cancellationToken: cancellationToken).ConfigureAwait(false);
- foreach (var vector in _model.VectorProperties)
- {
- var indexType = MilvusCollectionCreateMapping.GetIndexType(vector);
- var parameters = indexType == IndexType.Hnsw
- ? new Dictionary
- {
- ["M"] = _hnswM.ToString(System.Globalization.CultureInfo.InvariantCulture),
- ["efConstruction"] = _hnswEfConstruction.ToString(System.Globalization.CultureInfo.InvariantCulture)
- } : null;
- await _records.CreateIndexAsync(vector.StorageName, indexType,
- MilvusCollectionCreateMapping.GetMetric(vector), extraParams: parameters,
- cancellationToken: cancellationToken).ConfigureAwait(false);
- }
- foreach (var property in MilvusCollectionCreateMapping.GetFullTextProperties(_model))
+ await _clientWrapper.Client.CreateCollectionAsync(new CreateCollectionReq
{
- await _records.CreateIndexAsync(MilvusCollectionCreateMapping.GetBm25FieldName(property), IndexType.SparseInvertedIndex,
- SimilarityMetricType.Bm25, cancellationToken: cancellationToken).ConfigureAwait(false);
- }
+ CollectionName = Name,
+ Schema = MilvusCollectionCreateMapping.MapCollectionSchema(_model),
+ Indexes = MilvusCollectionCreateMapping.MapIndexes(_model, _hnswM, _hnswEfConstruction),
+ ConsistencyLevel = ConsistencyLevel.Strong,
+ }, cancellationToken).ConfigureAwait(false);
}
- await _records.LoadAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
- await _records.WaitForCollectionLoadAsync(timeout: _loadTimeout, cancellationToken: cancellationToken).ConfigureAwait(false);
+ await LoadAsync(cancellationToken).ConfigureAwait(false);
});
///
public override Task EnsureCollectionDeletedAsync(CancellationToken cancellationToken = default)
=> RunOperationAsync("DeleteCollection", async () =>
{
- if (await _clientWrapper.Client.HasCollectionAsync(Name, cancellationToken: cancellationToken).ConfigureAwait(false))
+ if (await HasCollectionAsync(cancellationToken).ConfigureAwait(false))
{
- await _records.DropAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
+ await _clientWrapper.Client.DropCollectionAsync(new DropCollectionReq { CollectionName = Name }, cancellationToken).ConfigureAwait(false);
}
});
@@ -238,7 +225,7 @@ public override async IAsyncEnumerable GetAsync(
}
var parameters = CreateQueryParameters(includeVectors);
var entries = await RunOperationAsync(OperationName,
- () => _records.QueryRowsAsync(KeyFilter(keyList), parameters, cancellationToken)).ConfigureAwait(false);
+ () => QueryRowsAsync(KeyFilter(keyList), parameters, cancellationToken)).ConfigureAwait(false);
foreach (var entry in entries)
{
yield return _mapper.MapFromStorageToDataModel(entry, includeVectors);
@@ -260,7 +247,8 @@ public override Task DeleteAsync(IEnumerable keys, CancellationToken cance
var keyList = keys.ToList();
return keyList.Count == 0 ? Task.CompletedTask
- : RunOperationAsync(MilvusConstants.DeleteName, () => _records.DeleteAsync(KeyFilter(keyList), cancellationToken: cancellationToken));
+ : RunOperationAsync(MilvusConstants.DeleteName, () => _clientWrapper.Client.DeleteAsync(
+ new DeleteReq { CollectionName = Name, Expression = KeyFilter(keyList), ConsistencyLevel = ConsistencyLevel.Strong }, cancellationToken));
}
///
@@ -322,7 +310,7 @@ public override async Task UpsertAsync(IEnumerable records, Cancellatio
}
if (rows.Count > 0)
{
- await RunOperationAsync(MilvusConstants.UpsertName, () => _records.UpsertAsync(MilvusFieldMapping.CreateColumns(_model, rows), cancellationToken: cancellationToken)).ConfigureAwait(false);
+ await RunOperationAsync(MilvusConstants.UpsertName, () => _clientWrapper.Client.UpsertAsync(new UpsertReq { CollectionName = Name, RowsData = rows }, cancellationToken)).ConfigureAwait(false);
}
}
@@ -363,22 +351,28 @@ public override async IAsyncEnumerable> SearchAsync<
}
if (MilvusCollectionCreateMapping.GetIndexType(vectorProperty) == IndexType.Hnsw)
{
- parameters.ExtraParameters["ef"] = Math.Max(MilvusConstants.DefaultHnswSearchEf, top + options.Skip).ToString(System.Globalization.CultureInfo.InvariantCulture);
+ parameters.Ef = Math.Max(MilvusConstants.DefaultHnswSearchEf, top + options.Skip);
}
- var results = await RunOperationAsync("Search", () => SearchAllowingEmptyResultsAsync(
- () => _records.SearchAsync(vectorProperty.StorageName, [vector],
- MilvusCollectionCreateMapping.GetMetric(vectorProperty), top, parameters, cancellationToken),
- parameters.OutputFields)).ConfigureAwait(false);
+ var request = new SearchReq
+ {
+ CollectionName = Name,
+ VectorFieldName = vectorProperty.StorageName,
+ Vectors = [vector],
+ MetricType = MilvusCollectionCreateMapping.GetMetric(vectorProperty),
+ Limit = top,
+ Parameters = parameters,
+ };
+ var results = await RunOperationAsync("Search", () => _clientWrapper.Client.SearchAsync(request, cancellationToken)).ConfigureAwait(false);
if (IsEmpty(results))
{
yield break;
}
- foreach (var hit in results.GetHits())
+ foreach (var (row, rawScore) in GetHits(results))
{
- var score = MilvusCollectionSearchMapping.MapScore(hit.Score, vectorProperty.DistanceFunction);
+ var score = MilvusCollectionSearchMapping.MapScore(rawScore, vectorProperty.DistanceFunction);
if (MilvusCollectionSearchMapping.PassesThreshold(score, options.ScoreThreshold, vectorProperty.DistanceFunction))
{
- yield return new VectorSearchResult(MapHit(hit, options.IncludeVectors), score);
+ yield return new VectorSearchResult(_mapper.MapFromStorageToDataModel(row, options.IncludeVectors), score);
}
}
}
@@ -420,74 +414,73 @@ public async IAsyncEnumerable> HybridSearchAsync(vectorProperty.StorageName, [vector],
- MilvusCollectionCreateMapping.GetMetric(vectorProperty), candidates)
+ var vectorSearch = new AnnSearchReq
{
+ VectorFieldName = vectorProperty.StorageName,
+ Vectors = [vector],
+ MetricType = MilvusCollectionCreateMapping.GetMetric(vectorProperty),
+ Limit = candidates,
Expression = filter,
};
if (MilvusCollectionCreateMapping.GetIndexType(vectorProperty) == IndexType.Hnsw)
{
vectorSearch.ExtraParameters["ef"] = Math.Max(MilvusConstants.DefaultHnswSearchEf, candidates).ToString(System.Globalization.CultureInfo.InvariantCulture);
}
- var keywordSearch = new TextAnnSearchRequest(MilvusCollectionCreateMapping.GetBm25FieldName(textProperty),
- [string.Join(" ", keywords)], candidates)
+ var keywordSearch = new AnnSearchReq
{
+ VectorFieldName = MilvusCollectionCreateMapping.GetBm25FieldName(textProperty),
+ Texts = [string.Join(" ", keywords)],
+ MetricType = MetricType.Bm25,
+ Limit = candidates,
Expression = filter,
};
- var parameters = new HybridSearchParameters { ConsistencyLevel = ConsistencyLevel.Strong };
+ var parameters = new SearchParameters { ConsistencyLevel = ConsistencyLevel.Strong };
foreach (var field in GetOutputFields(options.IncludeVectors))
{
parameters.OutputFields.Add(field);
}
- var results = await RunOperationAsync("HybridSearch", () => SearchAllowingEmptyResultsAsync(
- () => _records.HybridSearchAsync([vectorSearch, keywordSearch], new RrfReranker(60), limit, parameters, cancellationToken),
- parameters.OutputFields)).ConfigureAwait(false);
+ var request = new HybridSearchReq
+ {
+ CollectionName = Name,
+ SearchRequests = [vectorSearch, keywordSearch],
+ Reranker = new RrfReranker(60),
+ Limit = limit,
+ Parameters = parameters,
+ };
+ var results = await RunOperationAsync("HybridSearch", () => _clientWrapper.Client.HybridSearchAsync(request, cancellationToken)).ConfigureAwait(false);
if (IsEmpty(results))
{
yield break;
}
- foreach (var hit in results.GetHits().Skip(options.Skip))
+ foreach (var (row, score) in GetHits(results).Skip(options.Skip))
{
// A higher RRF score ranks higher: the threshold is a lower bound.
- if (options.ScoreThreshold is not { } threshold || hit.Score >= threshold)
+ if (options.ScoreThreshold is not { } threshold || score >= threshold)
{
- yield return new VectorSearchResult(MapHit(hit, options.IncludeVectors), hit.Score);
+ yield return new VectorSearchResult(_mapper.MapFromStorageToDataModel(row, options.IncludeVectors), score);
}
}
}
- // TODO: Remove this workaround once the SDK fix is available and adopted:
- // https://github.com/milvus-io/milvus-sdk-csharp/issues/191
- // Milvus.Client 2.6.0 cannot decode untyped output fields in an empty response.
- // Retry without output fields to verify that this really is an empty search;
- // do not hide the SDK error if the retry finds any records.
- private static async Task SearchAllowingEmptyResultsAsync(Func> search, IList outputFields)
+ private static bool IsEmpty(SearchResp results) => (results.Ids.LongIds?.Count ?? results.Ids.StringIds?.Count ?? 0) == 0;
+
+ /// Gets the rows of the hits of a single-vector search, each with its key from the IDs, and their scores.
+ private IEnumerable<(Dictionary Row, float Score)> GetHits(SearchResp results)
{
- try
+ var rows = MilvusFieldMapping.ReadRows(results.FieldsData);
+ var keyName = _model.KeyProperty.StorageName;
+ if (rows.Count != results.Scores.Count)
{
- return await search().ConfigureAwait(false);
+ throw new InvalidOperationException($"Milvus returned {rows.Count} rows for {results.Scores.Count} search hits.");
}
- catch (NotSupportedException exception) when (exception.Message == "Cannot convert None FieldData to Field")
+ for (var i = 0; i < results.Scores.Count; i++)
{
- outputFields.Clear();
- var retry = await search().ConfigureAwait(false);
- if (!IsEmpty(retry))
- {
- throw;
- }
- return retry;
+ var row = rows[i];
+ row[keyName] = results.Ids.LongIds is { } longIds ? longIds[i] : results.Ids.StringIds![i];
+ yield return (row, results.Scores[i]);
}
}
- private static bool IsEmpty(SearchResults results) => (results.Ids.LongIds?.Count ?? results.Ids.StringIds?.Count ?? 0) == 0;
-
- private TRecord MapHit(SearchHit hit, bool includeVectors)
- {
- var row = hit.Fields.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.Ordinal);
- row[_model.KeyProperty.StorageName] = hit.Id;
- return _mapper.MapFromStorageToDataModel(row, includeVectors);
- }
-
private static async ValueTask> GetSearchVectorAsync(TInput searchValue, VectorPropertyModel vectorProperty, CancellationToken cancellationToken)
where TInput : notnull
=> searchValue switch
@@ -529,7 +522,7 @@ public override async IAsyncEnumerable GetAsync(Expression _records.QueryRowsAsync(milvusFilter, parameters, cancellationToken)).ConfigureAwait(false);
+ () => QueryRowsAsync(milvusFilter, parameters, cancellationToken)).ConfigureAwait(false);
foreach (var entry in entries)
{
yield return _mapper.MapFromStorageToDataModel(entry, options.IncludeVectors);
@@ -544,7 +537,7 @@ public override async IAsyncEnumerable GetAsync(Expression) ? (MilvusCollectionCreateMapping.GetFullTextProperties(_model).Any() ? this : null) :
serviceType.IsInstanceOfType(this) ? this :
null;
@@ -578,6 +571,51 @@ private QueryParameters CreateQueryParameters(bool includeVectors)
return parameters;
}
+ private async Task>> QueryRowsAsync(string filter, QueryParameters parameters, CancellationToken cancellationToken)
+ {
+ var response = await _clientWrapper.Client.QueryAsync(
+ new QueryReq { CollectionName = Name, Expression = filter, Parameters = parameters }, cancellationToken).ConfigureAwait(false);
+ return MilvusFieldMapping.ReadRows(response.FieldsData);
+ }
+
+ ///
+ /// Loads the collection and waits until Milvus reports it loaded, for at most .
+ ///
+ ///
+ /// The wait is timed here with a , as Milvus.Client did, rather than by the synchronous load of
+ /// Milvus.Client.V2: that one takes the timeout in whole milliseconds, where 0 means no timeout, and adds it to
+ /// , which throws for a timeout such as .
+ ///
+ private async Task LoadAsync(CancellationToken cancellationToken)
+ {
+ await _clientWrapper.Client.LoadCollectionAsync(new LoadCollectionReq { CollectionName = Name, Sync = false }, cancellationToken)
+ .ConfigureAwait(false);
+
+ var stopwatch = Stopwatch.StartNew();
+ while (true)
+ {
+ var state = (await _clientWrapper.Client.GetLoadStateAsync(new GetLoadStateReq { CollectionName = Name }, cancellationToken)
+ .ConfigureAwait(false)).State;
+ if (state == LoadState.Loaded)
+ {
+ return;
+ }
+ if (state == LoadState.NotExist)
+ {
+ throw new MilvusException(MilvusErrorCode.UnexpectedError, $"Collection '{Name}' does not exist; load did not complete.");
+ }
+
+ // NotLoad right after the load request is transient: Milvus registers the load asynchronously.
+ var remaining = _loadTimeout - stopwatch.Elapsed;
+ if (remaining <= TimeSpan.Zero)
+ {
+ throw new TimeoutException($"Timed out waiting for collection '{Name}' to load.");
+ }
+ await Task.Delay(remaining < MilvusConstants.LoadPollInterval ? remaining : MilvusConstants.LoadPollInterval, cancellationToken)
+ .ConfigureAwait(false);
+ }
+ }
+
///
/// Run the given operation and wrap any with .
///
diff --git a/MEVD/src/Milvus/MilvusCollectionCreateMapping.cs b/MEVD/src/Milvus/MilvusCollectionCreateMapping.cs
index 25a93d1..ef6d64a 100644
--- a/MEVD/src/Milvus/MilvusCollectionCreateMapping.cs
+++ b/MEVD/src/Milvus/MilvusCollectionCreateMapping.cs
@@ -1,9 +1,10 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using Milvus.Client;
+using System.Globalization;
using Microsoft.Extensions.VectorData;
using Microsoft.Extensions.VectorData.ProviderServices;
+using Milvus.Client.V2.Types;
namespace CommunityToolkit.VectorData.Milvus;
@@ -13,7 +14,7 @@ public static IReadOnlyList MapCollectionDefinition(CollectionModel
{
var key = model.KeyProperty;
List fields = [key.Type == typeof(long)
- ? FieldSchema.Create(key.StorageName, isPrimaryKey: true)
+ ? new FieldSchema(key.StorageName, DataType.Int64, isPrimaryKey: true)
: FieldSchema.CreateVarchar(key.StorageName, MilvusConstants.MaxVarCharLength, isPrimaryKey: true)];
foreach (var property in model.DataProperties)
{
@@ -21,20 +22,22 @@ public static IReadOnlyList MapCollectionDefinition(CollectionModel
var nullable = !property.Type.IsValueType || Nullable.GetUnderlyingType(property.Type) is not null;
if (MilvusFieldMapping.GetElementType(type) is { } element)
{
- var name = property.StorageName;
- var field = element == typeof(string) ? FieldSchema.CreateVarcharArray(name, MilvusConstants.DefaultArrayCapacity, MilvusConstants.MaxVarCharLength, nullable: true)
- : element == typeof(bool) ? FieldSchema.CreateArray(name, MilvusConstants.DefaultArrayCapacity, nullable: true)
- : element == typeof(int) ? FieldSchema.CreateArray(name, MilvusConstants.DefaultArrayCapacity, nullable: true)
- : element == typeof(long) ? FieldSchema.CreateArray(name, MilvusConstants.DefaultArrayCapacity, nullable: true)
- : element == typeof(float) ? FieldSchema.CreateArray(name, MilvusConstants.DefaultArrayCapacity, nullable: true)
- : element == typeof(double) ? FieldSchema.CreateArray(name, MilvusConstants.DefaultArrayCapacity, nullable: true)
- : throw new NotSupportedException($"Unsupported Milvus array element type '{element}'.");
+ var field = new FieldSchema(property.StorageName, DataType.Array)
+ {
+ ElementDataType = MilvusFieldMapping.GetDataType(element),
+ MaxCapacity = MilvusConstants.DefaultArrayCapacity,
+ Nullable = true,
+ };
+ if (element == typeof(string))
+ {
+ field.MaxLength = MilvusConstants.MaxVarCharLength;
+ }
fields.Add(field);
continue;
}
fields.Add(type == typeof(string)
? FieldSchema.CreateVarchar(property.StorageName, MilvusConstants.MaxVarCharLength, nullable: true, enableAnalyzer: property.IsFullTextIndexed)
- : FieldSchema.Create(property.StorageName, MilvusFieldMapping.GetDataType(type), nullable: nullable));
+ : new FieldSchema(property.StorageName, MilvusFieldMapping.GetDataType(type)) { Nullable = nullable });
}
foreach (var vector in model.VectorProperties)
{
@@ -66,6 +69,32 @@ public static CollectionSchema MapCollectionSchema(CollectionModel model)
return schema;
}
+ ///
+ /// Maps the model to the indexes of the collection: one per vector property, and a sparse inverted index on the
+ /// hidden BM25 field of each full-text indexed property. Each index is named after its field: Milvus.Client.V2 3.0.0
+ /// gives every unnamed index the same default name, and Milvus rejects a second index with that name.
+ ///
+ public static IReadOnlyList MapIndexes(CollectionModel model, int hnswM, int hnswEfConstruction)
+ {
+ List indexes = [];
+ foreach (var vector in model.VectorProperties)
+ {
+ var indexType = GetIndexType(vector);
+ var index = new IndexParam(vector.StorageName, indexName: vector.StorageName, indexType: indexType, metricType: GetMetric(vector));
+ if (indexType == IndexType.Hnsw)
+ {
+ index.ExtraParams["M"] = hnswM.ToString(CultureInfo.InvariantCulture);
+ index.ExtraParams["efConstruction"] = hnswEfConstruction.ToString(CultureInfo.InvariantCulture);
+ }
+ indexes.Add(index);
+ }
+ foreach (var property in GetFullTextProperties(model))
+ {
+ indexes.Add(new IndexParam(GetBm25FieldName(property), indexName: GetBm25FieldName(property), indexType: IndexType.SparseInvertedIndex, metricType: MetricType.Bm25));
+ }
+ return indexes;
+ }
+
public static IEnumerable GetFullTextProperties(CollectionModel model)
=> model.DataProperties.Where(p => p.IsFullTextIndexed);
@@ -75,11 +104,11 @@ public static IEnumerable GetFullTextProperties(CollectionMod
///
public static string GetBm25FieldName(DataPropertyModel property) => property.StorageName + "_bm25";
- public static SimilarityMetricType GetMetric(VectorPropertyModel property) => property.DistanceFunction switch
+ public static MetricType GetMetric(VectorPropertyModel property) => property.DistanceFunction switch
{
- null or DistanceFunction.CosineSimilarity => SimilarityMetricType.Cosine,
- DistanceFunction.DotProductSimilarity => SimilarityMetricType.Ip,
- DistanceFunction.EuclideanSquaredDistance or DistanceFunction.EuclideanDistance => SimilarityMetricType.L2,
+ null or DistanceFunction.CosineSimilarity => MetricType.Cosine,
+ DistanceFunction.DotProductSimilarity => MetricType.Ip,
+ DistanceFunction.EuclideanSquaredDistance or DistanceFunction.EuclideanDistance => MetricType.L2,
_ => throw new NotSupportedException($"Milvus does not support distance function '{property.DistanceFunction}'."),
};
diff --git a/MEVD/src/Milvus/MilvusConstants.cs b/MEVD/src/Milvus/MilvusConstants.cs
index f119f7a..650b012 100644
--- a/MEVD/src/Milvus/MilvusConstants.cs
+++ b/MEVD/src/Milvus/MilvusConstants.cs
@@ -19,6 +19,9 @@ internal static class MilvusConstants
internal const int DefaultPort = 19530;
+ // How often EnsureCollectionExistsAsync asks whether the collection has loaded, as Milvus.Client.V2 does.
+ internal static readonly TimeSpan LoadPollInterval = TimeSpan.FromMilliseconds(500);
+
internal const int DefaultHnswSearchEf = 64;
internal const int MaxFieldNameLength = 255;
diff --git a/MEVD/src/Milvus/MilvusDynamicCollection.cs b/MEVD/src/Milvus/MilvusDynamicCollection.cs
index f58adc8..35b4a28 100644
--- a/MEVD/src/Milvus/MilvusDynamicCollection.cs
+++ b/MEVD/src/Milvus/MilvusDynamicCollection.cs
@@ -1,7 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using Milvus.Client;
+using Milvus.Client.V2;
namespace CommunityToolkit.VectorData.Milvus;
@@ -19,7 +19,7 @@ public sealed class MilvusDynamicCollection : MilvusCollection