Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
<PackageVersion Include="Microsoft.Data.SqlClient" Version="6.1.6" />
<PackageVersion Include="System.Security.Cryptography.Pkcs" Version="10.0.13" />
<PackageVersion Include="Microsoft.Data.Sqlite" Version="10.0.10" />
<PackageVersion Include="Milvus.Client" Version="2.6.0" />
<PackageVersion Include="Milvus.Client.V2" Version="3.0.1" />
<PackageVersion Include="MongoDB.Driver" Version="3.10.0" />
<PackageVersion Include="Npgsql" Version="10.0.3" />
<PackageVersion Include="NRedisStack" Version="1.6.0" />
Expand Down
12 changes: 6 additions & 6 deletions MEVD/src/Milvus/ClientWrapper.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// The <see cref="MilvusClient"/> of a vector store or of a collection. A vector store shares it with the collections it returns,
/// and the <see cref="MilvusClient"/> it owns is disposed when the last of them is disposed.
/// The <see cref="MilvusClientV2"/> of a vector store or of a collection. A vector store shares it with the collections it returns,
/// and the <see cref="MilvusClientV2"/> it owns is disposed when the last of them is disposed.
/// </summary>
internal sealed class ClientWrapper : IDisposable
{
private readonly MilvusClient? _ownedClient;
private readonly MilvusClientV2? _ownedClient;

private int _referenceCount = 1;

/// <summary>
/// Gets the client.
/// </summary>
public MilvusClient Client { get; }
public MilvusClientV2 Client { get; }

/// <summary>
/// Gets the database name for telemetry, or <see langword="null"/> for a client created by the caller: the SDK does not
Expand All @@ -35,7 +35,7 @@ internal sealed class ClientWrapper : IDisposable
/// <param name="databaseName">
/// The database the SDK client connects to, for telemetry: known to the host-based registrations, which create the client.
/// </param>
public ClientWrapper(MilvusClient milvusClient, bool ownsClient, string? databaseName = null)
public ClientWrapper(MilvusClientV2 milvusClient, bool ownsClient, string? databaseName = null)
{
Throw.IfNull(milvusClient);

Expand Down
4 changes: 2 additions & 2 deletions MEVD/src/Milvus/Milvus.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<Version>1.0.0-preview</Version>
<Version>1.1.0-preview</Version>
<AssemblyName>CommunityToolkit.VectorData.Milvus</AssemblyName>
<RootNamespace>$(AssemblyName)</RootNamespace>
<TargetFrameworks>net10.0;net8.0;netstandard2.0;net462</TargetFrameworks>
Expand All @@ -16,7 +16,7 @@
<PackageReference Include="System.Linq.AsyncEnumerable" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" />
<PackageReference Include="Microsoft.Extensions.AI.Abstractions" />
<PackageReference Include="Milvus.Client" />
<PackageReference Include="Milvus.Client.V2" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' Or '$(TargetFramework)' == 'net462' ">
Expand Down
204 changes: 121 additions & 83 deletions MEVD/src/Milvus/MilvusCollection.cs

Large diffs are not rendered by default.

59 changes: 44 additions & 15 deletions MEVD/src/Milvus/MilvusCollectionCreateMapping.cs
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -13,28 +14,30 @@ public static IReadOnlyList<FieldSchema> MapCollectionDefinition(CollectionModel
{
var key = model.KeyProperty;
List<FieldSchema> fields = [key.Type == typeof(long)
? FieldSchema.Create<long>(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)
{
var type = Nullable.GetUnderlyingType(property.Type) ?? property.Type;
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<bool>(name, MilvusConstants.DefaultArrayCapacity, nullable: true)
: element == typeof(int) ? FieldSchema.CreateArray<int>(name, MilvusConstants.DefaultArrayCapacity, nullable: true)
: element == typeof(long) ? FieldSchema.CreateArray<long>(name, MilvusConstants.DefaultArrayCapacity, nullable: true)
: element == typeof(float) ? FieldSchema.CreateArray<float>(name, MilvusConstants.DefaultArrayCapacity, nullable: true)
: element == typeof(double) ? FieldSchema.CreateArray<double>(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)
{
Expand Down Expand Up @@ -66,6 +69,32 @@ public static CollectionSchema MapCollectionSchema(CollectionModel model)
return schema;
}

/// <summary>
/// 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.
/// </summary>
public static IReadOnlyList<IndexParam> MapIndexes(CollectionModel model, int hnswM, int hnswEfConstruction)
{
List<IndexParam> 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<DataPropertyModel> GetFullTextProperties(CollectionModel model)
=> model.DataProperties.Where(p => p.IsFullTextIndexed);

Expand All @@ -75,11 +104,11 @@ public static IEnumerable<DataPropertyModel> GetFullTextProperties(CollectionMod
/// </summary>
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}'."),
};

Expand Down
3 changes: 3 additions & 0 deletions MEVD/src/Milvus/MilvusConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
4 changes: 2 additions & 2 deletions MEVD/src/Milvus/MilvusDynamicCollection.cs
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -19,7 +19,7 @@ public sealed class MilvusDynamicCollection : MilvusCollection<object, Dictionar
/// <param name="name">The name of the collection.</param>
/// <param name="ownsClient">A value indicating whether <paramref name="milvusClient"/> is disposed when the collection is disposed.</param>
/// <param name="options">Optional configuration options for this class.</param>
public MilvusDynamicCollection(MilvusClient milvusClient, string name, bool ownsClient, MilvusCollectionOptions options)
public MilvusDynamicCollection(MilvusClientV2 milvusClient, string name, bool ownsClient, MilvusCollectionOptions options)
: this(() => new ClientWrapper(milvusClient, ownsClient), name, options)
{
}
Expand Down
4 changes: 2 additions & 2 deletions MEVD/src/Milvus/MilvusErrorHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@

using Grpc.Core;
using Microsoft.Extensions.VectorData;
using Milvus.Client;
using Milvus.Client.V2;

namespace CommunityToolkit.VectorData.Milvus;

// Milvus.Client reports server errors as MilvusException, gRPC errors as RpcException, and a wait that runs out of time,
// Milvus.Client.V2 reports server and gRPC errors as MilvusException (keeping the gRPC status), and a wait that runs out of time,
// such as the wait for a collection to load, as TimeoutException.
internal static class MilvusErrorHandler
{
Expand Down
91 changes: 51 additions & 40 deletions MEVD/src/Milvus/MilvusFieldMapping.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,20 @@

using System.Globalization;
using System.Text;
using Milvus.Client;
using Milvus.Client.V2.Types;
using Microsoft.Extensions.VectorData.ProviderServices;

namespace CommunityToolkit.VectorData.Milvus;

internal static class MilvusFieldMapping
{
public static MilvusDataType GetDataType(Type type)
=> type == typeof(string) ? MilvusDataType.VarChar
: type == typeof(bool) ? MilvusDataType.Bool
: type == typeof(int) ? MilvusDataType.Int32
: type == typeof(long) ? MilvusDataType.Int64
: type == typeof(float) ? MilvusDataType.Float
: type == typeof(double) ? MilvusDataType.Double
public static DataType GetDataType(Type type)
=> type == typeof(string) ? DataType.VarChar
: type == typeof(bool) ? DataType.Bool
: type == typeof(int) ? DataType.Int32
: type == typeof(long) ? DataType.Int64
: type == typeof(float) ? DataType.Float
: type == typeof(double) ? DataType.Double
: throw new NotSupportedException($"Unsupported Milvus field type '{type}'.");

internal static Type? GetElementType(Type type)
Expand All @@ -41,45 +41,56 @@ static object ReadArray<T>(object value, bool array)
=> array ? ((IEnumerable<T>)value).ToArray() : ((IEnumerable<T>)value).ToList();
}

internal static IReadOnlyList<FieldData> CreateColumns(CollectionModel model, IReadOnlyList<IDictionary<string, object?>> rows)
/// <summary>
/// Turns the columns of a query or search response into rows keyed by field name.
/// </summary>
internal static List<Dictionary<string, object?>> ReadRows(IReadOnlyList<FieldData> columns)
{
List<FieldData> fields = [];
var key = model.KeyProperty;
fields.Add(key.Type == typeof(long) ? Scalar<long>(key.StorageName) : Scalar<string>(key.StorageName));
foreach (var property in model.DataProperties)
var count = columns.Count == 0 ? 0 : columns.Max(c => c.RowCount);
var rows = new List<Dictionary<string, object?>>(count);
for (var i = 0; i < count; i++)
{
var name = property.StorageName;
if (GetElementType(property.Type) is { } element)
var row = new Dictionary<string, object?>(StringComparer.Ordinal);
foreach (var column in columns)
{
fields.Add(element == typeof(string) ? ArrayColumn<string>(name)
: element == typeof(bool) ? ArrayColumn<bool>(name)
: element == typeof(int) ? ArrayColumn<int>(name)
: element == typeof(long) ? ArrayColumn<long>(name)
: element == typeof(float) ? ArrayColumn<float>(name)
: element == typeof(double) ? ArrayColumn<double>(name)
: throw new NotSupportedException($"Unsupported array element type '{element}'."));
}
else
{
var type = property.Type;
fields.Add(type == typeof(string) ? Scalar<string?>(name)
: type == typeof(bool) ? Scalar<bool>(name) : type == typeof(bool?) ? Scalar<bool?>(name)
: type == typeof(int) ? Scalar<int>(name) : type == typeof(int?) ? Scalar<int?>(name)
: type == typeof(long) ? Scalar<long>(name) : type == typeof(long?) ? Scalar<long?>(name)
: type == typeof(float) ? Scalar<float>(name) : type == typeof(float?) ? Scalar<float?>(name)
: type == typeof(double) ? Scalar<double>(name) : type == typeof(double?) ? Scalar<double?>(name)
: throw new NotSupportedException($"Unsupported Milvus data type '{type}'."));
if (column.FieldName.Length > 0 && i < column.RowCount)
{
row[column.FieldName] = ReadCell(column, i);
}
}
rows.Add(row);
}
foreach (var property in model.VectorProperties)
return rows;
}

private static object? ReadCell(FieldData column, int index)
{
if (column.ValidData is { } valid && !valid[index])
{
fields.Add(FieldData.CreateFloatVector(property.StorageName, rows.Select(r => (ReadOnlyMemory<float>)r[property.StorageName]!).ToArray()));
return null;
}
return fields;

FieldData Scalar<T>(string name) => FieldData.Create(name, rows.Select(r => (T)r[name]!).ToArray());
FieldData ArrayColumn<T>(string name) => FieldData.CreateArray<T>(name,
rows.Select(r => r[name] is { } value ? (IReadOnlyList<T>)((IEnumerable<T>)value).ToArray() : null).ToArray());
return column switch
{
FieldData<string> f => f.Data[index],
FieldData<bool> f => f.Data[index],
FieldData<bool?> f => f.Data[index],
FieldData<int> f => f.Data[index],
FieldData<int?> f => f.Data[index],
FieldData<long> f => f.Data[index],
FieldData<long?> f => f.Data[index],
FieldData<float> f => f.Data[index],
FieldData<float?> f => f.Data[index],
FieldData<double> f => f.Data[index],
FieldData<double?> f => f.Data[index],
FieldData<ReadOnlyMemory<float>> f => f.Data[index],
FieldData<IReadOnlyList<string>?> f => f.Data[index],
FieldData<IReadOnlyList<bool>?> f => f.Data[index],
FieldData<IReadOnlyList<int>?> f => f.Data[index],
FieldData<IReadOnlyList<long>?> f => f.Data[index],
FieldData<IReadOnlyList<float>?> f => f.Data[index],
FieldData<IReadOnlyList<double>?> f => f.Data[index],
_ => throw new NotSupportedException($"Unsupported Milvus field data '{column.GetType()}' for field '{column.FieldName}'."),
};
}

public static object ToKey(object key) => key is Guid guid ? guid.ToString("D") : key;
Expand Down
Loading