├── .editorconfig
├── .gitattributes
├── .github
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
└── workflows
│ ├── Build.yml
│ └── NugetPublish.yml
├── .gitignore
├── .gitmodules
├── .vscode
└── settings.json
├── Changelog.md
├── Directory.Build.props
├── Directory.Packages.props
├── LICENSE
├── Milvus.Client.Tests
├── AliasTests.cs
├── CollectionTests.cs
├── DataTests.cs
├── DatabaseTests.cs
├── FieldTests.cs
├── IndexTests.cs
├── Milvus.Client.Tests.csproj
├── MilvusFixture.cs
├── MiscTests.cs
├── PartitionTests.cs
├── SearchQueryIteratorLongKeyTests.cs
├── SearchQueryIteratorStringKeyTests.cs
├── SearchQueryTests.cs
├── TimestampUtilsTests.cs
├── UserTests.cs
└── Utils.cs
├── Milvus.Client.sln
├── Milvus.Client.sln.DotSettings
├── Milvus.Client
├── .editorconfig
├── ArrayFieldData.cs
├── BinaryVectorFieldData.cs
├── ByteStringFieldData.cs
├── CollectionFilter.cs
├── CollectionSchema.cs
├── CompactionPlans.cs
├── CompactionState.cs
├── ConsistencyLevel.cs
├── Constants.cs
├── Diagnostics
│ ├── CompilerAttributes.cs
│ ├── Logging.cs
│ ├── NullableAttributes.cs
│ └── Verify.cs
├── FieldData.cs
├── FieldSchema.cs
├── FieldState.cs
├── FloatVectorFieldData.cs
├── FlushResult.cs
├── GrantResult.cs
├── HealthState.cs
├── IndexBuildProgress.cs
├── IndexState.cs
├── IndexType.cs
├── Milvus.Client.csproj
├── MilvusClient.Alias.cs
├── MilvusClient.Collection.cs
├── MilvusClient.Compaction.cs
├── MilvusClient.Database.cs
├── MilvusClient.Entity.cs
├── MilvusClient.Metrics.cs
├── MilvusClient.Role.cs
├── MilvusClient.User.cs
├── MilvusClient.cs
├── MilvusCollection.Collection.cs
├── MilvusCollection.Entity.cs
├── MilvusCollection.Index.cs
├── MilvusCollection.Partition.cs
├── MilvusCollection.cs
├── MilvusCollectionDescription.cs
├── MilvusCollectionInfo.cs
├── MilvusDataType.cs
├── MilvusErrorCode.cs
├── MilvusException.cs
├── MilvusIds.cs
├── MilvusIndexInfo.cs
├── MilvusMetrics.cs
├── MilvusPartition.cs
├── MilvusTimestampUtils.cs
├── MutationResult.cs
├── PersistentSegmentInfo.cs
├── QueryParameters.cs
├── QuerySegmentResult.cs
├── RoleResult.cs
├── SearchParameters.cs
├── SearchResults.cs
├── SegmentState.cs
├── SimilarityMetricType.cs
├── UserResult.cs
└── Utils.cs
├── README.md
├── Version.props
├── docs
├── api_reference
│ ├── Alias
│ │ ├── AlterAliasAsync().md
│ │ ├── CreateAliasAsync().md
│ │ └── DropAliasAsync().md
│ ├── Collection
│ │ ├── CompactAsync().md
│ │ ├── DeleteAsync().md
│ │ ├── DescribeAsync().md
│ │ ├── DropAsync().md
│ │ ├── FlushAsync().md
│ │ ├── GetEntityCountAsync().md
│ │ ├── GetLoadingProgressAsync().md
│ │ ├── InsertAsync().md
│ │ ├── LoadAsync().md
│ │ ├── QueryAsync().md
│ │ ├── ReleaseAsync().md
│ │ ├── RenameAsync().md
│ │ ├── SearchAsync().md
│ │ └── WaitForCollectionLoadAsync().md
│ ├── Database
│ │ ├── CreateDatabaseAsync().md
│ │ ├── DropDatabaseAsync().md
│ │ └── ListDatabasesAsync().md
│ ├── Index
│ │ ├── CreateIndexAsync().md
│ │ ├── DescribeIndexAsync().md
│ │ ├── DropIndexAsync().md
│ │ ├── GetIndexBuildProgressAsync().md
│ │ ├── GetIndexStateAsync().md
│ │ └── WaitForIndexBuildAsync().md
│ ├── Partition
│ │ ├── CreatePartitionAsync().md
│ │ ├── DropPartitionAsync().md
│ │ ├── GetPartitionStatisticsAsync().md
│ │ ├── HasPartitionAsync().md
│ │ ├── LoadPartitionAsync().md
│ │ ├── LoadPartitionsAsync().md
│ │ ├── ReleasePartitionAsync().md
│ │ ├── ReleasePartitionsAsync().md
│ │ └── ShowPartitionsAsync().md
│ └── Role
│ │ ├── AddUserToRoleAsync().md
│ │ ├── CreateRoleAsync().md
│ │ ├── DropRoleAsync().md
│ │ ├── GrantRolePrivilegeAsync().md
│ │ ├── ListGrantsForRoleAsync().md
│ │ ├── RemoveUserFromRoleAsync().md
│ │ ├── RevokeRolePrivilegeAsync().md
│ │ ├── SelectAllRolesAsync().md
│ │ ├── SelectAllUsersAsync().md
│ │ ├── SelectGrantForRoleAndObjectAsync().md
│ │ ├── SelectRoleAsync().md
│ │ └── SelectUserAsync().md
├── notebooks
│ ├── 00.Settings.ipynb
│ ├── 01.Connect to milvus.ipynb
│ ├── 02.Create a Collection.ipynb
│ ├── 03.Create a Partition.ipynb
│ ├── 04.Insert Vectors.ipynb
│ ├── 05.Build an Index on Vectors.ipynb
│ ├── 06.Search.ipynb
│ ├── 07.Query.ipynb
│ ├── config
│ │ ├── .gitignore
│ │ ├── Settings.cs
│ │ └── settings.example.zilliz.json
│ └── resources
│ │ └── zilliz.svg
├── readme.md
├── restful-api.html
└── user_guide
│ ├── manage_collections.md
│ ├── manage_data.md
│ ├── manage_databases.md
│ ├── manage_indexes.md
│ ├── manage_milvus_connections.md
│ ├── manage_partitions.md
│ └── search_and_query.md
├── global.json
├── milvussharp.png
├── nuget.config
└── resources
└── workbench.png
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Set default behavior to automatically normalize line endings.
2 | * text=auto
3 |
4 | *.cs text=auto diff=csharp
5 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Desktop (please complete the following information):**
27 | - OS: [e.g. iOS]
28 | - Browser [e.g. chrome, safari]
29 | - Version [e.g. 22]
30 |
31 | **Smartphone (please complete the following information):**
32 | - Device: [e.g. iPhone6]
33 | - OS: [e.g. iOS8.1]
34 | - Browser [e.g. stock browser, safari]
35 | - Version [e.g. 22]
36 |
37 | **Additional context**
38 | Add any other context about the problem here.
39 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/.github/workflows/Build.yml:
--------------------------------------------------------------------------------
1 | name: Build
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 | pull_request:
8 |
9 | jobs:
10 | build:
11 | runs-on: ubuntu-latest
12 |
13 | strategy:
14 | matrix:
15 | milvus_version: [v2.3.10, v2.4.0-rc.1]
16 |
17 | steps:
18 | - name: Checkout
19 | uses: actions/checkout@v3
20 | with:
21 | submodules: 'recursive'
22 | fetch-depth: 0
23 |
24 | - name: Setup .NET SDKs
25 | uses: actions/setup-dotnet@v3
26 |
27 | - name: Test
28 | run: dotnet test --logger "GitHubActions;report-warnings=false"
29 | env:
30 | MILVUS_IMAGE: milvusdb/milvus:${{ matrix.milvus_version }}
31 |
32 | - name: Pack
33 | run: dotnet pack -c Release -o Artifacts
34 |
35 | - name: Upload artifacts (nupkg)
36 | uses: actions/upload-artifact@v3
37 | with:
38 | name: nupkgs
39 | path: |
40 | Artifacts/*.nupkg
41 | Artifacts/*.snupkg
42 |
43 |
--------------------------------------------------------------------------------
/.github/workflows/NugetPublish.yml:
--------------------------------------------------------------------------------
1 | name: Publish to nuget.org
2 |
3 | on:
4 | push:
5 | tags:
6 | - '*'
7 |
8 | jobs:
9 | build:
10 | runs-on: ubuntu-latest
11 |
12 | steps:
13 | - name: Checkout
14 | uses: actions/checkout@v3
15 | with:
16 | submodules: 'recursive'
17 | fetch-depth: 0
18 |
19 | - name: Setup .NET SDKs
20 | uses: actions/setup-dotnet@v3
21 |
22 | # https://github.com/dotnet-campus/dotnetCampus.TagToVersion
23 | - name: Install dotnet tool
24 | run: dotnet tool install -g dotnetCampus.TagToVersion
25 |
26 | - name: Set tag to version
27 | run: dotnet TagToVersion -t ${{ github.ref }} -f Version.props
28 |
29 | - name: Build
30 | run: dotnet build -c Release
31 |
32 | - name: Pack
33 | run: dotnet pack -c Release -o Artifacts
34 |
35 | - name: Upload artifacts (nupkg)
36 | uses: actions/upload-artifact@v3
37 | with:
38 | name: nupkgs
39 | path: |
40 | Artifacts/*.nupkg
41 | Artifacts/*.snupkg
42 |
43 | - name: Publish to nuget.org
44 | run: dotnet nuget push Artifacts/*.nupkg --api-key ${{ secrets.NugetKey }} --source https://api.nuget.org/v3/index.json
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "src/Milvus.Client/Protos"]
2 | path = Milvus.Client/Protos
3 | url = https://github.com/milvus-io/milvus-proto.git
4 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "dotnet.defaultSolution": "Milvus.Client.sln"
3 | }
4 |
--------------------------------------------------------------------------------
/Changelog.md:
--------------------------------------------------------------------------------
1 | - 2023-6-25 **2.2.1-beta.9**
2 | - Support Json field(grpcclient only)(#19).
3 | - Support PartitionKey(grpcclient only)(#19).
4 | - Support IsDynamic(grpcclient only)(#19).
5 | - Support RBAC api(grpcclient only)(#19).
6 | - Support Database(grpcclient only)(#19).
7 | - Fix extraparam null issue(#19).
8 | - Fix autoid issue(#19).
9 | - 2023-6-05 **2.2.1-alpha.8**
10 | - Fix float vector field dim split error
11 | - Add isdynamic and ispartitionkey to fieldType
12 | - - 2023-6-05 **2.2.1-alpha.7**
13 | - add WaitForLoadingProgressCollectionAsync and WaitForLoadingProgressCollectionValueAsync methods.
14 | - 2023-06-04 **2.2.1-alpha.6**
15 | - Fix field json convert error when query.
16 | - 2023-06-04 **2.2.1-alpha.5**
17 | - Support restful client and grpc client.
18 | - Fix load partition error
19 | - Fix #14 about json format error when use restful client.
--------------------------------------------------------------------------------
/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | latest
5 | true
6 | enable
7 | latest
8 | enable
9 |
10 | true
11 | true
12 | snupkg
13 | true
14 | true
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/Directory.Packages.props:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/Milvus.Client.Tests/AliasTests.cs:
--------------------------------------------------------------------------------
1 | using Xunit;
2 |
3 | namespace Milvus.Client.Tests;
4 |
5 | [Collection("Milvus")]
6 | public class AliasTests : IAsyncLifetime
7 | {
8 | [Fact]
9 | public async Task Create()
10 | {
11 | await Client.CreateAliasAsync(CollectionName, "a");
12 | await Client.CreateAliasAsync(CollectionName, "b");
13 |
14 | var description = await Collection.DescribeAsync();
15 | Assert.Collection(description.Aliases.Order(),
16 | alias => Assert.Equal("a", alias),
17 | alias => Assert.Equal("b", alias));
18 | }
19 |
20 | // [Fact]
21 | // public async Task Alter()
22 | // {
23 | // await Client.CreateAliasAsync(CollectionName, "a");
24 | //
25 | // await Client.DropCollectionAsync("AnotherCollection");
26 | // await Client.CreateCollectionAsync(
27 | // "AnotherCollection",
28 | // new[] { FieldSchema.Create("id", isPrimaryKey: true) });
29 | //
30 | // await Client.AlterAliasAsync("AnotherCollection", "a");
31 | //
32 | // var description1 = await Client.DescribeCollectionAsync(CollectionName);
33 | // Assert.DoesNotContain(description1.Aliases, alias => alias == "a");
34 | //
35 | // var description2 = await Client.DescribeCollectionAsync("AnotherCollection");
36 | // Assert.Collection(description2.Aliases, alias => Assert.Equal("a", alias));
37 | // }
38 |
39 | [Fact]
40 | public async Task Drop()
41 | {
42 | await Client.CreateAliasAsync(CollectionName, "a");
43 |
44 | await Client.DropAliasAsync("a");
45 |
46 | var description = await Collection.DescribeAsync();
47 | Assert.DoesNotContain(description.Aliases, alias => alias == "a");
48 | }
49 |
50 | public string CollectionName = nameof(AliasTests);
51 |
52 | private MilvusCollection Collection { get; set; }
53 |
54 | public AliasTests(MilvusFixture milvusFixture)
55 | {
56 | Client = milvusFixture.CreateClient();
57 | Collection = Client.GetCollection(CollectionName);
58 | }
59 |
60 | public async Task InitializeAsync()
61 | {
62 | await Client.DropAliasAsync("a");
63 | await Client.DropAliasAsync("b");
64 |
65 | await Collection.DropAsync();
66 | Collection = await Client.CreateCollectionAsync(
67 | CollectionName,
68 | new[]
69 | {
70 | FieldSchema.Create("id", isPrimaryKey: true),
71 | FieldSchema.CreateVarchar("varchar", 256),
72 | FieldSchema.CreateFloatVector("float_vector", 2)
73 | });
74 | }
75 |
76 | private readonly MilvusClient Client;
77 |
78 | public Task DisposeAsync()
79 | {
80 | Client.Dispose();
81 | return Task.CompletedTask;
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/Milvus.Client.Tests/DatabaseTests.cs:
--------------------------------------------------------------------------------
1 | using Xunit;
2 |
3 | namespace Milvus.Client.Tests;
4 |
5 | [Collection("Milvus")]
6 | public class DatabaseTests(MilvusFixture milvusFixture) : IAsyncLifetime
7 | {
8 | [Fact]
9 | public async Task Create_List_Drop()
10 | {
11 | Assert.DoesNotContain(DatabaseName, await DefaultClient.ListDatabasesAsync());
12 |
13 | await DefaultClient.CreateDatabaseAsync(DatabaseName);
14 |
15 | Assert.Contains(DatabaseName, await DefaultClient.ListDatabasesAsync());
16 |
17 | MilvusCollection collection = await DatabaseClient.CreateCollectionAsync(
18 | "foo",
19 | new[] { FieldSchema.Create("id", isPrimaryKey: true) });
20 |
21 | // The collection should be visible on the database-bound client, but not on the default client.
22 | Assert.True(await DatabaseClient.HasCollectionAsync("foo"));
23 | Assert.False(await DefaultClient.HasCollectionAsync("foo"));
24 |
25 | await collection.DropAsync();
26 | await DatabaseClient.DropDatabaseAsync(DatabaseName);
27 |
28 | await Assert.ThrowsAsync(() =>
29 | DatabaseClient.CreateCollectionAsync(
30 | "foo",
31 | new[] { FieldSchema.Create("id", isPrimaryKey: true) }));
32 | Assert.DoesNotContain(DatabaseName, await DefaultClient.ListDatabasesAsync());
33 | }
34 |
35 | [Fact]
36 | public async Task Search_on_non_default_database()
37 | {
38 | string databaseName = nameof(Search_on_non_default_database);
39 |
40 | using var databaseClient = milvusFixture.CreateClient(databaseName);
41 |
42 | // If the database exists, drop it using the regular client and recreate it.
43 | if ((await DefaultClient.ListDatabasesAsync()).Contains(databaseName))
44 | {
45 | foreach (MilvusCollectionInfo collectionInfo in await databaseClient.ListCollectionsAsync())
46 | {
47 | await databaseClient.GetCollection(collectionInfo.Name).DropAsync();
48 | }
49 |
50 | await DefaultClient.DropDatabaseAsync(databaseName);
51 | }
52 |
53 | await DefaultClient.CreateDatabaseAsync(nameof(Search_on_non_default_database));
54 | MilvusCollection collection = await databaseClient.CreateCollectionAsync(
55 | "coll",
56 | new[]
57 | {
58 | FieldSchema.Create("id", isPrimaryKey: true),
59 | FieldSchema.CreateVarchar("varchar", 256),
60 | FieldSchema.CreateFloatVector("float_vector", 2)
61 | });
62 |
63 | await collection.CreateIndexAsync(
64 | "float_vector", IndexType.Flat, SimilarityMetricType.L2, "float_vector_idx", new Dictionary());
65 |
66 | long[] ids = { 1, 2, 3, 4, 5 };
67 | string[] strings = { "one", "two", "three", "four", "five" };
68 | ReadOnlyMemory[] floatVectors =
69 | {
70 | new[] { 1f, 2f },
71 | new[] { 3.5f, 4.5f },
72 | new[] { 5f, 6f },
73 | new[] { 7.7f, 8.8f },
74 | new[] { 9f, 10f }
75 | };
76 |
77 | await collection.InsertAsync(
78 | new FieldData[]
79 | {
80 | FieldData.Create("id", ids),
81 | FieldData.Create("varchar", strings),
82 | FieldData.CreateFloatVector("float_vector", floatVectors)
83 | });
84 |
85 | await collection.LoadAsync();
86 | await collection.WaitForCollectionLoadAsync(
87 | waitingInterval: TimeSpan.FromMilliseconds(100), timeout: TimeSpan.FromMinutes(1));
88 |
89 | var results = await collection.SearchAsync(
90 | "float_vector",
91 | new ReadOnlyMemory[] { new[] { 0.1f, 0.2f } },
92 | SimilarityMetricType.L2,
93 | limit: 2);
94 |
95 | Assert.Equal(collection.Name, results.CollectionName);
96 | Assert.Empty(results.FieldsData);
97 | Assert.Collection(results.Ids.LongIds!,
98 | id => Assert.Equal(1, id),
99 | id => Assert.Equal(2, id));
100 | Assert.Null(results.Ids.StringIds);
101 | Assert.Equal(1, results.NumQueries);
102 | Assert.Equal(2, results.Scores.Count);
103 | Assert.Equal(2, results.Limit);
104 | Assert.Collection(results.Limits, l => Assert.Equal(2, l));
105 | }
106 |
107 | public async Task InitializeAsync()
108 | {
109 | if ((await DefaultClient.ListDatabasesAsync()).Contains(DatabaseName))
110 | {
111 | // First drop all collections from a possible previous test run, otherwise dropping fails
112 | foreach (var collection in await DatabaseClient.ListCollectionsAsync())
113 | {
114 | await DatabaseClient.GetCollection(collection.Name).DropAsync();
115 | }
116 |
117 | await DefaultClient.DropDatabaseAsync(DatabaseName);
118 | }
119 | }
120 |
121 | public Task DisposeAsync()
122 | {
123 | DefaultClient.Dispose();
124 | DatabaseClient.Dispose();
125 | return Task.CompletedTask;
126 | }
127 |
128 | private readonly MilvusClient DefaultClient = milvusFixture.CreateClient();
129 | private readonly MilvusClient DatabaseClient = milvusFixture.CreateClient(DatabaseName);
130 |
131 | private const string DatabaseName = nameof(DatabaseTests);
132 | }
133 |
--------------------------------------------------------------------------------
/Milvus.Client.Tests/Milvus.Client.Tests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net7.0
5 | false
6 | $(NoWarn);CA1062
7 |
8 |
9 |
10 |
11 |
12 |
13 | runtime; build; native; contentfiles; analyzers; buildtransitive
14 | all
15 |
16 |
17 | runtime; build; native; contentfiles; analyzers; buildtransitive
18 | all
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/Milvus.Client.Tests/MilvusFixture.cs:
--------------------------------------------------------------------------------
1 | using Testcontainers.Milvus;
2 | using Xunit;
3 |
4 | namespace Milvus.Client.Tests;
5 |
6 | [CollectionDefinition("Milvus")]
7 | public sealed class MilvusTestCollection : ICollectionFixture;
8 |
9 | public sealed class MilvusFixture : IAsyncLifetime
10 | {
11 | private const string DefaultMilvusImage = "milvusdb/milvus:v2.4.0-rc.1";
12 |
13 | private readonly MilvusContainer _container = new MilvusBuilder()
14 | .WithImage(Environment.GetEnvironmentVariable("MILVUS_IMAGE") ?? DefaultMilvusImage)
15 | .Build();
16 |
17 | public string Host => _container.Hostname;
18 | public int Port => _container.GetMappedPublicPort(MilvusBuilder.MilvusGrpcPort);
19 | public string Username => "root";
20 | public string Password => "Milvus";
21 |
22 | public MilvusClient CreateClient()
23 | => new(Host, Username, Password, Port, ssl: false);
24 |
25 | public MilvusClient CreateClient(string database)
26 | => new(Host, Username, Password, Port, ssl: false, database);
27 |
28 | public Task InitializeAsync() => _container.StartAsync();
29 | public Task DisposeAsync() => _container.DisposeAsync().AsTask();
30 | }
31 |
--------------------------------------------------------------------------------
/Milvus.Client.Tests/MiscTests.cs:
--------------------------------------------------------------------------------
1 | using Grpc.Core;
2 | using Xunit;
3 |
4 | namespace Milvus.Client.Tests;
5 |
6 | [Collection("Milvus")]
7 | public class MiscTests(MilvusFixture milvusFixture) : IDisposable
8 | {
9 | // If this test is failing for you, that means you haven't enabled authorization in Milvus; follow the instructions
10 | // in https://milvus.io/docs/authenticate.md.
11 | [Fact]
12 | public async Task Auth_failure_with_wrong_password()
13 | {
14 | using var badClient = new MilvusClient(
15 | milvusFixture.Host, username: milvusFixture.Username, password: "incorrect_password");
16 |
17 | try
18 | {
19 | await badClient.GetCollection("foo").DropAsync();
20 |
21 | if (Environment.GetEnvironmentVariable("CI") != null)
22 | {
23 | Assert.Fail("Authorization seems to be disabled in Milvus; follow the instructions in https://milvus.io/docs/authenticate.md");
24 | }
25 | }
26 | catch (RpcException) // TODO: We should maybe catch the RpcException and rethrow a MilvusException instead
27 | {
28 | // Expected behavior
29 | }
30 | }
31 |
32 | [Fact]
33 | public async Task HealthTest()
34 | {
35 | MilvusHealthState result = await Client.HealthAsync();
36 | Assert.True(result.IsHealthy, result.ToString());
37 | }
38 |
39 | [Fact]
40 | public async Task GetVersion()
41 | {
42 | string version = await Client.GetVersionAsync();
43 |
44 | Assert.NotEmpty(version);
45 | }
46 |
47 | [Fact]
48 | public async Task Dispose_client()
49 | {
50 | MilvusHealthState state = await Client.HealthAsync();
51 | Assert.True(state.IsHealthy);
52 |
53 | Client.Dispose();
54 |
55 | await Assert.ThrowsAsync(() => Client.HealthAsync());
56 | }
57 |
58 | private readonly MilvusClient Client = milvusFixture.CreateClient();
59 |
60 | public void Dispose() => Client.Dispose();
61 | }
62 |
--------------------------------------------------------------------------------
/Milvus.Client.Tests/PartitionTests.cs:
--------------------------------------------------------------------------------
1 | using Xunit;
2 |
3 | namespace Milvus.Client.Tests;
4 |
5 | [Collection("Milvus")]
6 | public class PartitionTests : IAsyncLifetime
7 | {
8 | [Fact]
9 | public async Task Create()
10 | {
11 | await Collection.CreatePartitionAsync("partition");
12 | }
13 |
14 | [Fact]
15 | public async Task Exists()
16 | {
17 | await Collection.CreatePartitionAsync("partition");
18 | Assert.True(await Collection.HasPartitionAsync("partition"));
19 | }
20 |
21 | [Fact]
22 | public async Task List()
23 | {
24 | await Collection.CreatePartitionAsync("partition1");
25 | await Collection.CreatePartitionAsync("partition2");
26 |
27 | var partitions = await Collection.ShowPartitionsAsync();
28 |
29 | Assert.Contains(partitions, p => p.PartitionName == "partition1");
30 | Assert.Contains(partitions, p => p.PartitionName == "partition2");
31 | }
32 |
33 | [Fact]
34 | public async Task Load_and_Release()
35 | {
36 | await Collection.CreatePartitionAsync("partition");
37 | await Collection.CreateIndexAsync(
38 | "float_vector", IndexType.Flat, SimilarityMetricType.L2, "float_vector_idx", new Dictionary());
39 | await Collection.WaitForIndexBuildAsync("float_vector");
40 |
41 | await Collection.LoadPartitionsAsync(new[] { "partition" });
42 | await Collection.ReleasePartitionsAsync(new[] { "partition" });
43 | }
44 |
45 | [Fact]
46 | public async Task Drop()
47 | {
48 | await Collection.DropPartitionAsync("partition");
49 | Assert.False(await Collection.HasPartitionAsync("partition"));
50 | }
51 |
52 | public PartitionTests(MilvusFixture milvusFixture)
53 | {
54 | Client = milvusFixture.CreateClient();
55 | Collection = Client.GetCollection(CollectionName);
56 | }
57 |
58 | public async Task InitializeAsync()
59 | {
60 | await Collection.DropAsync();
61 | await Client.CreateCollectionAsync(
62 | CollectionName,
63 | new[]
64 | {
65 | FieldSchema.Create("id", isPrimaryKey: true),
66 | FieldSchema.CreateVarchar("varchar", 256),
67 | FieldSchema.CreateFloatVector("float_vector", 4),
68 | });
69 | }
70 |
71 | public Task DisposeAsync()
72 | {
73 | Client.Dispose();
74 | return Task.CompletedTask;
75 | }
76 |
77 | private const string CollectionName = nameof(PartitionTests);
78 | private readonly MilvusClient Client;
79 |
80 | private MilvusCollection Collection { get; }
81 | }
82 |
--------------------------------------------------------------------------------
/Milvus.Client.Tests/TimestampUtilsTests.cs:
--------------------------------------------------------------------------------
1 | using Xunit;
2 |
3 | namespace Milvus.Client.Tests;
4 |
5 | public class TimestampUtilsTests
6 | {
7 | [Fact]
8 | public void ToDateTime_returns_utc_DateTime()
9 | => Assert.Equal(DateTimeKind.Utc, MilvusTimestampUtils.ToDateTime(0).Kind);
10 |
11 | [Fact]
12 | public void FromDateTime_with_non_utc_DateTime_throws()
13 | => Assert.Throws(() =>
14 | MilvusTimestampUtils.FromDateTime(new DateTime(2020, 1, 1, 12, 0, 0, DateTimeKind.Local)));
15 |
16 | [Fact]
17 | public void Can_roundtrip_down_to_milliseconds()
18 | {
19 | var dateTimeWithMilliseconds = new DateTime(2020, 1, 1, 12, 0, 0, 123, DateTimeKind.Utc);
20 | var dateTimeWithMicroseconds = new DateTime(2020, 1, 1, 12, 0, 0, 123, 456, DateTimeKind.Utc);
21 |
22 | ulong milvusTimestamp = MilvusTimestampUtils.FromDateTime(dateTimeWithMicroseconds);
23 | Assert.Equal(dateTimeWithMilliseconds, MilvusTimestampUtils.ToDateTime(milvusTimestamp));
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Milvus.Client.Tests/Utils.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client.Tests;
2 |
3 | public static class Utils
4 | {
5 | public static async Task GetParsedMilvusVersion(this MilvusClient client)
6 | {
7 | string version = await client.GetVersionAsync();
8 |
9 | if (version.StartsWith("v", StringComparison.Ordinal))
10 | {
11 | version = version[1..];
12 | }
13 |
14 | int dash = version.IndexOf('-');
15 | if (dash != -1)
16 | {
17 | version = version[..dash];
18 | }
19 |
20 | return Version.Parse(version);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Milvus.Client.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.2.32526.322
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Milvus.Client", "Milvus.Client\Milvus.Client.csproj", "{B580F531-D699-475D-AB09-9D6979DDE4D7}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Milvus.Client.Tests", "Milvus.Client.Tests\Milvus.Client.Tests.csproj", "{A7A92847-F38D-4F27-AB11-5EF4BF0822E8}"
9 | EndProject
10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{9BA6CDDC-9D2A-429F-9244-B9615BB1B107}"
11 | ProjectSection(SolutionItems) = preProject
12 | .editorconfig = .editorconfig
13 | .github\workflows\Build.yml = .github\workflows\Build.yml
14 | Directory.Build.props = Directory.Build.props
15 | Directory.Packages.props = Directory.Packages.props
16 | .github\workflows\NugetPublish.yml = .github\workflows\NugetPublish.yml
17 | EndProjectSection
18 | EndProject
19 | Global
20 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
21 | Debug|Any CPU = Debug|Any CPU
22 | Release|Any CPU = Release|Any CPU
23 | EndGlobalSection
24 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
25 | {B580F531-D699-475D-AB09-9D6979DDE4D7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
26 | {B580F531-D699-475D-AB09-9D6979DDE4D7}.Debug|Any CPU.Build.0 = Debug|Any CPU
27 | {B580F531-D699-475D-AB09-9D6979DDE4D7}.Release|Any CPU.ActiveCfg = Release|Any CPU
28 | {B580F531-D699-475D-AB09-9D6979DDE4D7}.Release|Any CPU.Build.0 = Release|Any CPU
29 | {A7A92847-F38D-4F27-AB11-5EF4BF0822E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
30 | {A7A92847-F38D-4F27-AB11-5EF4BF0822E8}.Debug|Any CPU.Build.0 = Debug|Any CPU
31 | {A7A92847-F38D-4F27-AB11-5EF4BF0822E8}.Release|Any CPU.ActiveCfg = Release|Any CPU
32 | {A7A92847-F38D-4F27-AB11-5EF4BF0822E8}.Release|Any CPU.Build.0 = Release|Any CPU
33 | EndGlobalSection
34 | GlobalSection(SolutionProperties) = preSolution
35 | HideSolutionNode = FALSE
36 | EndGlobalSection
37 | GlobalSection(ExtensibilityGlobals) = postSolution
38 | SolutionGuid = {FD71787C-3A9C-44DD-AAC4-D372BCD88452}
39 | EndGlobalSection
40 | EndGlobal
41 |
--------------------------------------------------------------------------------
/Milvus.Client.sln.DotSettings:
--------------------------------------------------------------------------------
1 |
2 | 1
3 | True
4 | True
5 | True
6 | True
7 | True
8 | True
9 | True
10 | True
11 | True
12 | True
13 | True
14 | True
--------------------------------------------------------------------------------
/Milvus.Client/.editorconfig:
--------------------------------------------------------------------------------
1 | [*.cs]
2 |
3 | # CA2007: Consider calling ConfigureAwait on the awaited task
4 | # We put it here because we don't want to enable it for the tests
5 | dotnet_diagnostic.CA2007.severity = warning
6 |
--------------------------------------------------------------------------------
/Milvus.Client/BinaryVectorFieldData.cs:
--------------------------------------------------------------------------------
1 | using System.Buffers;
2 | using System.Diagnostics;
3 |
4 | namespace Milvus.Client;
5 |
6 | ///
7 | /// Binary Field
8 | ///
9 | public sealed class BinaryVectorFieldData : FieldData>
10 | {
11 | ///
12 | /// Construct a binary vector field
13 | ///
14 | ///
15 | ///
16 | public BinaryVectorFieldData(string fieldName, IReadOnlyList> bytes)
17 | : base(fieldName, bytes, MilvusDataType.BinaryVector, false)
18 | {
19 | }
20 |
21 | ///
22 | internal override Grpc.FieldData ToGrpcFieldData()
23 | {
24 | int dataCount = Data.Count;
25 | if (dataCount == 0)
26 | {
27 | throw new MilvusException("The number of vectors must be positive.");
28 | }
29 |
30 | int vectorByteLength = Data[0].Length;
31 | int totalByteLength = vectorByteLength;
32 | for (int i = 1; i < dataCount; i++)
33 | {
34 | int rowLength = Data[i].Length;
35 | if (rowLength != vectorByteLength)
36 | {
37 | throw new MilvusException("All vectors must have the same dimensionality.");
38 | }
39 |
40 | checked { totalByteLength += rowLength; }
41 | }
42 |
43 | byte[] bytes = ArrayPool.Shared.Rent(totalByteLength);
44 | int pos = 0;
45 | for (int i = 0; i < dataCount; i++)
46 | {
47 | ReadOnlyMemory row = Data[i];
48 | row.Span.CopyTo(bytes.AsSpan(pos, row.Length));
49 | pos += row.Length;
50 | }
51 | Debug.Assert(pos == totalByteLength);
52 |
53 | var result = new Grpc.FieldData
54 | {
55 | FieldName = FieldName,
56 | Type = (Grpc.DataType)DataType,
57 | Vectors = new Grpc.VectorField
58 | {
59 | BinaryVector = ByteString.CopyFrom(bytes.AsSpan(0, totalByteLength)),
60 | Dim = vectorByteLength * 8,
61 | }
62 | };
63 |
64 | ArrayPool.Shared.Return(bytes);
65 |
66 | return result;
67 | }
68 |
69 | internal override object GetValueAsObject(int index)
70 | => throw new NotSupportedException("Dynamic vector fields are not supported");
71 | }
72 |
--------------------------------------------------------------------------------
/Milvus.Client/ByteStringFieldData.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// ByteString Field
5 | ///
6 | public sealed class ByteStringFieldData : FieldData
7 | {
8 | ///
9 | /// Construct a ByteString field
10 | ///
11 | public ByteStringFieldData(
12 | string fieldName,
13 | ByteString byteString,
14 | long dimension) :
15 | base(fieldName, MilvusDataType.BinaryVector)
16 | {
17 | DataType = MilvusDataType.BinaryVector;
18 | ByteString = byteString;
19 | RowCount = dimension;
20 | }
21 |
22 | ///
23 | /// ByteString
24 | ///
25 | public ByteString ByteString { get; set; }
26 |
27 | ///
28 | public override long RowCount { get; protected set; }
29 |
30 | ///
31 | internal override Grpc.FieldData ToGrpcFieldData()
32 | {
33 | return new Grpc.FieldData
34 | {
35 | FieldName = FieldName,
36 | Type = (Grpc.DataType)DataType,
37 | Vectors = new Grpc.VectorField
38 | {
39 | BinaryVector = ByteString,
40 | Dim = RowCount,
41 | }
42 | };
43 | }
44 |
45 | internal override object GetValueAsObject(int index)
46 | => throw new NotSupportedException("Dynamic ByteString fields are not supported");
47 | }
48 |
--------------------------------------------------------------------------------
/Milvus.Client/CollectionFilter.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// Determines which collection to return in an invocation of .
5 | ///
6 | public enum CollectionFilter
7 | {
8 | ///
9 | /// Lists all collections.
10 | ///
11 | All = 0,
12 |
13 | ///
14 | /// Lists only connections which have been loaded into memory.
15 | ///
16 | InMemory = 1,
17 | }
18 |
--------------------------------------------------------------------------------
/Milvus.Client/CollectionSchema.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 |
3 | namespace Milvus.Client;
4 | using System.Collections.Generic;
5 |
6 | ///
7 | /// The logical definition of a collection, describing the fields which make it up.
8 | ///
9 | [DebuggerDisplay("{DebuggerDisplay,nq}")]
10 | public sealed class CollectionSchema
11 | {
12 | private readonly List _fields = new();
13 |
14 | ///
15 | /// Instantiates a new .
16 | ///
17 | public CollectionSchema()
18 | {
19 | }
20 |
21 | internal CollectionSchema(IReadOnlyList fields)
22 | => _fields.AddRange(fields);
23 |
24 | ///
25 | /// The name of the collection.
26 | ///
27 | public string? Name { get; set; } // TODO: does the schema really have a name separate from the collection's?
28 |
29 | ///
30 | /// An optional description for the collection.
31 | ///
32 | public string? Description { get; set; }
33 |
34 | ///
35 | /// The fields which make up the schema of the collection.
36 | ///
37 | public IList Fields => _fields;
38 |
39 | ///
40 | /// Whether to enable dynamic fields for this schema. Defaults to false.
41 | ///
42 | ///
43 | ///
44 | ///
45 | public bool EnableDynamicFields { get; set; }
46 |
47 | // Note that an AutoId previously existed at the schema level, but is not deprecated.
48 | // AutoId is now only defined at the field level.
49 |
50 | private string DebuggerDisplay => $"{Name} ({Fields.Count} fields)";
51 | }
52 |
--------------------------------------------------------------------------------
/Milvus.Client/CompactionPlans.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// Milvus compaction plans.
5 | ///
6 | public sealed class CompactionPlans
7 | {
8 | internal CompactionPlans(IReadOnlyList plans, CompactionState state)
9 | {
10 | Plans = plans;
11 | State = state;
12 | }
13 |
14 | ///
15 | /// Merge infos.
16 | ///
17 | public IReadOnlyList Plans { get; }
18 |
19 | ///
20 | /// State.
21 | ///
22 | public CompactionState State { get; }
23 | }
24 |
25 | ///
26 | /// Milvus compaction plan.
27 | ///
28 | public sealed class MilvusCompactionPlan
29 | {
30 | ///
31 | /// Sources
32 | ///
33 | public required IReadOnlyList Sources { get; set; }
34 |
35 | ///
36 | /// Target
37 | ///
38 | public long Target { get; set; }
39 | }
40 |
--------------------------------------------------------------------------------
/Milvus.Client/CompactionState.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// The state of an compaction previously started via , returned by
5 | /// .
6 | ///
7 | public enum CompactionState
8 | {
9 | ///
10 | /// The provided compaction ID doesn't refer to a unknown compaction.
11 | ///
12 | Undefined = 0,
13 |
14 | ///
15 | /// The compaction is currently executing.
16 | ///
17 | Executing = 1,
18 |
19 | ///
20 | /// The compaction has completed.
21 | ///
22 | Completed = 2,
23 | }
24 |
--------------------------------------------------------------------------------
/Milvus.Client/ConsistencyLevel.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// The consistency level to be used by a Milvus collection.
5 | ///
6 | ///
7 | /// For more details, see .
8 | ///
9 | public enum ConsistencyLevel
10 | {
11 | ///
12 | /// The highest and the most strict level of consistency. This level ensures that users can read the latest
13 | /// version of data.
14 | ///
15 | Strong = 0,
16 |
17 | ///
18 | /// Ensures that all data writes can be immediately perceived in reads during the same session. In other
19 | /// words, when you write data via one client, the newly inserted data instantaneously become searchable.
20 | ///
21 | Session = 1,
22 |
23 | ///
24 | /// Allows data inconsistency during a certain period of time. However, generally, the data are always globally
25 | /// consistent out of that period of time.
26 | ///
27 | BoundedStaleness = 2,
28 |
29 | ///
30 | /// There is no guaranteed order of reads and writes, and replicas eventually converge to the same state given that
31 | /// no further write operations are done. Under this level, replicas start working on read requests with the latest
32 | /// updated values. Eventually consistent is the weakest of the four consistency levels.
33 | ///
34 | Eventually = 3,
35 |
36 | ///
37 | /// In this consistency level, users pass their own guarantee timestamp..
38 | ///
39 | Customized = 4
40 | }
41 |
--------------------------------------------------------------------------------
/Milvus.Client/Constants.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// Constant/static values for internal usage.
5 | ///
6 | internal static class Constants
7 | {
8 | ///
9 | /// Vector tag for
10 | ///
11 | internal const string VectorTag = "$0";
12 |
13 | ///
14 | /// Key name in parameters.
15 | ///
16 | internal const string VectorField = "anns_field";
17 |
18 | ///
19 | /// Key name in parameters.
20 | ///
21 | internal const string VectorDim = "dim";
22 |
23 | ///
24 | /// Key name in parameters.Indicate the max length of varchar datatype.
25 | ///
26 | internal const string VarcharMaxLength = "max_length";
27 |
28 | ///
29 | /// Top parameter key name.
30 | ///
31 | internal const string TopK = "topk";
32 |
33 | ///
34 | /// Top parameter key name.
35 | ///
36 | internal const string Offset = "offset";
37 |
38 | ///
39 | /// Top parameter key name.
40 | ///
41 | internal const string Limit = "limit";
42 |
43 | ///
44 | /// Top parameter key name.
45 | ///
46 | internal const string BatchSize = "batch_size";
47 |
48 | ///
49 | /// Top parameter key name.
50 | ///
51 | internal const string Iterator = "iterator";
52 |
53 | ///
54 | /// Top parameter key name.
55 | ///
56 | internal const string ReduceStopForBest = "reduce_stop_for_best";
57 |
58 | ///
59 | /// Key name in parameters.
60 | ///
61 | internal const string IndexType = "index_type";
62 |
63 | ///
64 | /// Key name in parameters.
65 | ///
66 | internal const string MetricType = "metric_type";
67 |
68 | ///
69 | /// Key name in search parameters.
70 | ///
71 | internal const string RoundDecimal = "round_decimal";
72 |
73 | ///
74 | /// Key name.
75 | ///
76 | internal const string Params = "params";
77 |
78 | ///
79 | /// Row count key name.
80 | ///
81 | internal const string RowCount = "row_count";
82 |
83 | ///
84 | /// Key name.
85 | ///
86 | internal const string Bucket = "bucket";
87 |
88 | ///
89 | /// Key name.
90 | ///
91 | internal const string FailedReason = "failed_reason";
92 |
93 | ///
94 | /// Key name.
95 | ///
96 | internal const string MaxCapacity = "max_capacity";
97 |
98 | ///
99 | /// Files.
100 | ///
101 | internal const string ImportFiles = "files";
102 |
103 | ///
104 | /// Collection.
105 | ///
106 | internal const string ImportCollection = "collection";
107 |
108 | ///
109 | /// Partition.
110 | ///
111 | internal const string ImportPartition = "partition";
112 |
113 | ///
114 | /// Default index name.
115 | ///
116 | internal const string DefaultIndexName = "_default_idx";
117 |
118 | ///
119 | /// Key name.
120 | ///
121 | internal const string IgnoreGrowing = "ignore_growing";
122 |
123 | ///
124 | /// Key name.
125 | ///
126 | internal const string GroupByField = "group_by_field";
127 |
128 | ///
129 | /// Default database name.
130 | ///
131 | internal const string DefaultDatabaseName = "default";
132 |
133 | ///
134 | /// max value for waiting loading collection/partition interval, unit: millisecond
135 | ///
136 | internal const long MaxWaitingLoadingInterval = 2000L;
137 |
138 | ///
139 | /// max value for waiting loading collection/partition timeout, unit: second
140 | ///
141 | internal const long MaxWaitingLoadingTimeout = 300L;
142 |
143 | ///
144 | /// max value for waiting flushing collection/partition interval, unit: millisecond
145 | ///
146 | internal const long MaxWaitingFlushingInterval = 2000L;
147 |
148 | ///
149 | /// max value for waiting flushing collection/partition timeout, unit: second
150 | ///
151 | internal const long MaxWaitingFlushingTimeout = 300L;
152 |
153 | ///
154 | /// max value for waiting create index interval, unit: millisecond
155 | ///
156 | internal const long MaxWaitingIndexInterval = 2000L;
157 |
158 | ///
159 | /// set this value for "withGuaranteeTimestamp" of QueryParam/SearchParam
160 | /// to instruct server execute query/search immediately.
161 | ///
162 | internal const long GuaranteeEventuallyTs = 1L;
163 |
164 | ///
165 | /// set this value for "withGuaranteeTimestamp" of QueryParam/SearchParam
166 | /// to instruct server execute query/search after all DML operations finished.
167 | ///
168 | internal const long GuaranteeStrongTs = 0L;
169 | }
170 |
--------------------------------------------------------------------------------
/Milvus.Client/Diagnostics/CompilerAttributes.cs:
--------------------------------------------------------------------------------
1 | // Licensed to the .NET Foundation under one or more agreements.
2 | // The .NET Foundation licenses this file to you under the MIT license.
3 |
4 | // This was copied from https://github.com/dotnet/runtime/blob/1db4357891752cc028620710fe924425235b8f89/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/CallerArgumentExpressionAttribute.cs
5 | // and updated to have the scope of the attributes be internal.
6 |
7 | namespace System.Runtime.CompilerServices;
8 |
9 | #if NETSTANDARD2_0 || NET462
10 |
11 | using ComponentModel;
12 |
13 | [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
14 | internal sealed class CallerArgumentExpressionAttribute : Attribute
15 | {
16 | public CallerArgumentExpressionAttribute(string parameterName)
17 | {
18 | ParameterName = parameterName;
19 | }
20 |
21 | public string ParameterName { get; }
22 | }
23 |
24 | [EditorBrowsable(EditorBrowsableState.Never)]
25 | internal static class IsExternalInit {}
26 |
27 | #endif // !NET5_0_OR_GREATER
28 |
29 | #if !NET7_0_OR_GREATER
30 |
31 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Field | AttributeTargets.Property, Inherited = false)]
32 | internal sealed class RequiredMemberAttribute : Attribute {}
33 |
34 | [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
35 | internal sealed class CompilerFeatureRequiredAttribute : Attribute
36 | {
37 | public CompilerFeatureRequiredAttribute(string featureName)
38 | {
39 | FeatureName = featureName;
40 | }
41 |
42 | public string FeatureName { get; }
43 | public bool IsOptional { get; init; }
44 |
45 | public const string RefStructs = nameof(RefStructs);
46 | public const string RequiredMembers = nameof(RequiredMembers);
47 | }
48 |
49 | #endif // !NET7_0_OR_GREATER
50 |
--------------------------------------------------------------------------------
/Milvus.Client/Diagnostics/Logging.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Extensions.Logging;
2 |
3 | namespace Milvus.Client.Diagnostics;
4 |
5 | internal static partial class LoggingExtensions
6 | {
7 | [LoggerMessage(1, LogLevel.Warning, "Unhealthy: {Reasons}")]
8 | public static partial void HealthCheckFailed(this ILogger logger, IEnumerable reasons);
9 |
10 | [LoggerMessage(2, LogLevel.Debug, "{OperationName} invoked: {Argument}")]
11 | public static partial void OperationInvoked(this ILogger logger, string operationName, object argument);
12 |
13 | [LoggerMessage(3, LogLevel.Error, "{OperationName} failed: {ErrorCode}, {Reason}")]
14 | public static partial void OperationFailed(this ILogger logger, string operationName, MilvusErrorCode errorCode, string reason);
15 | }
16 |
--------------------------------------------------------------------------------
/Milvus.Client/Diagnostics/Verify.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics.CodeAnalysis;
2 | using System.Runtime.CompilerServices;
3 |
4 | namespace Milvus.Client;
5 |
6 | internal static class Verify
7 | {
8 | internal static void NotNull([NotNull] object? argument, [CallerArgumentExpression(nameof(argument))] string paramName = "")
9 | {
10 | if (argument is null)
11 | {
12 | ThrowNullException(paramName);
13 | }
14 |
15 | [DoesNotReturn]
16 | static void ThrowNullException(string paramName) => throw new ArgumentNullException(paramName);
17 | }
18 |
19 | internal static void NotNullOrWhiteSpace([NotNull] string? argument, [CallerArgumentExpression(nameof(argument))] string paramName = "")
20 | {
21 | NotNull(argument, paramName);
22 |
23 | if (string.IsNullOrWhiteSpace(argument))
24 | {
25 | ThrowWhiteSpaceException(paramName);
26 | }
27 |
28 | [DoesNotReturn]
29 | static void ThrowWhiteSpaceException(string paramName)
30 | => throw new ArgumentException("The value cannot be an empty string or composed entirely of whitespace.", paramName);
31 | }
32 |
33 | internal static void NotNullOrEmpty([NotNull] IReadOnlyList? argument, [CallerArgumentExpression(nameof(argument))] string paramName = "")
34 | {
35 | NotNull(argument);
36 |
37 | if (argument.Count == 0)
38 | {
39 | ThrowEmptyException(paramName);
40 | }
41 |
42 | static void ThrowEmptyException(string paramName)
43 | => throw new ArgumentException("The collection cannot empty", paramName);
44 | }
45 |
46 | internal static void GreaterThan(long value, long other, [CallerArgumentExpression(nameof(value))] string paramName = "")
47 | {
48 | if (value <= other)
49 | {
50 | ThrowLessThanOrEqual(other, paramName);
51 | }
52 |
53 | static void ThrowLessThanOrEqual(long other, string paramName) =>
54 | throw new ArgumentOutOfRangeException(paramName, $"The value must be greater than {other}.");
55 | }
56 |
57 | internal static void GreaterThanOrEqualTo(long value, long other, [CallerArgumentExpression(nameof(value))] string paramName = "")
58 | {
59 | if (value < other)
60 | {
61 | ThrowLessThan(other, paramName);
62 | }
63 |
64 | static void ThrowLessThan(long other, string paramName) =>
65 | throw new ArgumentOutOfRangeException(paramName, $"The value must be greater than or equal to {other}.");
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/Milvus.Client/FieldState.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// Milvus field state.
5 | ///
6 | public enum FieldState
7 | {
8 | ///
9 | /// The field has been created.
10 | ///
11 | FieldCreated = Grpc.FieldState.FieldCreated,
12 |
13 | ///
14 | /// The field is in the process of being created.
15 | ///
16 | FieldCreating = Grpc.FieldState.FieldCreating,
17 |
18 | ///
19 | /// The field is in the process of being dropped.
20 | ///
21 | FieldDropping = Grpc.FieldState.FieldDropping,
22 |
23 | ///
24 | /// The field has been dropped.
25 | ///
26 | FieldDropped = Grpc.FieldState.FieldDropped,
27 |
28 | ///
29 | /// The field state is unknown or not yet created.
30 | ///
31 | Unknown = int.MaxValue
32 | }
33 |
--------------------------------------------------------------------------------
/Milvus.Client/FloatVectorFieldData.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.InteropServices;
2 | using Google.Protobuf.Collections;
3 |
4 | namespace Milvus.Client;
5 |
6 | ///
7 | /// Float vector field
8 | ///
9 | public sealed class FloatVectorFieldData : FieldData>
10 | {
11 | ///
12 | /// Create a float vector field.
13 | ///
14 | /// Field name
15 | /// data
16 | public FloatVectorFieldData(
17 | string fieldName,
18 | IReadOnlyList> data)
19 | : base(fieldName, data, MilvusDataType.FloatVector, false)
20 | {
21 | }
22 |
23 | ///
24 | /// Row count.
25 | ///
26 | public override long RowCount => Data.Count;
27 |
28 | ///
29 | /// Convert to grpc field data
30 | ///
31 | /// Field data
32 | ///
33 | internal override Grpc.FieldData ToGrpcFieldData()
34 | {
35 | Grpc.FloatArray floatArray = new();
36 | RepeatedField destination = floatArray.Data;
37 |
38 | if (Data.Count == 0)
39 | {
40 | throw new MilvusException("The number of vectors must be positive.");
41 | }
42 |
43 | int dim = Data[0].Length;
44 |
45 | // The gRPC representation of the vector data is a flat list of the elements (the dimension is known and all
46 | // vectors have the same dimension)
47 | destination.Capacity = dim * Data.Count;
48 |
49 | foreach (ReadOnlyMemory vector in Data)
50 | {
51 | if (vector.Length != dim)
52 | {
53 | throw new MilvusException("All vectors must have the same dimensionality.");
54 | }
55 |
56 | // Special-case optimization for when the vector is an entire array
57 | if (MemoryMarshal.TryGetArray(vector, out ArraySegment segment) &&
58 | segment.Offset == 0 &&
59 | segment.Count == segment.Array!.Length)
60 | {
61 | destination.AddRange(segment.Array);
62 | }
63 | else
64 | {
65 | foreach (float f in vector.Span)
66 | {
67 | destination.Add(f);
68 | }
69 | }
70 | }
71 |
72 | return new Grpc.FieldData
73 | {
74 | FieldName = FieldName,
75 | Type = (Grpc.DataType)DataType,
76 | Vectors = new Grpc.VectorField
77 | {
78 | FloatVector = floatArray,
79 | Dim = dim,
80 | }
81 | };
82 | }
83 |
84 | internal override object GetValueAsObject(int index)
85 | => throw new NotSupportedException("Dynamic vector fields are not supported");
86 | }
87 |
--------------------------------------------------------------------------------
/Milvus.Client/FlushResult.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// Milvus flush result.
5 | ///
6 | public sealed class FlushResult
7 | {
8 | ///
9 | /// Collection segment ids.
10 | ///
11 | ///
12 | ///
13 | /// A segment is a data file automatically created by Milvus for holding inserted data.
14 | ///
15 | ///
16 | /// A collection can have multiple segments and a segment can have multiple entities.
17 | ///
18 | ///
19 | public IReadOnlyDictionary> CollSegIDs { get; }
20 |
21 | ///
22 | /// Flush collection segment ids.
23 | ///
24 | public IReadOnlyDictionary> FlushCollSegIds { get; }
25 |
26 | ///
27 | /// Collection seal times.
28 | ///
29 | ///
30 | ///
31 | /// A segment can be either growing or sealed. A growing segment keeps receiving the newly inserted data till it is sealed.
32 | ///
33 | ///
34 | /// A sealed segment no longer receives any new data, and will be flushed to the object storage
35 | ///
36 | ///
37 | public IReadOnlyDictionary CollSealTimes { get; }
38 |
39 | internal static FlushResult From(FlushResponse response)
40 | => new(
41 | response.CollSegIDs.ToDictionary(static p => p.Key,
42 | static p => (IReadOnlyList)p.Value.Data.ToArray()),
43 | response.FlushCollSegIDs.ToDictionary(static p => p.Key,
44 | static p => (IReadOnlyList)p.Value.Data.ToArray()),
45 | response.CollSealTimes);
46 |
47 | private FlushResult(
48 | IReadOnlyDictionary> collSegIDs,
49 | IReadOnlyDictionary> flushCollSegIDs,
50 | IReadOnlyDictionary collSealTimes)
51 | {
52 | CollSegIDs = collSegIDs;
53 | FlushCollSegIds = flushCollSegIDs;
54 | CollSealTimes = collSealTimes;
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/Milvus.Client/GrantResult.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// Milvus grant entity.
5 | ///
6 | ///
7 | /// and
8 | ///
9 | ///
10 | public sealed class GrantEntity
11 | {
12 | internal GrantEntity(
13 | MilvusGrantorEntity grantor,
14 | string dbName,
15 | string @object,
16 | string role,
17 | string objectName)
18 | {
19 | Grantor = grantor;
20 | DbName = dbName;
21 | Object = @object;
22 | Role = role;
23 | ObjectName = objectName;
24 | }
25 |
26 | ///
27 | /// Grantor.
28 | ///
29 | public MilvusGrantorEntity Grantor { get; }
30 |
31 | ///
32 | /// Database name.
33 | ///
34 | public string DbName { get; }
35 |
36 | ///
37 | /// Object.
38 | ///
39 | public string Object { get; }
40 |
41 | ///
42 | /// Role.
43 | ///
44 | public string Role { get; }
45 |
46 | ///
47 | /// Object name.
48 | ///
49 | public string ObjectName { get; }
50 | }
51 |
52 | ///
53 | /// Milvus grantor result.
54 | ///
55 | public sealed class MilvusGrantorEntity
56 | {
57 | private MilvusGrantorEntity(string privilege, string userName)
58 | {
59 | Privilege = privilege;
60 | UserName = userName;
61 | }
62 |
63 | ///
64 | /// Privilege name.
65 | ///
66 | public string Privilege { get; }
67 |
68 | ///
69 | /// User name.
70 | ///
71 | public string UserName { get; }
72 |
73 | internal static MilvusGrantorEntity Parse(GrantorEntity grantor)
74 | => new(grantor.Privilege.Name, grantor.User.Name);
75 | }
76 |
--------------------------------------------------------------------------------
/Milvus.Client/HealthState.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// Check if Milvus is healthy.
5 | ///
6 | public sealed class MilvusHealthState
7 | {
8 | internal MilvusHealthState(
9 | bool isHealthy,
10 | string errorMsg,
11 | MilvusErrorCode errorCode)
12 | {
13 | IsHealthy = isHealthy;
14 | ErrorMsg = errorMsg;
15 | ErrorCode = errorCode;
16 | }
17 |
18 | ///
19 | /// Health flag.
20 | ///
21 | public bool IsHealthy { get; }
22 |
23 | ///
24 | /// Error message.
25 | ///
26 | public string ErrorMsg { get; }
27 |
28 | ///
29 | /// Error code.
30 | ///
31 | public MilvusErrorCode ErrorCode { get; }
32 |
33 | ///
34 | /// Get string data.
35 | ///
36 | public override string ToString()
37 | {
38 | string state = $"{{{nameof(IsHealthy)}:{IsHealthy}}}";
39 | if (!IsHealthy)
40 | {
41 | state = $"{state}, {{{nameof(ErrorCode)}:{ErrorCode}}}, {{{nameof(ErrorMsg)}:{ErrorMsg}}}";
42 | }
43 |
44 | return state;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Milvus.Client/IndexBuildProgress.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// Indicate build progress of an index.
5 | ///
6 | public readonly struct IndexBuildProgress : IEquatable
7 | {
8 | ///
9 | /// Construct a index progress struct.
10 | ///
11 | /// Indexed rows.
12 | /// Total rows.
13 | public IndexBuildProgress(long indexedRows, long totalRows)
14 | {
15 | IndexedRows = indexedRows;
16 | TotalRows = totalRows;
17 | }
18 |
19 | ///
20 | /// Indexed rows.
21 | ///
22 | public long IndexedRows { get; }
23 |
24 | ///
25 | /// Total rows.
26 | ///
27 | public long TotalRows { get; }
28 |
29 | ///
30 | /// Whether the index has been fully built.
31 | ///
32 | public bool IsComplete => IndexedRows == TotalRows;
33 |
34 | ///
35 | public override bool Equals(object? obj)
36 | => obj is IndexBuildProgress other && Equals(other);
37 |
38 | ///
39 | public bool Equals(IndexBuildProgress other)
40 | => IndexedRows == other.IndexedRows && TotalRows == other.TotalRows;
41 |
42 | ///
43 | public override int GetHashCode() => HashCode.Combine(IndexedRows, TotalRows);
44 |
45 | ///
46 | public override string ToString() => $"Progress: {IndexedRows}/{TotalRows}";
47 |
48 | ///
49 | /// Compares two instances for equality.
50 | ///
51 | public static bool operator ==(IndexBuildProgress left, IndexBuildProgress right) => left.Equals(right);
52 |
53 | ///
54 | /// Compares two instances for inequality.
55 | ///
56 | public static bool operator !=(IndexBuildProgress left, IndexBuildProgress right) => !(left == right);
57 | }
58 |
--------------------------------------------------------------------------------
/Milvus.Client/IndexState.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// Index state.
5 | ///
6 | public enum IndexState
7 | {
8 | ///
9 | /// None.
10 | ///
11 | None = 0,
12 |
13 | ///
14 | /// Unissued.
15 | ///
16 | Unissued = 1,
17 |
18 | ///
19 | /// InProgress.
20 | ///
21 | InProgress = 2,
22 |
23 | ///
24 | /// Finished.
25 | ///
26 | Finished = 3,
27 |
28 | ///
29 | /// Failed.
30 | ///
31 | Failed = 4,
32 |
33 | ///
34 | /// Retry.
35 | ///
36 | Retry = 5,
37 | }
38 |
--------------------------------------------------------------------------------
/Milvus.Client/Milvus.Client.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | net6.0;netstandard2.0;net462
6 | net6.0
7 | true
8 | All
9 |
10 | Milvus C# SDK
11 | https://github.com/milvus-io/milvus-sdk-csharp
12 | milvussharp.png
13 | https://github.com/milvus-io/milvus-sdk-csharp
14 | milvus;vector database
15 | readme.md
16 | True
17 |
18 |
19 |
20 |
21 | True
22 | \
23 |
24 |
25 | True
26 | \
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 | all
44 | runtime; build; native; contentfiles; analyzers; buildtransitive
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/Milvus.Client/MilvusClient.Alias.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | public partial class MilvusClient
4 | {
5 | ///
6 | /// Creates an alias for a collection.
7 | ///
8 | /// The name of the collection for which to create the alias.
9 | /// The alias to be created.
10 | ///
11 | /// The token to monitor for cancellation requests. The default value is .
12 | ///
13 | public async Task CreateAliasAsync(
14 | string collectionName,
15 | string alias,
16 | CancellationToken cancellationToken = default)
17 | {
18 | Verify.NotNullOrWhiteSpace(collectionName);
19 | Verify.NotNullOrWhiteSpace(alias);
20 |
21 | var request = new CreateAliasRequest { CollectionName = collectionName, Alias = alias };
22 |
23 | await InvokeAsync(GrpcClient.CreateAliasAsync, request, cancellationToken)
24 | .ConfigureAwait(false);
25 | }
26 |
27 | ///
28 | /// Drops an alias.
29 | ///
30 | /// The alias to be dropped.
31 | ///
32 | /// The token to monitor for cancellation requests. The default value is .
33 | ///
34 | public async Task DropAliasAsync(string alias, CancellationToken cancellationToken = default)
35 | {
36 | Verify.NotNullOrWhiteSpace(alias);
37 |
38 | var request = new DropAliasRequest { Alias = alias };
39 |
40 | await InvokeAsync(GrpcClient.DropAliasAsync, request, cancellationToken).ConfigureAwait(false);
41 | }
42 |
43 | ///
44 | /// Alters an alias to point to a new collection.
45 | ///
46 | /// The name of the collection to which the alias should point.
47 | /// The alias to be altered.
48 | ///
49 | /// The token to monitor for cancellation requests. The default value is .
50 | ///
51 | public async Task AlterAliasAsync(
52 | string collectionName,
53 | string alias,
54 | CancellationToken cancellationToken = default)
55 | {
56 | Verify.NotNullOrWhiteSpace(collectionName);
57 | Verify.NotNullOrWhiteSpace(alias);
58 |
59 | var request = new AlterAliasRequest { CollectionName = collectionName, Alias = alias };
60 |
61 | await InvokeAsync(GrpcClient.AlterAliasAsync, request, cancellationToken: cancellationToken)
62 | .ConfigureAwait(false);
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/Milvus.Client/MilvusClient.Compaction.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | public partial class MilvusClient
4 | {
5 | ///
6 | /// Gets the state of a compaction previously started via .
7 | ///
8 | /// The compaction ID returned by .
9 | ///
10 | /// The token to monitor for cancellation requests. The default value is .
11 | ///
12 | public async Task GetCompactionStateAsync(
13 | long compactionId,
14 | CancellationToken cancellationToken = default)
15 | {
16 | Verify.GreaterThan(compactionId, 0);
17 |
18 | GetCompactionStateResponse response = await InvokeAsync(GrpcClient.GetCompactionStateAsync,
19 | new GetCompactionStateRequest { CompactionID = compactionId }, static r => r.Status, cancellationToken)
20 | .ConfigureAwait(false);
21 |
22 | return (CompactionState)response.State;
23 | }
24 |
25 | ///
26 | /// Polls Milvus for the state of a compaction process until it is complete..
27 | /// To perform a single progress check, use .
28 | ///
29 | /// The compaction ID returned by .
30 | /// Waiting interval. Defaults to 500 milliseconds.
31 | /// How long to poll for before throwing a .
32 | ///
33 | /// The token to monitor for cancellation requests. The default value is .
34 | ///
35 | public async Task WaitForCompactionAsync(
36 | long compactionId,
37 | TimeSpan? waitingInterval = null,
38 | TimeSpan? timeout = null,
39 | CancellationToken cancellationToken = default)
40 | {
41 | await Utils.Poll(
42 | async () =>
43 | {
44 | CompactionState state = await GetCompactionStateAsync(compactionId, cancellationToken)
45 | .ConfigureAwait(false);
46 |
47 | return state switch
48 | {
49 | CompactionState.Undefined
50 | => throw new InvalidOperationException($"Compaction with ID {compactionId} is in an undefined state."),
51 | CompactionState.Executing => (false, 0),
52 | CompactionState.Completed => (true, 0),
53 |
54 | _ => throw new ArgumentOutOfRangeException("Invalid state: " + state)
55 | };
56 | },
57 | $"Timeout when waiting for compaction with ID {compactionId}",
58 | waitingInterval, timeout, progress: null, cancellationToken).ConfigureAwait(false);
59 | }
60 |
61 | ///
62 | /// Gets the compaction states of a compaction.
63 | ///
64 | /// The compaction ID returned by .
65 | ///
66 | /// The token to monitor for cancellation requests. The default value is .
67 | ///
68 | public async Task GetCompactionPlansAsync(
69 | long compactionId,
70 | CancellationToken cancellationToken = default)
71 | {
72 | Verify.GreaterThan(compactionId, 0);
73 |
74 | GetCompactionPlansResponse response = await InvokeAsync(GrpcClient.GetCompactionStateWithPlansAsync,
75 | new GetCompactionPlansRequest { CompactionID = compactionId }, static r => r.Status, cancellationToken)
76 | .ConfigureAwait(false);
77 |
78 | return new(
79 | response.MergeInfos
80 | .Select(static x => new MilvusCompactionPlan { Sources = x.Sources, Target = x.Target })
81 | .ToList(),
82 | (CompactionState)response.State);
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/Milvus.Client/MilvusClient.Database.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | public partial class MilvusClient
4 | {
5 | ///
6 | /// Creates a new database.
7 | ///
8 | /// The name of the new database to be created.
9 | ///
10 | /// The token to monitor for cancellation requests. The default value is .
11 | ///
12 | ///
13 | ///
14 | /// Available starting Milvus 2.2.9.
15 | ///
16 | ///
17 | public async Task CreateDatabaseAsync(string databaseName, CancellationToken cancellationToken = default)
18 | {
19 | Verify.NotNullOrWhiteSpace(databaseName);
20 |
21 | await InvokeAsync(
22 | GrpcClient.CreateDatabaseAsync, new CreateDatabaseRequest { DbName = databaseName }, cancellationToken)
23 | .ConfigureAwait(false);
24 | }
25 |
26 | ///
27 | /// List all available databases.
28 | ///
29 | ///
30 | ///
31 | /// Available starting Milvus 2.2.9.
32 | ///
33 | ///
34 | /// The list of available databases.
35 | public async Task> ListDatabasesAsync(CancellationToken cancellationToken = default)
36 | {
37 | ListDatabasesResponse response = await InvokeAsync(
38 | GrpcClient.ListDatabasesAsync, new ListDatabasesRequest(), static r => r.Status, cancellationToken)
39 | .ConfigureAwait(false);
40 |
41 | return response.DbNames;
42 | }
43 |
44 | ///
45 | /// Drops a database.
46 | ///
47 | /// The name of the database to be dropped.
48 | ///
49 | /// The token to monitor for cancellation requests. The default value is .
50 | ///
51 | ///
52 | ///
53 | /// Available starting Milvus 2.2.9.
54 | ///
55 | ///
56 | public async Task DropDatabaseAsync(string databaseName, CancellationToken cancellationToken = default)
57 | {
58 | await InvokeAsync(
59 | GrpcClient.DropDatabaseAsync, new DropDatabaseRequest { DbName = databaseName }, cancellationToken)
60 | .ConfigureAwait(false);
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/Milvus.Client/MilvusClient.Metrics.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | public partial class MilvusClient
4 | {
5 | ///
6 | /// Gets metrics.
7 | ///
8 | /// Request in JSON format.
9 | ///
10 | /// The token to monitor for cancellation requests. The default value is .
11 | ///
12 | public async Task GetMetricsAsync(
13 | string request,
14 | CancellationToken cancellationToken = default)
15 | {
16 | Verify.NotNullOrWhiteSpace(request);
17 |
18 | GetMetricsResponse response = await InvokeAsync(GrpcClient.GetMetricsAsync, new GetMetricsRequest
19 | {
20 | Request = request
21 | }, static r => r.Status, cancellationToken).ConfigureAwait(false);
22 |
23 | return new MilvusMetrics(response.Response, response.ComponentName);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Milvus.Client/MilvusClient.User.cs:
--------------------------------------------------------------------------------
1 | using System.Text;
2 |
3 | namespace Milvus.Client;
4 |
5 | public partial class MilvusClient
6 | {
7 | ///
8 | /// Creates a new user.
9 | ///
10 | /// The username of the user to be created.
11 | /// The password of the user to be created..
12 | ///
13 | /// The token to monitor for cancellation requests. The default value is .
14 | ///
15 | public async Task CreateUserAsync(
16 | string username,
17 | string password,
18 | CancellationToken cancellationToken = default)
19 | {
20 | Verify.NotNullOrWhiteSpace(username);
21 | Verify.NotNullOrWhiteSpace(password);
22 |
23 | await InvokeAsync(GrpcClient.CreateCredentialAsync, new CreateCredentialRequest
24 | {
25 | Username = username,
26 | Password = Base64Encode(password),
27 | }, cancellationToken).ConfigureAwait(false);
28 | }
29 |
30 | ///
31 | /// Deletes a user.
32 | ///
33 | /// The username of the user to delete.
34 | ///
35 | /// The token to monitor for cancellation requests. The default value is .
36 | ///
37 | public async Task DeleteUserAsync(
38 | string username,
39 | CancellationToken cancellationToken = default)
40 | {
41 | Verify.NotNullOrWhiteSpace(username);
42 |
43 | await InvokeAsync(GrpcClient.DeleteCredentialAsync, new DeleteCredentialRequest
44 | {
45 | Username = username
46 | }, cancellationToken).ConfigureAwait(false);
47 | }
48 |
49 | ///
50 | /// Updates the password for a user.
51 | ///
52 | /// The username for which to change the password.
53 | /// The user's old password.
54 | /// The new password to set for the user.
55 | ///
56 | /// The token to monitor for cancellation requests. The default value is .
57 | ///
58 | public async Task UpdatePassword(
59 | string username,
60 | string oldPassword,
61 | string newPassword,
62 | CancellationToken cancellationToken = default)
63 | {
64 | Verify.NotNullOrWhiteSpace(username);
65 | Verify.NotNullOrWhiteSpace(oldPassword);
66 | Verify.NotNullOrWhiteSpace(newPassword);
67 |
68 | await InvokeAsync(GrpcClient.UpdateCredentialAsync, new UpdateCredentialRequest
69 | {
70 | NewPassword = Base64Encode(newPassword),
71 | OldPassword = Base64Encode(oldPassword),
72 | Username = username
73 | }, cancellationToken).ConfigureAwait(false);
74 | }
75 |
76 | ///
77 | /// Lists all users.
78 | ///
79 | ///
80 | /// The token to monitor for cancellation requests. The default value is .
81 | ///
82 | public async Task> ListUsernames(
83 | CancellationToken cancellationToken = default)
84 | {
85 | ListCredUsersResponse response = await InvokeAsync(GrpcClient.ListCredUsersAsync, new ListCredUsersRequest(),
86 | static r => r.Status, cancellationToken).ConfigureAwait(false);
87 |
88 | return response.Usernames;
89 | }
90 |
91 | private static string Base64Encode(string input)
92 | => Convert.ToBase64String(Encoding.UTF8.GetBytes(input));
93 | }
94 |
--------------------------------------------------------------------------------
/Milvus.Client/MilvusCollection.cs:
--------------------------------------------------------------------------------
1 | using System.Text;
2 |
3 | namespace Milvus.Client;
4 |
5 | ///
6 | /// Represents a Milvus collection, and is the starting point for all operations involving one.
7 | ///
8 | #pragma warning disable CA1711
9 | public partial class MilvusCollection
10 | #pragma warning restore CA1711
11 | {
12 | private readonly MilvusClient _client;
13 |
14 | ///
15 | /// The name of the collection.
16 | ///
17 | public string Name { get; private set; }
18 |
19 | internal MilvusCollection(MilvusClient client, string collectionName)
20 | => (_client, Name) = (client, collectionName);
21 |
22 | #region Utilities
23 |
24 | private static string Combine(IDictionary parameters)
25 | {
26 | StringBuilder stringBuilder = new();
27 | stringBuilder.Append('{');
28 |
29 | int index = 0;
30 | foreach (KeyValuePair parameter in parameters)
31 | {
32 | stringBuilder
33 | .Append('"')
34 | .Append(parameter.Key)
35 | .Append("\":")
36 | .Append(parameter.Value);
37 |
38 | if (index++ != parameters.Count - 1)
39 | {
40 | stringBuilder.Append(", ");
41 | }
42 | }
43 |
44 | stringBuilder.Append('}');
45 | return stringBuilder.ToString();
46 | }
47 |
48 | #endregion Utilities
49 | }
50 |
--------------------------------------------------------------------------------
/Milvus.Client/MilvusCollectionDescription.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// Describe a milvus collection
5 | ///
6 | public sealed class MilvusCollectionDescription
7 | {
8 | internal MilvusCollectionDescription(
9 | IReadOnlyList aliases,
10 | string collectionName,
11 | long collectionId,
12 | ConsistencyLevel consistencyLevel,
13 | ulong creationTimestamp,
14 | CollectionSchema schema,
15 | int shardsNum,
16 | IReadOnlyDictionary> startPositions)
17 | {
18 | Aliases = aliases;
19 | CollectionName = collectionName;
20 | CollectionId = collectionId;
21 | ConsistencyLevel = consistencyLevel;
22 | CreationTimestamp = creationTimestamp;
23 | Schema = schema;
24 | ShardsNum = shardsNum;
25 | StartPositions = startPositions;
26 | }
27 |
28 | ///
29 | /// The aliases of this collection.
30 | ///
31 | public IReadOnlyList Aliases { get; }
32 |
33 | ///
34 | /// The collection name.
35 | ///
36 | public string CollectionName { get; }
37 |
38 | ///
39 | /// The collection id.
40 | ///
41 | public long CollectionId { get; }
42 |
43 | ///
44 | /// Consistency level.
45 | ///
46 | ///
47 | /// The consistency level that the collection used, modification is not supported now.
48 | ///
49 | public ConsistencyLevel ConsistencyLevel { get; }
50 |
51 | ///
52 | /// An opaque identifier for the point in time in which the the collection was created. Can be passed to
53 | /// or as a guarantee
54 | /// timestamp or as a time travel timestamp.
55 | ///
56 | public ulong CreationTimestamp { get; }
57 |
58 | ///
59 | /// Collection Schema.
60 | ///
61 | public CollectionSchema Schema { get; }
62 |
63 | ///
64 | /// The shards number you set.
65 | ///
66 | public int ShardsNum { get; }
67 |
68 | ///
69 | /// The message ID/position when collection is created.
70 | ///
71 | public IReadOnlyDictionary> StartPositions { get; }
72 | }
73 |
--------------------------------------------------------------------------------
/Milvus.Client/MilvusCollectionInfo.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// Milvus collection information
5 | ///
6 | public sealed class MilvusCollectionInfo
7 | {
8 | internal MilvusCollectionInfo(
9 | long id,
10 | string name,
11 | ulong creationTimestamp,
12 | long inMemoryPercentage)
13 | {
14 | Id = id;
15 | Name = name;
16 | CreationTimestamp = creationTimestamp;
17 | InMemoryPercentage = inMemoryPercentage;
18 | }
19 |
20 | ///
21 | /// Collection Id list.
22 | ///
23 | public long Id { get; }
24 |
25 | ///
26 | /// Collection name list.
27 | ///
28 | public string Name { get; }
29 |
30 | ///
31 | /// An opaque identifier for the point in time in which the the collection was created. Can be passed to
32 | /// or as a guarantee
33 | /// timestamp or as a time travel timestamp.
34 | ///
35 | public ulong CreationTimestamp { get; }
36 |
37 | ///
38 | /// Load percentage on query node when type is InMemory.
39 | ///
40 | public long InMemoryPercentage { get; }
41 |
42 | ///
43 | /// Return string value of .
44 | ///
45 | public override string ToString()
46 | => $"MilvusCollection: {{{nameof(Name)}: {Name}, {nameof(Id)}: {Id}, {nameof(CreationTimestamp)}:{CreationTimestamp}, {nameof(InMemoryPercentage)}: {InMemoryPercentage}}}";
47 | }
48 |
--------------------------------------------------------------------------------
/Milvus.Client/MilvusDataType.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// Data type
5 | ///
6 | ///
7 | ///
8 | ///
9 | public enum MilvusDataType
10 | {
11 | ///
12 | /// None
13 | ///
14 | None = 0,
15 |
16 | ///
17 | /// Bool
18 | ///
19 | Bool = 1,
20 |
21 | ///
22 | /// Int8
23 | ///
24 | Int8 = 2,
25 |
26 | ///
27 | /// Int16
28 | ///
29 | Int16 = 3,
30 |
31 | ///
32 | /// Int32
33 | ///
34 | Int32 = 4,
35 |
36 | ///
37 | /// Int64
38 | ///
39 | Int64 = 5,
40 |
41 | ///
42 | /// Float
43 | ///
44 | Float = 10,
45 |
46 | ///
47 | /// Double
48 | ///
49 | Double = 11,
50 |
51 | ///
52 | /// String
53 | ///
54 | String = 20,
55 |
56 | ///
57 | /// VarChar
58 | ///
59 | VarChar = 21,
60 |
61 | ///
62 | /// Array
63 | ///
64 | Array = 22,
65 |
66 | ///
67 | /// Json
68 | ///
69 | Json = 23,
70 |
71 | ///
72 | /// BinaryVector
73 | ///
74 | BinaryVector = 100,
75 |
76 | ///
77 | /// FloatVector
78 | ///
79 | FloatVector = 101,
80 | }
81 |
--------------------------------------------------------------------------------
/Milvus.Client/MilvusErrorCode.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | #pragma warning disable CS1591 // Missing XML docs
4 |
5 | ///
6 | /// An error code returned in .
7 | ///
8 | public enum MilvusErrorCode
9 | {
10 | Success = 0,
11 | UnexpectedError = 1,
12 | RateLimit = 8,
13 | ForceDeny = 9,
14 | CollectionNotFound = 100,
15 | IndexNotFound = 700
16 | }
17 |
--------------------------------------------------------------------------------
/Milvus.Client/MilvusException.cs:
--------------------------------------------------------------------------------
1 | #if NET462
2 | using System.Runtime.Serialization;
3 | #endif
4 |
5 | namespace Milvus.Client;
6 |
7 | ///
8 | /// Exception thrown for errors related to the Milvus client.
9 | ///
10 | #if NET462
11 | [Serializable]
12 | #endif
13 | public sealed class MilvusException : Exception
14 | {
15 | ///
16 | /// The error code.
17 | ///
18 | public MilvusErrorCode ErrorCode { get; }
19 |
20 | ///
21 | public MilvusException()
22 | {
23 | }
24 |
25 | ///
26 | public MilvusException(string message) : base(message)
27 | {
28 | }
29 |
30 | ///
31 | public MilvusException(string message, Exception innerException) : base(message, innerException)
32 | {
33 | }
34 |
35 | ///
36 | /// Instantiates a new .
37 | ///
38 | public MilvusException(MilvusErrorCode errorCode, string reason)
39 | : base($"ErrorCode: {errorCode} Reason: {reason}")
40 | {
41 | ErrorCode = errorCode;
42 | }
43 |
44 | #if NET462
45 | private MilvusException(SerializationInfo info, StreamingContext context)
46 | {
47 | info.AddValue(nameof(ErrorCode), ErrorCode);
48 | }
49 | #endif
50 | }
51 |
--------------------------------------------------------------------------------
/Milvus.Client/MilvusIds.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 |
3 | namespace Milvus.Client;
4 |
5 | ///
6 | /// A wrapper around an array of IDs returned from a query or search. Can contain either long or string IDs.
7 | ///
8 | public readonly struct MilvusIds : IEquatable
9 | {
10 | private MilvusIds(IReadOnlyList longIds)
11 | => LongIds = longIds;
12 |
13 | private MilvusIds(IReadOnlyList stringIds)
14 | => StringIds = stringIds;
15 |
16 | ///
17 | /// Int id.
18 | ///
19 | public IReadOnlyList? LongIds { get; }
20 |
21 | ///
22 | /// String id.
23 | ///
24 | public IReadOnlyList? StringIds { get; }
25 |
26 | internal static MilvusIds FromGrpc(Grpc.IDs grpcIds)
27 | => grpcIds.IdFieldCase switch
28 | {
29 | IDs.IdFieldOneofCase.None => default,
30 | IDs.IdFieldOneofCase.IntId => new MilvusIds(grpcIds.IntId.Data),
31 | IDs.IdFieldOneofCase.StrId => new MilvusIds(grpcIds.StrId.Data),
32 | _ => throw new NotSupportedException("Invalid ID type in search results: " + grpcIds.IdFieldCase)
33 | };
34 |
35 | ///
36 | public bool Equals(MilvusIds other)
37 | {
38 | switch (this)
39 | {
40 | case { LongIds: IReadOnlyList longIds }:
41 | if (other.LongIds is not IReadOnlyList otherLongIds ||
42 | longIds.Count != otherLongIds.Count)
43 | {
44 | return false;
45 | }
46 |
47 | for (int i = 0; i < longIds.Count; i++)
48 | {
49 | if (longIds[i] != otherLongIds[i])
50 | {
51 | return false;
52 | }
53 | }
54 |
55 | return true;
56 |
57 | case { StringIds: IReadOnlyList stringIds }:
58 | if (other.StringIds is not IReadOnlyList otherStringIds ||
59 | stringIds.Count != otherStringIds.Count)
60 | {
61 | return false;
62 | }
63 |
64 | for (int i = 0; i < stringIds.Count; i++)
65 | {
66 | if (stringIds[i] != otherStringIds[i])
67 | {
68 | return false;
69 | }
70 | }
71 |
72 | return true;
73 |
74 | default:
75 | Debug.Assert(this == default);
76 | return other == default;
77 | }
78 | }
79 |
80 | ///
81 | public override bool Equals(object? obj)
82 | => obj is MilvusIds other && Equals(other);
83 |
84 | ///
85 | public override int GetHashCode()
86 | {
87 | HashCode hashCode = new();
88 |
89 | switch (this)
90 | {
91 | case { LongIds: IReadOnlyList longIds }:
92 | foreach (long id in longIds)
93 | {
94 | hashCode.Add(id);
95 | }
96 |
97 | break;
98 |
99 | case { StringIds: IReadOnlyList stringIds }:
100 | foreach (string id in stringIds)
101 | {
102 | hashCode.Add(id);
103 | }
104 |
105 | break;
106 | }
107 |
108 | return hashCode.ToHashCode();
109 | }
110 |
111 | ///
112 | /// Compares the two ID lists for equality.
113 | ///
114 | public static bool operator ==(MilvusIds left, MilvusIds right)
115 | => left.Equals(right);
116 |
117 | ///
118 | /// Compares the two ID lists for equality.
119 | ///
120 | public static bool operator !=(MilvusIds left, MilvusIds right)
121 | => !(left == right);
122 |
123 | }
124 |
--------------------------------------------------------------------------------
/Milvus.Client/MilvusIndexInfo.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// Contains information about an index in Milvus; returned from .
5 | ///
6 | public sealed class MilvusIndexInfo
7 | {
8 | internal MilvusIndexInfo(
9 | string fieldName,
10 | string indexName,
11 | long indexId,
12 | IndexState state,
13 | long indexedRows,
14 | long totalRows,
15 | long pendingIndexRows,
16 | string? indexStateFailReason,
17 | IReadOnlyDictionary @params)
18 | {
19 | FieldName = fieldName;
20 | IndexName = indexName;
21 | IndexId = indexId;
22 | State = state;
23 | IndexedRows = indexedRows;
24 | TotalRows = totalRows;
25 | PendingIndexRows = pendingIndexRows;
26 | IndexStateFailReason = indexStateFailReason;
27 | Params = @params;
28 | }
29 |
30 | ///
31 | /// Field name.
32 | ///
33 | public string FieldName { get; }
34 |
35 | ///
36 | /// Index name.
37 | ///
38 | public string IndexName { get; }
39 |
40 | ///
41 | /// Index id.
42 | ///
43 | public long IndexId { get; }
44 |
45 | ///
46 | /// The state of the index.
47 | ///
48 | public IndexState State { get; }
49 |
50 | ///
51 | /// The number of rows indexed by this index;
52 | ///
53 | public long IndexedRows { get; }
54 |
55 | ///
56 | /// The total rows in the collection.
57 | ///
58 | public long TotalRows { get; }
59 |
60 | ///
61 | /// The number of pending rows in the index.
62 | ///
63 | public long PendingIndexRows { get; }
64 |
65 | ///
66 | /// If creation of the index failed, contains the reason for the failure.
67 | ///
68 | public string? IndexStateFailReason { get; }
69 |
70 | ///
71 | /// Contains index_type, metric_type, params.
72 | ///
73 | public IReadOnlyDictionary Params { get; }
74 |
75 | ///
76 | /// Get string data of
77 | ///
78 | ///
79 | public override string ToString()
80 | => $"MilvusIndex: {{{nameof(FieldName)}: {FieldName}, {nameof(IndexName)}: {IndexName}, {nameof(IndexId)}: {IndexId}}}";
81 | }
82 |
--------------------------------------------------------------------------------
/Milvus.Client/MilvusMetrics.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// Contains the response to a request for metrics via .
5 | ///
6 | public sealed class MilvusMetrics
7 | {
8 | internal MilvusMetrics(string response, string componentName)
9 | {
10 | Response = response;
11 | ComponentName = componentName;
12 | }
13 |
14 | ///
15 | /// A response in JSON format.
16 | ///
17 | public string Response { get; }
18 |
19 | ///
20 | /// The name of the component from which the metrics were returned.
21 | ///
22 | public string ComponentName { get; }
23 | }
24 |
--------------------------------------------------------------------------------
/Milvus.Client/MilvusPartition.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// Milvus partition
5 | ///
6 | ///
7 | /// Milvus allows you to divide the bulk of vector data into a small number of partitions.
8 | /// Search and other operations can then be limited to one partition to improve the performance.
9 | ///
10 | public sealed class MilvusPartition
11 | {
12 | internal MilvusPartition(
13 | long partitionId,
14 | string partitionName,
15 | ulong creationTimestamp)
16 | {
17 | PartitionId = partitionId;
18 | PartitionName = partitionName;
19 | CreationTimestamp = creationTimestamp;
20 | }
21 |
22 | ///
23 | /// Partition id.
24 | ///
25 | public long PartitionId { get; }
26 |
27 | ///
28 | /// Partition name.
29 | ///
30 | public string PartitionName { get; }
31 |
32 | ///
33 | /// An opaque identifier for the point in time in which the partition was created. Can be passed to
34 | /// or as a guarantee
35 | /// timestamp or as a time travel timestamp.
36 | ///
37 | ///
38 | /// For more details, see .
39 | ///
40 | public ulong CreationTimestamp { get; }
41 |
42 | ///
43 | /// Return string value of .
44 | ///
45 | public override string ToString()
46 | => $"MilvusPartition: {{{nameof(PartitionName)}: {PartitionName}, {nameof(PartitionId)}: {PartitionId}, {nameof(CreationTimestamp)}:{CreationTimestamp}}}";
47 | }
48 |
--------------------------------------------------------------------------------
/Milvus.Client/MilvusTimestampUtils.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// Utilities for converting to Milvus timestamps and back.
5 | ///
6 | ///
7 | /// For more information about Milvus timestamps, see .
8 | ///
9 | public static class MilvusTimestampUtils
10 | {
11 | ///
12 | /// Converts a to a Milvus timestamp, suitable for passing to
13 | /// or as a guarantee
14 | /// timestamp or as a time travel timestamp.
15 | ///
16 | /// A UTC .
17 | ///
18 | /// A Milvus timestamp. Note that Milvus timestamps contain an opaque internal component which isn't converted, so
19 | /// timestamps cannot be fully round-tripped to .
20 | ///
21 | ///
22 | ///
23 | /// For more information about Milvus timestamps, see .
24 | ///
25 | public static ulong FromDateTime(DateTime dateTime)
26 | => dateTime.Kind == DateTimeKind.Utc
27 | ? ((ulong)dateTime.Ticks - UnixEpochTicks) / 10000 << LogicalBits
28 | : throw new ArgumentException("Only UTC DateTimes are supported", nameof(dateTime));
29 |
30 | ///
31 | /// Converts a Milvus timestamp to a .
32 | ///
33 | /// A Milvus timestamp.
34 | ///
35 | /// A UTC . Note that Milvus timestamps contain an opaque internal component which isn't
36 | /// converted, so timestamps cannot be fully round-tripped to .
37 | ///
38 | ///
39 | /// For more information about Milvus timestamps, see .
40 | ///
41 | public static DateTime ToDateTime(ulong timestamp)
42 | {
43 | // Zero out the 18-bit logical component of the Milvus timestamp, leaving only milliseconds since Unix epoch
44 | timestamp = (timestamp & LogicalBitmask) >> LogicalBits;
45 | DateTimeOffset dto = DateTimeOffset.FromUnixTimeMilliseconds((long)timestamp);
46 | return DateTime.SpecifyKind(dto.DateTime, DateTimeKind.Utc);
47 | }
48 |
49 | private const int LogicalBits = 18;
50 | private const ulong LogicalBitmask = ~(((ulong)1 << LogicalBits) - 1);
51 |
52 | private const ulong UnixEpochTicks = 621355968000000000;
53 | }
54 |
--------------------------------------------------------------------------------
/Milvus.Client/MutationResult.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// Contains results information about an operation which modified rows in a collection.
5 | ///
6 | public sealed class MutationResult
7 | {
8 | internal MutationResult(Grpc.MutationResult mutationResult)
9 | {
10 | InsertCount = mutationResult.InsertCnt;
11 | DeleteCount = mutationResult.DeleteCnt;
12 | UpsertCount = mutationResult.UpsertCnt;
13 | Acknowledged = mutationResult.Acknowledged;
14 | SuccessIndex = mutationResult.SuccIndex.ToList();
15 | ErrorIndex = mutationResult.ErrIndex.ToList();
16 | Timestamp = mutationResult.Timestamp;
17 | Ids = MilvusIds.FromGrpc(mutationResult.IDs);
18 | }
19 |
20 | #pragma warning disable CS1591 // Missing documentation
21 | public bool Acknowledged { get; }
22 | #pragma warning restore CS1591
23 |
24 | ///
25 | /// An opaque identifier for the point in time in which the mutation operation occurred. Can be passed to
26 | /// or as a guarantee
27 | /// timestamp or as a time travel timestamp.
28 | ///
29 | ///
30 | /// For more details, see .
31 | ///
32 | public ulong Timestamp { get; }
33 |
34 | ///
35 | /// The number of inserted rows.
36 | ///
37 | public long InsertCount { get; }
38 |
39 | ///
40 | /// The number of deleted rows.
41 | ///
42 | public long DeleteCount { get; }
43 |
44 | ///
45 | /// The number of upserted rows.
46 | ///
47 | public long UpsertCount { get; }
48 |
49 | ///
50 | /// Success index.
51 | ///
52 | public IReadOnlyList SuccessIndex { get; }
53 |
54 | ///
55 | /// Error index.
56 | ///
57 | public IReadOnlyList ErrorIndex { get; }
58 |
59 | ///
60 | /// The IDs of the rows returned from the search.
61 | ///
62 | public MilvusIds Ids { get; set; }
63 | }
64 |
--------------------------------------------------------------------------------
/Milvus.Client/PersistentSegmentInfo.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// Milvus persistent segment info
5 | ///
6 | public sealed class PersistentSegmentInfo
7 | {
8 | internal PersistentSegmentInfo(
9 | long collectionId, long partitionId, long segmentId, long numRows, Grpc.SegmentState state)
10 | {
11 | CollectionId = collectionId;
12 | PartitionId = partitionId;
13 | SegmentId = segmentId;
14 | NumRows = numRows;
15 | State = (SegmentState)state;
16 | }
17 |
18 | ///
19 | /// Collection id.
20 | ///
21 | public long CollectionId { get; set; }
22 |
23 | ///
24 | /// Number of rows.
25 | ///
26 | public long NumRows { get; set; }
27 |
28 | ///
29 | /// Partition id.
30 | ///
31 | public long PartitionId { get; set; }
32 |
33 | ///
34 | /// Segment id.
35 | ///
36 | public long SegmentId { get; set; }
37 |
38 | ///
39 | /// State
40 | ///
41 | public SegmentState State { get; }
42 |
43 | ///
44 | /// Returns a string that represents the current object.
45 | ///
46 | public override string ToString()
47 | => $"MilvusPersistentSegmentInfo {{{nameof(State)}: {State}, {nameof(SegmentId)}: {SegmentId}, {nameof(CollectionId)}: {CollectionId}, {nameof(PartitionId)}: {PartitionId}, {nameof(NumRows)}: {NumRows}}}";
48 | }
49 |
--------------------------------------------------------------------------------
/Milvus.Client/QueryParameters.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// A set of optional parameters for performing a query via .
5 | ///
6 | public class QueryParameters
7 | {
8 | internal List? OutputFieldsInternal { get; private set; }
9 | internal List? PartitionNamesInternal { get; private set; }
10 |
11 | ///
12 | /// The maximum number of records to return, also known as 'topk'. If set, the sum of this parameter and of
13 | /// must be between 1 and 16384.
14 | ///
15 | public int? Limit { get; set; }
16 |
17 | ///
18 | /// Number of entities to skip during the search. If set, the sum of this parameter and of must
19 | /// be between 1 and 16384.
20 | ///
21 | public int? Offset { get; set; }
22 |
23 | ///
24 | /// An optional list of partitions to be searched in the collection.
25 | ///
26 | public IList PartitionNames => PartitionNamesInternal ??= new();
27 |
28 | ///
29 | /// The names of fields to be returned from the search. Vector fields currently cannot be returned.
30 | ///
31 | public IList OutputFields => OutputFieldsInternal ??= new();
32 |
33 | ///
34 | /// The consistency level to be used in the search. Defaults to the consistency level configured
35 | ///
36 | ///
37 | /// For more details, see .
38 | ///
39 | public ConsistencyLevel? ConsistencyLevel { get; set; }
40 |
41 | ///
42 | /// If set, guarantee that the search operation will be performed after any updates up to the provided timestamp.
43 | /// If a query node isn't yet up to date for the timestamp, it waits until the missing data is received.
44 | /// If unset, the server executes the search immediately.
45 | ///
46 | public ulong? GuaranteeTimestamp { get; set; }
47 |
48 | ///
49 | /// Specifies an optional time travel timestamp; the search will get results based on the data at that point in
50 | /// time.
51 | ///
52 | ///
53 | /// For more details, see .
54 | ///
55 | public ulong? TimeTravelTimestamp { get; set; }
56 | }
57 |
--------------------------------------------------------------------------------
/Milvus.Client/QuerySegmentResult.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// Milvus query segment result.
5 | ///
6 | public sealed class QuerySegmentInfoResult
7 | {
8 | internal QuerySegmentInfoResult(
9 | long collectionId,
10 | string indexName,
11 | long indexId,
12 | long memSize,
13 | IReadOnlyList nodeIds,
14 | long numRows,
15 | long partitionId,
16 | long segmentId,
17 | SegmentState state)
18 | {
19 | CollectionId = collectionId;
20 | IndexName = indexName;
21 | IndexId = indexId;
22 | MemSize = memSize;
23 | NodeIds = nodeIds;
24 | NumRows = numRows;
25 | PartitionId = partitionId;
26 | SegmentId = segmentId;
27 | State = state;
28 | }
29 |
30 | ///
31 | /// Collection id.
32 | ///
33 | public long CollectionId { get; }
34 |
35 | ///
36 | /// Index name.
37 | ///
38 | public string IndexName { get; }
39 |
40 | ///
41 | /// Index id.
42 | ///
43 | public long IndexId { get; }
44 |
45 | ///
46 | /// Memory size.
47 | ///
48 | public long MemSize { get; }
49 |
50 | ///
51 | /// Node id.
52 | ///
53 | public IReadOnlyList NodeIds { get; }
54 |
55 | ///
56 | /// Number of rows.
57 | ///
58 | public long NumRows { get; }
59 |
60 | ///
61 | /// Partition id.
62 | ///
63 | public long PartitionId { get; }
64 |
65 | ///
66 | /// Segment id.
67 | ///
68 | public long SegmentId { get; }
69 |
70 | ///
71 | /// State.
72 | ///
73 | public SegmentState State { get; }
74 | }
75 |
--------------------------------------------------------------------------------
/Milvus.Client/RoleResult.cs:
--------------------------------------------------------------------------------
1 | using Google.Protobuf.Collections;
2 |
3 | namespace Milvus.Client;
4 |
5 | ///
6 | /// Information about a role, returned from and
7 | /// .
8 | ///
9 | ///
10 | /// For more details, see .
11 | ///
12 | public sealed class RoleResult
13 | {
14 | internal RoleResult(string role, RepeatedField users)
15 | {
16 | Role = role;
17 | Users = users.Select(static u => u.Name).ToList();
18 | }
19 |
20 | ///
21 | /// The name of the role.
22 | ///
23 | public string Role { get; }
24 |
25 | ///
26 | /// The names of user in this role. Always empty if includeUserInfo was false in the call to
27 | /// or .
28 | ///
29 | public IReadOnlyList Users { get; }
30 | }
31 |
--------------------------------------------------------------------------------
/Milvus.Client/SearchParameters.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// A set of optional parameters for performing a vector similarity search via
5 | /// .
6 | ///
7 | public class SearchParameters
8 | {
9 | internal List? OutputFieldsInternal { get; private set; }
10 | internal List? PartitionNamesInternal { get; private set; }
11 |
12 | ///
13 | /// Number of entities to skip during the search. The sum of this parameter and Limit should be less than
14 | /// 16384.
15 | ///
16 | public int? Offset { get; set; }
17 |
18 | ///
19 | /// An optional list of partitions to be searched in the collection.
20 | ///
21 | public IList PartitionNames => PartitionNamesInternal ??= new();
22 |
23 | ///
24 | /// The names of fields to be returned from the search. Vector fields currently cannot be returned.
25 | ///
26 | public IList OutputFields => OutputFieldsInternal ??= new();
27 |
28 | ///
29 | /// The consistency level to be used in the search. Defaults to the consistency level configured
30 | ///
31 | ///
32 | /// For more details, see .
33 | ///
34 | public ConsistencyLevel? ConsistencyLevel { get; set; }
35 |
36 | ///
37 | /// If set, guarantee that the search operation will be performed after any updates up to the provided timestamp.
38 | /// If a query node isn't yet up to date for the timestamp, it waits until the missing data is received.
39 | /// If unset, the server executes the search immediately.
40 | ///
41 | public ulong? GuaranteeTimestamp { get; set; }
42 |
43 | ///
44 | /// Specifies an optional time travel timestamp; the search will get results based on the data at that point in
45 | /// time.
46 | ///
47 | ///
48 | /// For more details, see .
49 | ///
50 | public ulong? TimeTravelTimestamp { get; set; }
51 |
52 | ///
53 | /// An optional boolean expression to filter scalar fields before performing the vector similarity search.
54 | ///
55 | public string? Expression { get; set; }
56 |
57 | ///
58 | /// Specifies the decimal place of the returned results.
59 | ///
60 | public long? RoundDecimal { get; set; }
61 |
62 | ///
63 | /// Search parameter(s) specific to the specified index type.
64 | ///
65 | ///
66 | /// See for more information.
67 | ///
68 | public IDictionary ExtraParameters { get; } = new Dictionary();
69 |
70 | ///
71 | /// Whether to ignore growing segments during similarity searches. Defaults to false, indicating that
72 | /// searches involve growing segments.
73 | ///
74 | public bool? IgnoreGrowing { get; private set; }
75 |
76 | ///
77 | /// Group search results by the specified field.
78 | ///
79 | ///
80 | /// See for more information.
81 | ///
82 | public string? GroupByField { get; set; }
83 | }
84 |
--------------------------------------------------------------------------------
/Milvus.Client/SearchResults.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | ///
4 | /// The results from a vector similarity search executed via .
5 | ///
6 | public sealed class SearchResults
7 | {
8 | ///
9 | /// The name of the searched collection.
10 | ///
11 | public required string CollectionName { get; init; }
12 |
13 | ///
14 | /// The fields returned from the search, as specified by .
15 | ///
16 | public required IReadOnlyList FieldsData { get; init; }
17 |
18 | ///
19 | /// The IDs of the rows returned from the search.
20 | ///
21 | public required MilvusIds Ids { get; init; }
22 |
23 | ///
24 | /// The number of queries executed.
25 | ///
26 | public required long NumQueries { get; init; }
27 |
28 | ///
29 | /// The scores for the results.
30 | ///
31 | public required IReadOnlyList Scores { get; init; }
32 |
33 | #pragma warning disable CS1591
34 | public required long Limit { get; init; }
35 |
36 | public required IReadOnlyList Limits { get; init; }
37 | #pragma warning restore CS1591
38 | }
39 |
--------------------------------------------------------------------------------
/Milvus.Client/SegmentState.cs:
--------------------------------------------------------------------------------
1 | namespace Milvus.Client;
2 |
3 | #pragma warning disable CS1591 // Missing documentation for the below
4 |
5 | public enum SegmentState
6 | {
7 | None = Grpc.SegmentState.None,
8 | NotExist = Grpc.SegmentState.NotExist,
9 | Growing = Grpc.SegmentState.Growing,
10 | Sealed = Grpc.SegmentState.Sealed,
11 | Flushed = Grpc.SegmentState.Flushed,
12 | Flushing = Grpc.SegmentState.Flushing,
13 | Dropped = Grpc.SegmentState.Dropped,
14 | Importing = Grpc.SegmentState.Importing,
15 | }
16 |
--------------------------------------------------------------------------------
/Milvus.Client/UserResult.cs:
--------------------------------------------------------------------------------
1 | using Google.Protobuf.Collections;
2 |
3 | namespace Milvus.Client;
4 |
5 | ///
6 | /// Information about a user, returned from and
7 | /// .
8 | ///
9 | ///
10 | /// For more details, see .
11 | ///
12 | public sealed class UserResult
13 | {
14 | internal UserResult(string user, RepeatedField roles)
15 | {
16 | User = user;
17 | Roles = roles.Select(static r => r.Name).ToList();
18 | }
19 |
20 | ///
21 | /// The name of the user.
22 | ///
23 | public string User { get; }
24 |
25 | ///
26 | /// The roles this user has. Always empty if includeRoleInfo was false in the call to
27 | /// or .
28 | ///
29 | public IReadOnlyList Roles { get; }
30 | }
31 |
--------------------------------------------------------------------------------
/Milvus.Client/Utils.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 |
3 | namespace Milvus.Client;
4 |
5 | internal static class Utils
6 | {
7 | internal static async Task Poll(
8 | Func> pollingAction,
9 | string timeoutExceptionMessage,
10 | TimeSpan? waitingInterval = null,
11 | TimeSpan? timeout = null,
12 | IProgress? progress = null,
13 | CancellationToken cancellationToken = default)
14 | {
15 | waitingInterval ??= TimeSpan.FromMilliseconds(500);
16 |
17 | Stopwatch? stopWatch = timeout is null ? null : Stopwatch.StartNew();
18 |
19 | while (true)
20 | {
21 | (bool isComplete, TProgress currentProgress) = await pollingAction().ConfigureAwait(false);
22 |
23 | progress?.Report(currentProgress);
24 |
25 | if (isComplete)
26 | {
27 | return;
28 | }
29 |
30 | if (stopWatch is not null && stopWatch.Elapsed + waitingInterval.Value >= timeout)
31 | {
32 | throw new TimeoutException(timeoutExceptionMessage);
33 | }
34 |
35 | await Task.Delay(waitingInterval.Value, cancellationToken).ConfigureAwait(false);
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # milvus-sdk-csharp
2 |
3 |
8 |
9 |
10 |

11 |
12 |
13 | C# SDK for [Milvus](https://github.com/milvus-io/milvus).
14 |
15 | **Supported Net versions:**
16 | * .NET Core 2.1+
17 | * .NET Framework 4.6.1+
18 |
19 | **[NuGet](https://www.nuget.org/packages/Milvus.Client/)**
20 |
21 | Milvus.Client is delivered via NuGet package manager.
22 |
23 | | Nuget version | Branch | Description | Milvus version
24 | | --- | --- | --- | --- |
25 | | v2.2.2 | main | Support grpc only | 2.2.x |
26 | | v2.2.1 | main | Support restfulapi and grpc[**Obsolete**] | 2.2.x |
27 | | v2.2.0 | 2.2 | Support grpc only[**Obsolete**] | 2.2.x |
28 |
29 | ## Docs 📚
30 |
31 | * [Quick Start](./docs/readme.md)
32 | * [Milvus docs](https://milvus.io/docs)
33 |
34 | ### Jupyter Notebooks 📙
35 |
36 | You can find Jupyter notebooks in the [docs/notebooks](./docs/notebooks) folder.
37 |
38 | [](https://codespaces.new/milvus-io/milvus-sdk-csharp)
39 |
40 | * [00.Settings.ipynb](./docs/notebooks/00.Settings.ipynb)
41 | * [01.Connect to milvus.ipynb](./docs/notebooks/01.Connect%20to%20milvus.ipynb)
42 | * [02.Create a Collection.ipynb](./docs/notebooks/02.Create%20a%20Collection.ipynb)
43 | * [03.Create a Partition.ipynb](./docs/notebooks/03.Create%20a%20Partition.ipynb)
44 | * [04.Insert Vectors.ipynb](./docs/notebooks/04.Insert%20Vectors.ipynb)
45 | * [05.Build an Index on Vectors.ipynb](./docs/notebooks/05.Build%20an%20Index%20on%20Vectors.ipynb)
46 | * [06.Search.ipynb](./docs/notebooks/06.Search.ipynb)
47 | * [07.Query.ipynb](./docs/notebooks/07.Query.ipynb)
48 |
49 | > Requirements: C# notebooks require .NET 7 and the VS Code Polyglot extension.
50 |
--------------------------------------------------------------------------------
/Version.props:
--------------------------------------------------------------------------------
1 |
2 |
3 | 2.4.0
4 |
5 |
6 |
--------------------------------------------------------------------------------
/docs/api_reference/Alias/AlterAliasAsync().md:
--------------------------------------------------------------------------------
1 | # AlterAliasAsync()
2 |
3 | Alters an alias to point to a new collection.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await milvusClient.AlterAliasAsync(collectionName, alias, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `collectionName` | The name of the collection to which the alias should point. | `string` | True |
16 | | `alias` | The alias to be altered. | `string` | True |
17 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
18 |
19 | ## Return
20 |
21 | This method does not return any value.
22 |
--------------------------------------------------------------------------------
/docs/api_reference/Alias/CreateAliasAsync().md:
--------------------------------------------------------------------------------
1 | # CreateAliasAsync()
2 |
3 | Creates an alias for a collection.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await milvusClient.CreateAliasAsync(collectionName, alias, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `collectionName` | The name of the collection for which to create the alias. | `string` | True |
16 | | `alias` | The alias to be created. | `string` | True |
17 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
18 |
19 | ## Return
20 |
21 | This method does not return any value.
22 |
--------------------------------------------------------------------------------
/docs/api_reference/Alias/DropAliasAsync().md:
--------------------------------------------------------------------------------
1 | # DropAliasAsync()
2 |
3 | Drops an alias.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await milvusClient.DropAliasAsync(alias, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `alias` | The alias to be dropped. | `string` | True |
16 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
17 |
18 | ## Return
19 |
20 | This method does not return any value.
21 |
--------------------------------------------------------------------------------
/docs/api_reference/Collection/CompactAsync().md:
--------------------------------------------------------------------------------
1 | # CompactAsync()
2 |
3 | Compacts the collection.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.CompactAsync(newName, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
16 |
17 | ## Return
18 |
19 | The compaction ID.
--------------------------------------------------------------------------------
/docs/api_reference/Collection/DeleteAsync().md:
--------------------------------------------------------------------------------
1 | # DeleteAsync()()
2 |
3 | Deletes rows from a collection by given expression.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.DeleteAsync(expression, partitionName = null, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `expression` | A boolean expression determining which rows are to be deleted. | `string` | True |
16 | | `partitionName` | An optional name of a partition from which rows are to be deleted. | `string?` | False |
17 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
18 |
19 | ## Return
20 |
21 | A `MutationResult` containing information about the drop operation.
22 |
--------------------------------------------------------------------------------
/docs/api_reference/Collection/DescribeAsync().md:
--------------------------------------------------------------------------------
1 | # DescribeAsync()
2 |
3 | Describes a collection, returning information about its configuration and schema.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.DescribeAsync(cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
16 |
17 | ## Return
18 |
19 | A description of the collection.
20 |
--------------------------------------------------------------------------------
/docs/api_reference/Collection/DropAsync().md:
--------------------------------------------------------------------------------
1 | # DropAsync()
2 |
3 | Drops a collection.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.DropAsync(cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
16 |
17 | ## Return
18 |
19 | This method does not return any value.
20 |
--------------------------------------------------------------------------------
/docs/api_reference/Collection/FlushAsync().md:
--------------------------------------------------------------------------------
1 | # FlushAsync()
2 |
3 | Flushes collection data to disk, required only in order to get up-to-date statistics.
4 | This method will be removed in a future version.
5 |
6 | ## Invocation
7 |
8 | ```c#
9 | await collection.FlushAsync(cancellationToken = default);
10 | ```
11 |
12 | ## Parameters
13 |
14 | | Parameter | Description | Type | Required |
15 | | ------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
16 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
17 |
18 | ## Return
19 |
20 | A `FlushResult` containing information about the flush operation.
21 |
--------------------------------------------------------------------------------
/docs/api_reference/Collection/GetEntityCountAsync().md:
--------------------------------------------------------------------------------
1 | # GetEntityCountAsync()
2 |
3 | Retrieves the current number of entities in the collection. Call `FlushAsync` before invoking this method to ensure up-to-date results.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.GetEntityCountAsync(cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
16 |
17 | ## Return
18 |
19 | The number of entities currently in the collection.
20 |
--------------------------------------------------------------------------------
/docs/api_reference/Collection/GetLoadingProgressAsync().md:
--------------------------------------------------------------------------------
1 | # GetLoadingProgressAsync()
2 |
3 | Returns the loading progress for a collection, and optionally one or more of its partitions.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.GetLoadingProgressAsync(partitionNames = null, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `partitionNames` | An optional list of partition names for which to check the loading progress. | `IReadOnlyList?` | False |
16 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is . | `CancellationToken` | False |
17 |
18 | ## Return
19 |
20 | The loading progress of the collection.
21 |
--------------------------------------------------------------------------------
/docs/api_reference/Collection/InsertAsync().md:
--------------------------------------------------------------------------------
1 | # InsertAsync()
2 |
3 | Inserts rows of data into a collection.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.InsertAsync(data, partitionName = null, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `data` | The field data to insert; each field contains a list of row values. | `IReadOnlyList` | True |
16 | | `partitionName` | An optional name of a partition to insert into. | `string?` | False |
17 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
18 |
19 | ## Return
20 |
21 | This method does not return any value.
22 |
23 | ## Example
24 |
25 | ```c#
26 | await milvusClient.GetCollection("book").InsertAsync(new FieldData[]
27 | {
28 | FieldData.Create("book_id", bookIds),
29 | FieldData.Create("word_count", wordCounts),
30 | FieldData.CreateFloatVector("book_intro", bookIntros)
31 | });
32 | ```
33 |
--------------------------------------------------------------------------------
/docs/api_reference/Collection/LoadAsync().md:
--------------------------------------------------------------------------------
1 | # LoadAsync()
2 |
3 | Loads a collection into memory so that it can be searched or queried.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.LoadAsync(replicaNumber = null, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `replicaNumber` | An optional replica number to load. | `int?` | False |
16 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
17 |
18 | ## Return
19 |
20 | This method does not return any value.
21 |
--------------------------------------------------------------------------------
/docs/api_reference/Collection/QueryAsync().md:
--------------------------------------------------------------------------------
1 | # QueryAsync()
2 |
3 | Retrieves rows from a collection via scalar filtering based on a boolean expression.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.QueryAsync(expression, parameters = null, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `expression` | A boolean expression determining which rows are to be returned. | `string` | True |
16 | | `parameters` | Various additional optional parameters to configure the query. | `QueryParameters?` | False |
17 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
18 |
19 | ## Return
20 |
21 | A list of `FieldData` instances with the query results.
22 |
23 | ## Example
24 |
25 | ```c#
26 | var results = await Client.GetCollection("book").QueryAsync(
27 | expression: "book_id in [2,4,6,8]",
28 | new QueryParameters
29 | {
30 | Offset = 0,
31 | Limit = 10,
32 | OutputFields = { "book_id", "book_intro" }
33 | });
34 | ```
35 |
--------------------------------------------------------------------------------
/docs/api_reference/Collection/ReleaseAsync().md:
--------------------------------------------------------------------------------
1 | # ReleaseAsync()
2 |
3 | Releases a collection that has been previously loaded.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.ReleaseAsync(cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
16 |
17 | ## Return
18 |
19 | This method does not return any value.
20 |
--------------------------------------------------------------------------------
/docs/api_reference/Collection/RenameAsync().md:
--------------------------------------------------------------------------------
1 | # RenameAsync()
2 |
3 | Renames a collection.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.RenameAsync(newName, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `newName` | The new collection name. | `string` | True |
16 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
17 |
18 | ## Return
19 |
20 | This method does not return any value.
21 |
--------------------------------------------------------------------------------
/docs/api_reference/Collection/SearchAsync().md:
--------------------------------------------------------------------------------
1 | # SearchAsync()()
2 |
3 | Perform a vector similarity search.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.SearchAsync(vectorFieldName, vectors, metricType, limit, parameters = null, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- | -------- |
15 | | `vectorFieldName` | The name of the vector field to search in. | `string` | True |
16 | | `vectors` | The set of vectors to send as input for the similarity search. | `IReadOnlyList>` | True |
17 | | `metricType` | Method used to measure the distance between vectors during search. Must correspond to the metric type specified when building the index. | `SimilarityMetricType` | True |
18 | | `limit` | The maximum number of records to return, also known as 'topk'. Must be between 1 and 16384. | `int` | True |
19 | | `parameters` | Various additional optional parameters to configure the similarity search. | `SearchParameters` | False |
20 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
21 |
22 | ## Return
23 |
24 | The results of the vector similarity search.
25 |
26 | ## Example
27 |
28 | ```c#
29 | var results = await milvusClient.GetCollection("book").SearchAsync(
30 | vectorFieldName: "book_intro",
31 | vectors: new ReadOnlyMemory[] { new[] { 0.1f, 0.2f } },
32 | SimilarityMetricType.L2,
33 | // the sum of `offset` in `parameters` and `limit` should be less than 16384.
34 | limit: 10,
35 | new SearchParameters
36 | {
37 | OutputFields = { "title" },
38 | ConsistencyLevel = ConsistencyLevel.Strong,
39 | Offset = 5,
40 | ExtraParameters = { ["nprobe"] = "1024" }
41 | });
42 | ```
43 |
--------------------------------------------------------------------------------
/docs/api_reference/Collection/WaitForCollectionLoadAsync().md:
--------------------------------------------------------------------------------
1 | # WaitForCollectionLoadAsync()
2 |
3 | Polls Milvus for loading progress of a collection until it is fully loaded.
4 | To perform a single progress check, use `GetLoadingProgressAsync`.
5 |
6 | ## Invocation
7 |
8 | ```c#
9 | await collection.WaitForCollectionLoadAsync(partitionNames = null, waitingInterval = null, timeout = null, progress = null, cancellationToken = default);
10 | ```
11 |
12 | ## Parameters
13 |
14 | | Parameter | Description | Type | Required |
15 | | ------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
16 | | `partitionNames` | An optional list of partition names for which to check the loading progress. | `IReadOnlyList?` | False |
17 | | `waitingInterval` | Waiting interval. Defaults to 500 milliseconds. | `TimeSpan?` | False |
18 | | `timeout` | How long to poll for before throwing a `TimeoutException`. | `TimeSpan?` | False |
19 | | `progress` | Provides information about the progress of the loading operation. | `IProgress?` | False |
20 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
21 |
22 | ## Return
23 |
24 | This method does not return any value.
25 |
--------------------------------------------------------------------------------
/docs/api_reference/Database/CreateDatabaseAsync().md:
--------------------------------------------------------------------------------
1 | # CreateDatabaseAsync()
2 |
3 | Creates a new database.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await milvusClient.CreateDatabaseAsync(databaseName, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `databaseName` | The name of the new database to be created. | `string` | True |
16 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
17 |
18 | ## Return
19 |
20 | This method does not return any value.
21 |
--------------------------------------------------------------------------------
/docs/api_reference/Database/DropDatabaseAsync().md:
--------------------------------------------------------------------------------
1 | # DropDatabaseAsync()
2 |
3 | Drops a database.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await milvusClient.DropDatabaseAsync(databaseName, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `databaseName` | The name of the database to be dropped. | `string` | True |
16 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
17 |
18 | ## Return
19 |
20 | This method does not return any value.
21 |
--------------------------------------------------------------------------------
/docs/api_reference/Database/ListDatabasesAsync().md:
--------------------------------------------------------------------------------
1 | # ListDatabasesAsync()
2 |
3 | List all available databases.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await milvusClient.ListDatabasesAsync(cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
16 |
17 | ## Return
18 |
19 | The list of available databases.
20 |
--------------------------------------------------------------------------------
/docs/api_reference/Index/CreateIndexAsync().md:
--------------------------------------------------------------------------------
1 | # CreateIndexAsync()
2 |
3 | Creates an index.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.CreateIndexAsync(fieldName, indexType = null, metricType = null, indexName = null, extraParams = null, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `fieldName` | The name of the field in the collection for which the index will be created. | `string` | True |
16 | | `indexType` | The type of the index to be created. | `IndexType?` | False |
17 | | `metricType` | Method used to measure the distance between vectors during search. | `SimilarityMetricType?` | False |
18 | | `indexName` | An optional name for the index to be created. | `string?` | False |
19 | | `extraParams` | Extra parameters specific to each index type; consult the documentation for your index type for more details. | `IDictionary?` | False |
20 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
21 |
22 | ## Return
23 |
24 | This method does not return any value.
25 |
--------------------------------------------------------------------------------
/docs/api_reference/Index/DescribeIndexAsync().md:
--------------------------------------------------------------------------------
1 | # DescribeIndexAsync()
2 |
3 | Describes an index, returning information about its configuration.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.DescribeIndexAsync(fieldName, indexName = null, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `fieldName` | The name of the field which has the index to be described. | `string` | True |
16 | | `indexName` | An optional name of the index to be described. | `string?` | False |
17 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
18 |
19 | ## Return
20 |
21 | A list of `MilvusIndexInfo` containing information about the matching indexes.
22 |
--------------------------------------------------------------------------------
/docs/api_reference/Index/DropIndexAsync().md:
--------------------------------------------------------------------------------
1 | # DropIndexAsync()
2 |
3 | Drops an index.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.DropIndexAsync(fieldName, indexName = null, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `fieldName` | The name of the field which has the index to be dropped. | `string` | True |
16 | | `indexName` | An optional name for the index to be dropped. | `string?` | False |
17 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
18 |
19 | ## Return
20 |
21 | This method does not return any value.
22 |
--------------------------------------------------------------------------------
/docs/api_reference/Index/GetIndexBuildProgressAsync().md:
--------------------------------------------------------------------------------
1 | # GetIndexBuildProgressAsync()
2 |
3 | Gets the build progress of an index.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.GetIndexBuildProgressAsync(fieldName, indexName = null, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `fieldName` | The name of the field which has the index. | `string` | True |
16 | | `indexName` | An optional name of the index. | `string?` | False |
17 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
18 |
19 | ## Return
20 |
21 | An `IndexBuildProgress` with the number of rows indexed and the total number of rows.
22 |
--------------------------------------------------------------------------------
/docs/api_reference/Index/GetIndexStateAsync().md:
--------------------------------------------------------------------------------
1 | # GetIndexStateAsync()
2 |
3 | Gets the state of an index.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.GetIndexStateAsync(fieldName, indexName = null, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `fieldName` | The name of the field which has the index to get the state for. | `string` | True |
16 | | `indexName` | An optional name of the index to get the state for. | `string?` | False |
17 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
18 |
19 | ## Return
20 |
21 | The state of the index.
22 |
--------------------------------------------------------------------------------
/docs/api_reference/Index/WaitForIndexBuildAsync().md:
--------------------------------------------------------------------------------
1 | # WaitForIndexBuildAsync()
2 |
3 | Polls Milvus for building progress of an index until it is fully built.
4 | To perform a single progress check, use `GetIndexBuildProgressAsync`.
5 |
6 | ## Invocation
7 |
8 | ```c#
9 | await collection.WaitForIndexBuildAsync(fieldName, indexName = null, waitingInterval = null, timeout = null, progress = null, cancellationToken = default);
10 | ```
11 |
12 | ## Parameters
13 |
14 | | Parameter | Description | Type | Required |
15 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
16 | | `fieldName` | The name of the field which has the index. | `string` | True |
17 | | `indexName` | An optional name of the index. | `string?` | False |
18 | | `waitingInterval` | Waiting interval. Defaults to 500 milliseconds. | `TimeSpan?` | False |
19 | | `timeout` | How long to poll for before throwing a `TimeoutException`. | `TimeSpan?` | False |
20 | | `progress` | Provides information about the progress of the loading operation. | `IProgress?` | False |
21 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
22 |
23 | ## Return
24 |
25 | This method does not return any value.
26 |
--------------------------------------------------------------------------------
/docs/api_reference/Partition/CreatePartitionAsync().md:
--------------------------------------------------------------------------------
1 | # CreatePartitionAsync()
2 |
3 | Creates a partition.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.CreatePartitionAsync(partitionName, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `partitionName` | The name of partition to be created. | `string` | True |
16 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
17 |
18 | ## Return
19 |
20 | This method does not return any value.
21 |
--------------------------------------------------------------------------------
/docs/api_reference/Partition/DropPartitionAsync().md:
--------------------------------------------------------------------------------
1 | # DropPartitionAsync()
2 |
3 | Creates a partition.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.DropPartitionAsync(partitionName, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `partitionName` | The name of partition to be dropped. | `string` | True |
16 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
17 |
18 | ## Return
19 |
20 | This method does not return any value.
21 |
--------------------------------------------------------------------------------
/docs/api_reference/Partition/GetPartitionStatisticsAsync().md:
--------------------------------------------------------------------------------
1 | # GetPartitionStatisticsAsync()
2 |
3 | Retrieves statistics for a partition.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.GetPartitionStatisticsAsync(partitionName, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `partitionName` | The name of partition for which statistics are to be retrieved. | `string` | True |
16 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
17 |
18 | ## Return
19 |
20 | A dictionary containing statistics about the partition.
21 |
--------------------------------------------------------------------------------
/docs/api_reference/Partition/HasPartitionAsync().md:
--------------------------------------------------------------------------------
1 | # HasPartitionAsync()
2 |
3 | Checks whether a partition exists.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.HasPartitionAsync(partitionName, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `partitionName` | The name of partition to be checked. | `string` | True |
16 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
17 |
18 | ## Return
19 |
20 | Whether the partition exists or not.
21 |
--------------------------------------------------------------------------------
/docs/api_reference/Partition/LoadPartitionAsync().md:
--------------------------------------------------------------------------------
1 | # LoadPartitionAsync()
2 |
3 | Loads a partition into memory so that it can be searched or queries.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.LoadPartitionAsync(partitionName, replicaNumber = 1, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `partitionName` | The name of partition to be loaded. | `string` | True |
16 | | `replicaNumber` | An optional replica number to load. | `int?` | False |
17 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
18 |
19 | ## Return
20 |
21 | This method does not return any value.
22 |
--------------------------------------------------------------------------------
/docs/api_reference/Partition/LoadPartitionsAsync().md:
--------------------------------------------------------------------------------
1 | # LoadPartitionsAsync()
2 |
3 | Loads partitions into memory so that they can be searched or queries.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.CreatePartitionsAsync(partitionNames, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `partitionNames` | The names of the partitions to be loaded. | `IReadOnlyList` | True |
16 | | `replicaNumber` | An optional replica number to load. | `int?` | True |
17 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
18 |
19 | ## Return
20 |
21 | This method does not return any value.
22 |
--------------------------------------------------------------------------------
/docs/api_reference/Partition/ReleasePartitionAsync().md:
--------------------------------------------------------------------------------
1 | # ReleasePartitionAsync()
2 |
3 | Releases a loaded partition from memory.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.ReleasePartitionAsync(partitionName, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `partitionName` | The name of partition to be released. | `string` | True |
16 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
17 |
18 | ## Return
19 |
20 | This method does not return any value.
21 |
--------------------------------------------------------------------------------
/docs/api_reference/Partition/ReleasePartitionsAsync().md:
--------------------------------------------------------------------------------
1 | # ReleasePartitionAsync()
2 |
3 | Releases loaded partitions from memory.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.ReleasePartitionsAsync(partitionNames, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `partitionNames` | The names of the partitions to be released. | `IReadOnlyList` | True |
16 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
17 |
18 | ## Return
19 |
20 | This method does not return any value.
21 |
--------------------------------------------------------------------------------
/docs/api_reference/Partition/ShowPartitionsAsync().md:
--------------------------------------------------------------------------------
1 | # ShowPartitionsAsync()
2 |
3 | Lists all partitions defined for a collection.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await collection.ShowPartitionsAsync(cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
16 |
17 | ## Return
18 |
19 | A list of `MilvusPartition` instances providing information about all partitions in the collection.
20 |
--------------------------------------------------------------------------------
/docs/api_reference/Role/AddUserToRoleAsync().md:
--------------------------------------------------------------------------------
1 | # AddUserToRoleAsync()
2 |
3 | Adds a user to a role.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await milvusClient.AddUserToRoleAsync(username, roleName, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `username` | The name of the username to be added to the role. | `string` | True |
16 | | `roleName` | The name of the role the user will be added to. | `string` | True |
17 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
18 |
19 | ## Return
20 |
21 | This method does not return any value.
22 |
--------------------------------------------------------------------------------
/docs/api_reference/Role/CreateRoleAsync().md:
--------------------------------------------------------------------------------
1 | # CreateRoleAsync()
2 |
3 | Creates a role.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await milvusClient.CreateRoleAsync(roleName, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `roleName` | The name of the role to be created. | `string` | True |
16 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
17 |
18 | ## Return
19 |
20 | This method does not return any value.
21 |
--------------------------------------------------------------------------------
/docs/api_reference/Role/DropRoleAsync().md:
--------------------------------------------------------------------------------
1 | # DropRoleAsync()
2 |
3 | Drops a role.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await milvusClient.DropRoleAsync(roleName, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `roleName` | The name of the role to be dropped. | `string` | True |
16 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
17 |
18 | ## Return
19 |
20 | This method does not return any value.
21 |
--------------------------------------------------------------------------------
/docs/api_reference/Role/GrantRolePrivilegeAsync().md:
--------------------------------------------------------------------------------
1 | # GrantRolePrivilegeAsync()
2 |
3 | Revokes a privilege from a role.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await milvusClient.GrantRolePrivilegeAsync(roleName, object, objectName, privilege, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `roleName` | The name of the role to be granted a privilege. | `string` | True |
16 | | `object` | A string describing the object type on which the privilege is to be granted, e.g. `"Collection"`. | `string` | True |
17 | | `objectName` | A string describing the specific object on which the privilege will be granted. Can be `"*"`. | `string` | True |
18 | | `privilege` | A string describing the privilege to be granted, e.g. `"Search"`. | `string` | True |
19 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
20 |
21 | ## Return
22 |
23 | This method does not return any value.
24 |
--------------------------------------------------------------------------------
/docs/api_reference/Role/ListGrantsForRoleAsync().md:
--------------------------------------------------------------------------------
1 | # ListGrantsForRoleAsync()
2 |
3 | Lists a grant info for the role and the specific object.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await milvusClient.ListGrantsForRoleAsync(roleName, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `roleName` | The name of the role. | `string` | True |
16 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
17 |
18 | ## Return
19 |
20 | A list of `GrantEntity` instances describing the grants assigned to the role.
21 |
--------------------------------------------------------------------------------
/docs/api_reference/Role/RemoveUserFromRoleAsync().md:
--------------------------------------------------------------------------------
1 | # RemoveUserFromRoleAsync()
2 |
3 | Removes a user from a role.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await milvusClient.RemoveUserFromRoleAsync(username, roleName, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `username` | The name of the user to be removed from the role. | `string` | True |
16 | | `roleName` | The name of the role from which the user is to be removed. | `string` | True |
17 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
18 |
19 | ## Return
20 |
21 | This method does not return any value.
22 |
--------------------------------------------------------------------------------
/docs/api_reference/Role/RevokeRolePrivilegeAsync().md:
--------------------------------------------------------------------------------
1 | # RevokeRolePrivilegeAsync()
2 |
3 | Revokes a privilege from a role.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await milvusClient.RevokeRolePrivilegeAsync(roleName, object, objectName, privilege, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `roleName` | The name of the role to be created. | `string` | True |
16 | | `object` | A string describing the object type on which the privilege is to be revoked, e.g. `"Collection"`. | `string` | True |
17 | | `objectName` | A string describing the specific object on which the privilege will be revoked. Can be `"*"`. | `string` | True |
18 | | `privilege` | A string describing the privilege to be revoked, e.g. `"Search"`. | `string` | True |
19 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
20 |
21 | ## Return
22 |
23 | This method does not return any value.
24 |
--------------------------------------------------------------------------------
/docs/api_reference/Role/SelectAllRolesAsync().md:
--------------------------------------------------------------------------------
1 | # SelectAllRolesAsync()
2 |
3 | Gets information about all roles defined in Milvus, including optionally all their users.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await milvusClient.SelectAllRolesAsync(includeUserInfo = true, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `includeUserInfo` | Whether to include user information in the results. | `bool` | False |
16 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
17 |
18 | ## Return
19 |
20 | A list of `RoleResult` instances containing information about all the roles.
21 |
--------------------------------------------------------------------------------
/docs/api_reference/Role/SelectAllUsersAsync().md:
--------------------------------------------------------------------------------
1 | # SelectAllUsersAsync()
2 |
3 | Gets information about all users defined in Milvus, including optionally all their users.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await milvusClient.SelectAllUsersAsync(includeRoleInfo = true, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `includeRoleInfo` | Whether to include role information in the results. | `bool` | False |
16 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
17 |
18 | ## Return
19 |
20 | A list of `UserResult` instances containing information about all the users.
21 |
--------------------------------------------------------------------------------
/docs/api_reference/Role/SelectGrantForRoleAndObjectAsync().md:
--------------------------------------------------------------------------------
1 | # SelectGrantForRoleAndObjectAsync()
2 |
3 | Creates a role.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await milvusClient.SelectGrantForRoleAndObjectAsync(roleName, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `roleName` | The name of the role to be created. | `string` | True |
16 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
17 |
18 | ## Return
19 |
20 | This method does not return any value.
21 |
--------------------------------------------------------------------------------
/docs/api_reference/Role/SelectRoleAsync().md:
--------------------------------------------------------------------------------
1 | # SelectRoleAsync()
2 |
3 | Gets information about a role, including optionally all its users.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await milvusClient.SelectRoleAsync(roleName, includeUserInfo = true, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `roleName` | The name of the role to be selected. | `string` | True |
16 | | `includeUserInfo` | Whether to include user information in the results. | `bool` | False |
17 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
18 |
19 | ## Return
20 |
21 | A `RoleResult` instance containing information about the role, or `null` if the role does not exist.
22 |
--------------------------------------------------------------------------------
/docs/api_reference/Role/SelectUserAsync().md:
--------------------------------------------------------------------------------
1 | # SelectUserAsync()
2 |
3 | Gets information about a user, including optionally all its roles.
4 |
5 | ## Invocation
6 |
7 | ```c#
8 | await milvusClient.SelectUserAsync(username, includeRoleInfo = true, cancellationToken = default);
9 | ```
10 |
11 | ## Parameters
12 |
13 | | Parameter | Description | Type | Required |
14 | | ------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------- |
15 | | `username` | The name of the user to be selected. | `string` | True |
16 | | `includeRoleInfo` | Whether to include role information in the results. | `bool` | False |
17 | | `cancellationToken` | The token to monitor for cancellation requests. The default value is `CancellationToken.None`. | `CancellationToken` | False |
18 |
19 | ## Return
20 |
21 | A `UserResult` instance containing information about the user, or `null` if the user does not exist.
22 |
--------------------------------------------------------------------------------
/docs/notebooks/00.Settings.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "attachments": {},
5 | "cell_type": "markdown",
6 | "metadata": {},
7 | "source": [
8 | "# Welcome\n",
9 | "\n",
10 | "🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉\n",
11 | "\n",
12 | "Before starting we need to setup some configuration, to connect your milvus.\n",
13 | "\n",
14 | "When using this notebook for milvus, the kernel needs some settings like URL and\n",
15 | "credentials to the milvus.\n",
16 | "\n",
17 | "**If you don't know how to deply a milvus server, try [zilliz cloud](https://cloud.zilliz.com/).**\n",
18 | "\n",
19 | ""
20 | ]
21 | },
22 | {
23 | "attachments": {},
24 | "cell_type": "markdown",
25 | "metadata": {},
26 | "source": [
27 | "## First step - Config your milvus server.\n",
28 | "\n",
29 | "🧑💻🧑💻🧑💻🧑💻\n",
30 | "\n",
31 | "Run the following code. If you need to find the value and copy and paste, you can\n",
32 | "re-run the code and continue from where you left off.\n",
33 | "\n",
34 | "Milvus supports two ports, port 19530 and port 9091:\n",
35 | "\n",
36 | "* Port 19530 is for gRPC, it may be not same when you use zilliz clound.\n",
37 | "* Port 9091 is for RESTful API."
38 | ]
39 | },
40 | {
41 | "cell_type": "code",
42 | "execution_count": 8,
43 | "metadata": {
44 | "dotnet_interactive": {
45 | "language": "csharp"
46 | },
47 | "polyglot_notebook": {
48 | "kernelName": "csharp"
49 | },
50 | "vscode": {
51 | "languageId": "polyglot-notebook"
52 | }
53 | },
54 | "outputs": [],
55 | "source": [
56 | "#!import config/Settings.cs\n",
57 | "\n",
58 | "string endPoint = await Settings.AskEndpoint();\n",
59 | "await Settings.AskPort();\n",
60 | "\n",
61 | "await Settings.AskUsername();\n",
62 | "await Settings.AskPassword();"
63 | ]
64 | },
65 | {
66 | "attachments": {},
67 | "cell_type": "markdown",
68 | "metadata": {},
69 | "source": [
70 | "If the code above doesn't show any error, you're good to go and run the other notebooks.\n",
71 | "\n",
72 | "## Resetting the configuration\n",
73 | "\n",
74 | "If you want to reset the configuration and start again, please uncomment and run the code below.\n",
75 | "You can also edit the [config/settings.json](config/settings.json) manually if you prefer."
76 | ]
77 | },
78 | {
79 | "cell_type": "code",
80 | "execution_count": 7,
81 | "metadata": {
82 | "dotnet_interactive": {
83 | "language": "csharp"
84 | },
85 | "polyglot_notebook": {
86 | "kernelName": "csharp"
87 | },
88 | "vscode": {
89 | "languageId": "polyglot-notebook"
90 | }
91 | },
92 | "outputs": [
93 | {
94 | "name": "stdout",
95 | "output_type": "stream",
96 | "text": [
97 | "Settings deleted. Run the notebook again to configure your AI backend.\r\n"
98 | ]
99 | }
100 | ],
101 | "source": [
102 | "#!import config/Settings.cs\n",
103 | "\n",
104 | "// Uncomment this line to reset your settings and delete the file from disk.\n",
105 | "// Settings.Reset();"
106 | ]
107 | }
108 | ],
109 | "metadata": {
110 | "language_info": {
111 | "name": "python"
112 | },
113 | "orig_nbformat": 4
114 | },
115 | "nbformat": 4,
116 | "nbformat_minor": 2
117 | }
118 |
--------------------------------------------------------------------------------
/docs/notebooks/03.Create a Partition.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "attachments": {},
5 | "cell_type": "markdown",
6 | "metadata": {},
7 | "source": [
8 | "# [Create a Partition](https://milvus.io/docs/v2.3.0-beta/create_partition.md)\n",
9 | "\n",
10 | "> This topic describes how to create a partition in Milvus.\n",
11 | "\n",
12 | "**If you are using zillz cloud, skip this chapter because it's a deny api**"
13 | ]
14 | },
15 | {
16 | "attachments": {},
17 | "cell_type": "markdown",
18 | "metadata": {},
19 | "source": [
20 | "## Connect to milvus"
21 | ]
22 | },
23 | {
24 | "cell_type": "code",
25 | "execution_count": 3,
26 | "metadata": {
27 | "dotnet_interactive": {
28 | "language": "csharp"
29 | },
30 | "polyglot_notebook": {
31 | "kernelName": "csharp"
32 | },
33 | "vscode": {
34 | "languageId": "polyglot-notebook"
35 | }
36 | },
37 | "outputs": [
38 | {
39 | "data": {
40 | "text/html": [
41 | "Installed Packages- Milvus.Client, 2.2.2-preview.2
"
42 | ]
43 | },
44 | "metadata": {},
45 | "output_type": "display_data"
46 | },
47 | {
48 | "data": {
49 | "text/html": [
50 | "{MilvusClient:localhost:19530}
"
82 | ]
83 | },
84 | "metadata": {},
85 | "output_type": "display_data"
86 | }
87 | ],
88 | "source": [
89 | "#r \"nuget: Milvus.Client, 2.2.2-preview.2\"\n",
90 | "#!import config/Settings.cs\n",
91 | "\n",
92 | "using Milvus.Client;\n",
93 | "using InteractiveKernel = Microsoft.DotNet.Interactive.Kernel;\n",
94 | "\n",
95 | "//Connect to milvus\n",
96 | "(string endpoint, int port, string userName, string password) = Settings.LoadFromFile();\n",
97 | "\n",
98 | "MilvusClient milvusClient = default;\n",
99 | "\n",
100 | "milvusClient = new MilvusClient(endpoint, port, userName, password, null);\n",
101 | "milvusClient\n"
102 | ]
103 | },
104 | {
105 | "cell_type": "code",
106 | "execution_count": 4,
107 | "metadata": {
108 | "dotnet_interactive": {
109 | "language": "csharp"
110 | },
111 | "polyglot_notebook": {
112 | "kernelName": "csharp"
113 | },
114 | "vscode": {
115 | "languageId": "polyglot-notebook"
116 | }
117 | },
118 | "outputs": [
119 | {
120 | "data": {
121 | "text/html": [
122 | ""
154 | ]
155 | },
156 | "metadata": {},
157 | "output_type": "display_data"
158 | }
159 | ],
160 | "source": [
161 | "string collectionName = \"book\";\n",
162 | "string partitionName = \"novel\";\n",
163 | "\n",
164 | "MilvusCollection collection = milvusClient.GetCollection(collectionName);\n",
165 | "await collection.CreatePartitionAsync(partitionName);\n",
166 | "\n",
167 | "bool result = await collection.HasPartitionAsync(partitionName);\n",
168 | "\n",
169 | "result"
170 | ]
171 | }
172 | ],
173 | "metadata": {
174 | "language_info": {
175 | "name": "python"
176 | },
177 | "orig_nbformat": 4
178 | },
179 | "nbformat": 4,
180 | "nbformat_minor": 2
181 | }
182 |
--------------------------------------------------------------------------------
/docs/notebooks/05.Build an Index on Vectors.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "attachments": {},
5 | "cell_type": "markdown",
6 | "metadata": {},
7 | "source": [
8 | "# [Build an Index on Vectors](https://milvus.io/docs/v2.3.0-beta/build_index.md)\n",
9 | "\n",
10 | "> This guide describes how to build an index on vectors in Milvus.\n",
11 | "\n",
12 | "Vector indexes are an organizational unit of metadata used to accelerate vector similarity search. Without the index built on vectors, Milvus will perform a brute-force search by default.\n",
13 | "\n",
14 | "See Vector Index for more information about the mechanism and varieties of vector indexes."
15 | ]
16 | },
17 | {
18 | "attachments": {},
19 | "cell_type": "markdown",
20 | "metadata": {},
21 | "source": [
22 | "# Connect to Milvus"
23 | ]
24 | },
25 | {
26 | "cell_type": "code",
27 | "execution_count": 1,
28 | "metadata": {
29 | "dotnet_interactive": {
30 | "language": "csharp"
31 | },
32 | "polyglot_notebook": {
33 | "kernelName": "csharp"
34 | },
35 | "vscode": {
36 | "languageId": "polyglot-notebook"
37 | }
38 | },
39 | "outputs": [
40 | {
41 | "data": {
42 | "text/html": [
43 | "Installed Packages- Milvus.Client, 2.2.2-preview.2
"
44 | ]
45 | },
46 | "metadata": {},
47 | "output_type": "display_data"
48 | },
49 | {
50 | "data": {
51 | "text/html": [
52 | "{MilvusClient:localhost:19530}
"
84 | ]
85 | },
86 | "metadata": {},
87 | "output_type": "display_data"
88 | }
89 | ],
90 | "source": [
91 | "#r \"nuget: Milvus.Client, 2.2.2-preview.2\"\n",
92 | "#!import config/Settings.cs\n",
93 | "\n",
94 | "using Milvus.Client;\n",
95 | "using InteractiveKernel = Microsoft.DotNet.Interactive.Kernel;\n",
96 | "\n",
97 | "//Connect to milvus\n",
98 | "(string endpoint, int port, string userName, string password) = Settings.LoadFromFile();\n",
99 | "\n",
100 | "MilvusClient milvusClient = default;\n",
101 | "\n",
102 | "milvusClient = new MilvusClient(endpoint, port, userName, password, null);\n",
103 | "milvusClient"
104 | ]
105 | },
106 | {
107 | "attachments": {},
108 | "cell_type": "markdown",
109 | "metadata": {},
110 | "source": [
111 | "> The following example builds a 1024-cluster IVF_FLAT index with Euclidean distance (L2) as the similarity metric. You can choose the index and metrics that suit your scenario. See Similarity Metrics for more information."
112 | ]
113 | },
114 | {
115 | "cell_type": "code",
116 | "execution_count": 2,
117 | "metadata": {
118 | "dotnet_interactive": {
119 | "language": "csharp"
120 | },
121 | "polyglot_notebook": {
122 | "kernelName": "csharp"
123 | },
124 | "vscode": {
125 | "languageId": "polyglot-notebook"
126 | }
127 | },
128 | "outputs": [],
129 | "source": [
130 | "\n",
131 | "string collectionName = \"book\";\n",
132 | "MilvusCollection collection = milvusClient.GetCollection(collectionName);\n",
133 | "await collection.CreateIndexAsync(\n",
134 | " \"book_intro\",\n",
135 | " //MilvusIndexType.IVF_FLAT,//Use MilvusIndexType.IVF_FLAT.\n",
136 | " IndexType.AutoIndex,//Use MilvusIndexType.AUTOINDEX when you are using zilliz cloud.\n",
137 | " SimilarityMetricType.L2);"
138 | ]
139 | },
140 | {
141 | "attachments": {},
142 | "cell_type": "markdown",
143 | "metadata": {},
144 | "source": [
145 | "# Index info\n",
146 | "\n",
147 | "Now we had build"
148 | ]
149 | },
150 | {
151 | "cell_type": "code",
152 | "execution_count": 3,
153 | "metadata": {
154 | "dotnet_interactive": {
155 | "language": "csharp"
156 | },
157 | "polyglot_notebook": {
158 | "kernelName": "csharp"
159 | },
160 | "vscode": {
161 | "languageId": "polyglot-notebook"
162 | }
163 | },
164 | "outputs": [
165 | {
166 | "name": "stdout",
167 | "output_type": "stream",
168 | "text": [
169 | "FieldName:book_intro, IndexName:_default_idx_103, IndexId:443732094176145003\r\n"
170 | ]
171 | }
172 | ],
173 | "source": [
174 | "// Check index status\n",
175 | "IList indexInfos = await collection.DescribeIndexAsync(\"book_intro\");\n",
176 | "\n",
177 | "foreach(var info in indexInfos){\n",
178 | " Console.WriteLine(\"FieldName:{0}, IndexName:{1}, IndexId:{2}\", info.FieldName , info.IndexName,info.IndexId);\n",
179 | "}"
180 | ]
181 | }
182 | ],
183 | "metadata": {
184 | "language_info": {
185 | "name": "python"
186 | },
187 | "orig_nbformat": 4
188 | },
189 | "nbformat": 4,
190 | "nbformat_minor": 2
191 | }
192 |
--------------------------------------------------------------------------------
/docs/notebooks/config/.gitignore:
--------------------------------------------------------------------------------
1 | settings.json
2 | bin
3 | obj
4 | .ipy*
5 | *.csproj
6 | *.ini
7 | *.cache
8 | *.log
9 | *.tmp
10 |
--------------------------------------------------------------------------------
/docs/notebooks/config/Settings.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Text.Json;
5 | using System.Threading.Tasks;
6 | using Microsoft.DotNet.Interactive;
7 | using InteractiveKernel = Microsoft.DotNet.Interactive.Kernel;
8 |
9 | public static class Settings
10 | {
11 | private const string DefaultConfigFile = "config/settings.json";
12 | private const string Endpoint = "endpoint";
13 | private const string Port = "port";
14 | private const string Username = "username";
15 | private const string Password = "password";
16 |
17 | // Prompt user for milvus Endpoint URL
18 | public static async Task AskEndpoint(string configFile = DefaultConfigFile)
19 | {
20 | var (endpoint, port, userName, password) = ReadSettings(configFile);
21 |
22 | // If needed prompt user for Azure endpoint
23 | if (string.IsNullOrWhiteSpace(endpoint))
24 | {
25 | endpoint = await InteractiveKernel.GetInputAsync("Please enter your milvus endpoint");
26 | }
27 |
28 | WriteSettings(configFile,endpoint, port, userName, password);
29 |
30 | return endpoint;
31 | }
32 |
33 | public static async Task AskPort(string configFile = DefaultConfigFile)
34 | {
35 | var (endpoint, port, userName, password) = ReadSettings(configFile);
36 |
37 | if (port == 0)
38 | {
39 | port = int.Parse(await InteractiveKernel.GetInputAsync("Please enter your milvus port"));
40 | }
41 |
42 | WriteSettings(configFile,endpoint, port, userName, password);
43 |
44 | return port;
45 | }
46 |
47 | // Prompt user for milvus username
48 | public static async Task AskUsername(string configFile = DefaultConfigFile)
49 | {
50 | var (endpoint, port, userName, password) = ReadSettings(configFile);
51 |
52 | if (string.IsNullOrWhiteSpace(userName))
53 | {
54 | userName = await InteractiveKernel.GetInputAsync("Please enter your milvus username");
55 | }
56 |
57 | WriteSettings(configFile,endpoint, port, userName, password);
58 |
59 | return userName;
60 | }
61 |
62 | // Prompt user for password
63 | public static async Task AskPassword(string configFile = DefaultConfigFile)
64 | {
65 | var (endpoint, port, userName, password) = ReadSettings(configFile);
66 |
67 | if (string.IsNullOrWhiteSpace(password))
68 | {
69 | password = await InteractiveKernel.GetInputAsync("Please enter your milvus username");
70 | }
71 |
72 | WriteSettings(configFile,endpoint, port, userName, password);
73 |
74 | return userName;
75 | }
76 |
77 | // Load settings from file
78 | public static (string endpoint, int port, string username, string password)
79 | LoadFromFile(string configFile = DefaultConfigFile)
80 | {
81 | if (!File.Exists(DefaultConfigFile))
82 | {
83 | Console.WriteLine("Configuration not found: " + DefaultConfigFile);
84 | Console.WriteLine("\nPlease run the Setup Notebook (0-AI-settings.ipynb) to configure your milvus backend first.\n");
85 | throw new Exception("Configuration not found, please setup the notebooks first using 00.Settings.ipynb");
86 | }
87 |
88 | try
89 | {
90 | var config = JsonSerializer.Deserialize>(File.ReadAllText(DefaultConfigFile));
91 | string endpoint = config[Endpoint];
92 | int port = int.Parse(config[Port]);
93 | string username = config[Username];
94 | string password = config[Password];
95 |
96 | return (endpoint, port, username, password);
97 | }
98 | catch (Exception e)
99 | {
100 | Console.WriteLine("Something went wrong: " + e.Message);
101 | return ("", 0, "", "");
102 | }
103 | }
104 |
105 | // Delete settings file
106 | public static void Reset(string configFile = DefaultConfigFile)
107 | {
108 | if (!File.Exists(configFile)) { return; }
109 |
110 | try
111 | {
112 | File.Delete(configFile);
113 | Console.WriteLine("Settings deleted. Run the notebook again to configure your AI backend.");
114 | }
115 | catch (Exception e)
116 | {
117 | Console.WriteLine("Something went wrong: " + e.Message);
118 | }
119 | }
120 |
121 | // Read and return settings from file
122 | private static (string endpoint, int port, string username, string password)
123 | ReadSettings(string configFile)
124 | {
125 | // Save the preference set in the notebook
126 | string endpoint = "";
127 | int port = 0;
128 | string username = "";
129 | string password = "";
130 |
131 | try
132 | {
133 | if (File.Exists(configFile))
134 | {
135 | (endpoint, port, username, password) = LoadFromFile(configFile);
136 | }
137 | }
138 | catch (Exception e)
139 | {
140 | Console.WriteLine("Something went wrong: " + e.Message);
141 | }
142 |
143 | return (endpoint, port, username, password);
144 | }
145 |
146 | // Write settings to file
147 | private static void WriteSettings(
148 | string configFile, string endpoint, int port, string username, string password)
149 | {
150 | try
151 | {
152 | var data = new Dictionary
153 | {
154 | { Endpoint, endpoint },
155 | { Port, port.ToString() },
156 | { Username, username },
157 | { Password,password }
158 | };
159 |
160 | var options = new JsonSerializerOptions { WriteIndented = true };
161 | File.WriteAllText(configFile, JsonSerializer.Serialize(data, options));
162 |
163 | }
164 | catch (Exception e)
165 | {
166 | Console.WriteLine("Something went wrong: " + e.Message);
167 | }
168 | }
169 | }
170 |
--------------------------------------------------------------------------------
/docs/notebooks/config/settings.example.zilliz.json:
--------------------------------------------------------------------------------
1 | {
2 | "endpoint": "https://{id}.{machinename}.vectordb.zillizcloud.com",
3 | "port": "19536",
4 | "username": "db_admin",
5 | "password": "{password}"
6 | }
--------------------------------------------------------------------------------
/docs/notebooks/resources/zilliz.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/docs/readme.md:
--------------------------------------------------------------------------------
1 | # milvus-sdk-c#
2 |
3 | [Github Repository](https://github.com/milvus-io/milvus-sdk-csharp)
4 |
5 | [Milvus docs](https://milvus.io/docs)
6 |
7 | ## Overview
8 |
9 | This is the C# SDK for Milvus.
10 | It is implemented using the gRPC protocol and provides most of the features of the Milvus server.
11 | And restful api support is ready now.
12 |
13 | ### Create a client.
14 |
15 | > Grpc
16 |
17 | ```csharp
18 | using Milvus.Client;
19 |
20 | string Host = "localhost";
21 | int Port = 19530; // This is Milvus's default port
22 | bool UseSsl = false; // Default value is false
23 | string Database = "my_database"; // Defaults to the default Milvus database
24 |
25 | // See documentation for other constructor paramters
26 | MilvusClient milvusClient = new MilvusClient(Host, Port, UseSsl);
27 | MilvusHealthState result = await milvusClient.HealthAsync();
28 | ```
29 |
30 | ### Create a collection.
31 |
32 | ```csharp
33 | string collectionName = "book";
34 | MilvusCollection collection = milvusClient.GetCollection(collectionName);
35 |
36 | //Check if this collection exists
37 | var hasCollection = await milvusClient.HasCollectionAsync(collectionName);
38 |
39 | if(hasCollection){
40 | await collection.DropAsync();
41 | Console.WriteLine("Drop collection {0}",collectionName);
42 | }
43 |
44 | await milvusClient.CreateCollectionAsync(
45 | collectionName,
46 | new[] {
47 | FieldSchema.Create("book_id", isPrimaryKey:true),
48 | FieldSchema.Create("word_count"),
49 | FieldSchema.CreateVarchar("book_name", 256),
50 | FieldSchema.CreateFloatVector("book_intro", 2)
51 | }
52 | );
53 | ```
54 |
55 | ### Insert vectors.
56 |
57 | ```csharp
58 | Random ran = new ();
59 | List bookIds = new ();
60 | List wordCounts = new ();
61 | List> bookIntros = new ();
62 | List bookNames = new ();
63 | for (long i = 0L; i < 2000; ++i)
64 | {
65 | bookIds.Add(i);
66 | wordCounts.Add(i + 10000);
67 | bookNames.Add($"Book Name {i}");
68 |
69 | float[] vector = new float[2];
70 | for (int k = 0; k < 2; ++k)
71 | {
72 | vector[k] = ran.Next();
73 | }
74 | bookIntros.Add(vector);
75 | }
76 |
77 | MilvusCollection collection = milvusClient.GetCollection(collectionName);
78 |
79 | MutationResult result = await collection.InsertAsync(
80 | new FieldData[]
81 | {
82 | FieldData.Create("book_id", bookIds),
83 | FieldData.Create("word_count", wordCounts),
84 | FieldData.Create("book_name", bookNames),
85 | FieldData.CreateFloatVector("book_intro", bookIntros),
86 | });
87 |
88 | // Check result
89 | Console.WriteLine("Insert status: {0},", result.ToString());
90 | ```
91 |
92 | ### Create a index and load collection.
93 |
94 | ```csharp
95 | MilvusCollection collection = milvusClient.GetCollection(collectionName);
96 | await collection.CreateIndexAsync(
97 | "book_intro",
98 | //MilvusIndexType.IVF_FLAT,//Use MilvusIndexType.IVF_FLAT.
99 | IndexType.AutoIndex,//Use MilvusIndexType.AUTOINDEX when you are using zilliz cloud.
100 | SimilarityMetricType.L2);
101 |
102 | // Check index status
103 | IList indexInfos = await collection.DescribeIndexAsync("book_intro");
104 |
105 | foreach(var info in indexInfos){
106 | Console.WriteLine("FieldName:{0}, IndexName:{1}, IndexId:{2}", info.FieldName , info.IndexName,info.IndexId);
107 | }
108 |
109 | // Then load it
110 | await collection.LoadAsync();
111 | ```
112 |
113 | ### Search and query.
114 |
115 | ```csharp
116 | // Search
117 | List search_output_fields = new() { "book_id" };
118 | List> search_vectors = new() { new() { 0.1f, 0.2f } };
119 | SearchResults searchResult = await collection.SearchAsync(
120 | "book_intro",
121 | new ReadOnlyMemory[] { new[] { 0.1f, 0.2f } },
122 | SimilarityMetricType.L2,
123 | limit: 2);
124 |
125 | // Query
126 | string expr = "book_id in [2,4,6,8]";
127 |
128 | QueryParameters queryParameters = new ();
129 | queryParameters.OutputFields.Add("book_id");
130 | queryParameters.OutputFields.Add("word_count");
131 |
132 | IReadOnlyList queryResult = await collection.QueryAsync(
133 | expr,
134 | queryParameters);
135 | ```
136 |
--------------------------------------------------------------------------------
/docs/user_guide/manage_collections.md:
--------------------------------------------------------------------------------
1 | # Manage Collections
2 |
3 | ## Create a Collection
4 |
5 | ### Prepare schema
6 |
7 | ```c#
8 | var schema = new CollectionSchema
9 | {
10 | Fields =
11 | {
12 | FieldSchema.Create("book_id", isPrimaryKey: true),
13 | FieldSchema.CreateVarchar("book_name", maxLength: 200),
14 | FieldSchema.Create("word_count"),
15 | FieldSchema.CreateFloatVector("book_intro", dimension: 2)
16 | },
17 | Description = "Test book search",
18 | EnableDynamicFields = true
19 | };
20 | ```
21 |
22 | ### Create a collection with the schema
23 |
24 | ```c#
25 | var collection = await milvusClient.CreateCollectionAsync(collectionName, schema, shardsNum: 2);
26 | ```
27 |
28 | ## Rename a Collection
29 |
30 | ```c#
31 | var collection = milvusClient.GetCollection("old_collection").RenameAsync("new_collection");
32 | ```
33 |
34 | ## Check Collection Information
35 |
36 | ### Check if a collection exists
37 |
38 | ```c#
39 | var collectionExists = await Client.HasCollectionAsync("book");
40 | ```
41 |
42 | ### Check collection details
43 |
44 | ```c#
45 | var collection = milvusClient.GetCollection("book").DescribeAsync();
46 | ```
47 |
48 | ### List all collections
49 |
50 | ```c#
51 | var collections = await milvusClient.ListCollectionsAsync();
52 | ```
53 |
54 | ## Drop a Collection
55 |
56 | ```c#
57 | var collection = Client.GetCollection("book").DropAsync();
58 | ```
59 |
60 | ## Manage Collection Alias
61 |
62 | ### Create a collection alias
63 |
64 | ```c#
65 | await milvusClient.CreateAliasAsync("book", "publication");
66 | ```
67 |
68 | ### Drop a collection alias
69 |
70 | ```c#
71 | await milvusClient.DropAliasAsync("publication");
72 | ```
73 |
74 | ### Alter a collection alias
75 |
76 | ```c#
77 | await milvusClient.AlterAliasAsync("book", "publication");
78 | ```
79 |
80 | ## Load Collection
81 |
82 | ```c#
83 | var collection = Client.GetCollection("book").LoadAsync();
84 | ```
85 |
86 | ## Release Collection
87 |
88 | ```c#
89 | var collection = Client.GetCollection("book").ReleaseAsync();
90 | ```
91 |
--------------------------------------------------------------------------------
/docs/user_guide/manage_data.md:
--------------------------------------------------------------------------------
1 | # Manage Data
2 |
3 | ## Insert Entities
4 |
5 | ### Prepare data
6 |
7 | ```c#
8 | var bookIds = new long[2000];
9 | var wordCounts = new long[2000];
10 | var bookIntros = new ReadOnlyMemory[2000];
11 |
12 | for (var i = 0; i < 2000; i++)
13 | {
14 | bookIds[i] = i;
15 | wordCounts[i] = i + 10000;
16 | bookIntros[i] = new[] { Random.Shared.NextSingle(), Random.Shared.NextSingle() };
17 | }
18 | ```
19 |
20 | ### Insert data to Milvus
21 |
22 | ```c#
23 | await milvusClient.GetCollection("book").InsertAsync(new FieldData[]
24 | {
25 | FieldData.Create("book_id", bookIds),
26 | FieldData.Create("word_count", wordCounts),
27 | FieldData.CreateFloatVector("book_intro", bookIntros)
28 | });
29 | ```
30 |
31 | ## Delete Entities
32 |
33 | ### Prepare boolean expression
34 |
35 | ```c#
36 | var expression = "book_id in [0,1]";
37 | ```
38 |
39 | ### Delete entities
40 |
41 | ```c#
42 | await milvusClient.GetCollection("book").DeleteAsync(expression);
43 | ```
44 |
45 | ## Compact Data
46 |
47 | ### Compact data manually
48 |
49 | ```c#
50 | await milvusClient.GetCollection("book").CompactAsync();
51 | ```
52 |
--------------------------------------------------------------------------------
/docs/user_guide/manage_databases.md:
--------------------------------------------------------------------------------
1 | # Manage Databases
2 |
3 | # Create database
4 |
5 | ```c#
6 | await milvusClient.CreateDatabaseAsync("book");
7 | ```
8 |
9 | # Use a database
10 |
11 | ```c#
12 | var milvusClient = new MilvusClient("localhost", database: "book");
13 | ```
14 |
15 | # List database
16 |
17 | ```c#
18 | var databases = await milvusClient.ListDatabasesAsync();
19 | ```
20 |
21 | # Drop database
22 |
23 | ```c#
24 | await milvusClient.DropDatabaseAsync("book");
25 | ```
26 |
--------------------------------------------------------------------------------
/docs/user_guide/manage_indexes.md:
--------------------------------------------------------------------------------
1 | # Manage Indexes
2 |
3 | ## Build an Index on Vectors
4 |
5 | ### Prepare index parameter
6 |
7 | ```c#
8 | var indexType = IndexType.IvfFlat;
9 | var metricType = SimilarityMetricType.L2;
10 | var extraParams = new Dictionary { ["nlist"] = "1024" };
11 | ```
12 |
13 | ### Build index
14 |
15 | ```c#
16 | await milvusClient.GetCollection("book").CreateIndexAsync("book_intro", indexType, metricType, extraParams: extraParams);
17 | ```
18 |
19 | ## Build an Index on Scalars
20 |
21 | ```c#
22 | var collection = milvusClient.GetCollection("book");
23 | await collection.CreateIndexAsync("book_name", indexName: "scalar_index");
24 | await collection.LoadAsync();
25 | ```
26 |
27 | ## Drop an Index
28 |
29 | ```c#
30 | await milvusClient.GetCollection("book").DropIndexAsync("book_intro");
31 | ```
--------------------------------------------------------------------------------
/docs/user_guide/manage_milvus_connections.md:
--------------------------------------------------------------------------------
1 | # Manage Milvus Connections
2 |
3 | ## Connect to a Milvus server
4 |
5 | ```c#
6 | var milvusClient = new MilvusClient("localhost", username: "username", password: "password");
7 | ```
8 |
9 | ## Disconnect from a Milvus server
10 |
11 | ```c#
12 | milvusClient.Dispose();
13 | ```
--------------------------------------------------------------------------------
/docs/user_guide/manage_partitions.md:
--------------------------------------------------------------------------------
1 | # Manage Partitions
2 |
3 | ## Create a Partition
4 |
5 | ```c#
6 | var collection = milvusClient.GetCollection("book").CreatePartitionAsync("novel");
7 | ```
8 |
9 | ## Check Partition Information
10 |
11 | ### Verify if a partition exists
12 |
13 | ```c#
14 | var exists = await milvusClient.GetCollection("book").HasPartitionAsync("novel");
15 | ```
16 |
17 | ### List all partitions
18 |
19 | ```c#
20 | var partitions = await milvusClient.GetCollection("book").ShowPartitionsAsync();
21 | ```
22 |
23 | ## Drop Partitions
24 |
25 | ```c#
26 | await milvusClient.GetCollection("book").DropPartitionsAsync("novel");
27 | ```
28 |
29 | ## Load a Partition
30 |
31 | ```c#
32 | await milvusClient.GetCollection("book").LoadPartitionAsync("novel");
33 | ```
34 |
35 | ## Release a Partition
36 |
37 | ```c#
38 | await milvusClient.GetCollection("book").ReleasePartitionAsync("novel");
39 | ```
40 |
--------------------------------------------------------------------------------
/docs/user_guide/search_and_query.md:
--------------------------------------------------------------------------------
1 | # Search and Query
2 |
3 | ## Search
4 |
5 | ### Load collection
6 |
7 | ```c#
8 | var collection = milvusClient.GetCollection("book").LoadAsync();
9 | ```
10 |
11 | ### Prepare search parameters
12 |
13 | ```c#
14 | var parameters = new SearchParameters
15 | {
16 | OutputFields = { "title" },
17 | ConsistencyLevel = ConsistencyLevel.Strong,
18 | Offset = 5,
19 | ExtraParameters = { ["nprobe"] = "1024" }
20 | };
21 | ```
22 |
23 | ### Conduct a vector search
24 |
25 | ```c#
26 | var results = await milvusClient.GetCollection("book").SearchAsync(
27 | vectorFieldName: "book_intro",
28 | vectors: new ReadOnlyMemory[] { new[] { 0.1f, 0.2f } },
29 | SimilarityMetricType.L2,
30 | // the sum of `offset` in `parameters` and `limit` should be less than 16384.
31 | limit: 10,
32 | parameters);
33 | ```
34 |
35 | ```c#
36 | var collection = milvusClient.GetCollection("book").ReleaseAsync();
37 | ```
38 |
39 | ## Hybrid Search
40 |
41 | ### Load collection
42 |
43 | ```c#
44 | var collection = milvusClient.GetCollection("book").LoadAsync();
45 | ```
46 |
47 | ### Conduct a hybrid vector search
48 |
49 | ```c#
50 | var results = await milvusClient.GetCollection("book").SearchAsync(
51 | vectorFieldName: "book_intro",
52 | vectors: new ReadOnlyMemory[] { new[] { 0.1f, 0.2f } },
53 | SimilarityMetricType.L2,
54 | limit: 10,
55 | new SearchParameters
56 | {
57 | OutputFields = { "title" },
58 | ConsistencyLevel = ConsistencyLevel.Strong,
59 | Offset = 5,
60 | Expression = "word_count <= 11000",
61 | ExtraParameters = { ["nprobe"] = "1024" }
62 | });
63 | ```
64 |
65 | ## Query
66 |
67 | ### Load collection
68 |
69 | ```c#
70 | var collection = milvusClient.GetCollection("book").LoadAsync();
71 | ```
72 |
73 | ### Conduct a vector query
74 |
75 | ```c#
76 | var results = await Client.GetCollection("book").QueryAsync(
77 | expression: "book_id in [2,4,6,8]",
78 | new QueryParameters
79 | {
80 | Offset = 0,
81 | Limit = 10,
82 | OutputFields = { "book_id", "book_intro" }
83 | });
84 | ```
85 |
--------------------------------------------------------------------------------
/global.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdk": {
3 | "version": "8.0.201",
4 | "rollForward": "latestMajor"
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/milvussharp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/milvus-io/milvus-sdk-csharp/92877febde03406fe99495c45b5cb582b9cd553d/milvussharp.png
--------------------------------------------------------------------------------
/nuget.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/resources/workbench.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/milvus-io/milvus-sdk-csharp/92877febde03406fe99495c45b5cb582b9cd553d/resources/workbench.png
--------------------------------------------------------------------------------