BotSharp/src/Plugins/BotSharp.Plugin.Qdrant/QdrantDb.cs

872 lines
28 KiB
C#
Raw Normal View History

2025-03-12 21:33:20 +00:00
using BotSharp.Abstraction.Options;
2024-08-06 22:43:11 +00:00
using BotSharp.Abstraction.Utilities;
2025-03-12 21:33:20 +00:00
using BotSharp.Plugin.Qdrant.Models;
2025-08-15 14:50:09 +00:00
using Google.Protobuf.Collections;
2025-03-12 21:33:20 +00:00
using Microsoft.Extensions.DependencyInjection;
2024-09-10 19:02:25 +00:00
using Microsoft.Extensions.Logging;
2023-11-14 01:25:25 +00:00
using Qdrant.Client;
using Qdrant.Client.Grpc;
2025-08-05 20:46:07 +00:00
using System.Collections;
2025-03-12 21:33:20 +00:00
using System.Net.Http;
using System.Net.Mime;
using System.Text.Json;
2023-06-18 02:56:22 +00:00
namespace BotSharp.Plugin.Qdrant;
public class QdrantDb : IVectorDb
{
2024-01-06 03:24:13 +00:00
private QdrantClient _client;
2023-06-18 02:56:22 +00:00
private readonly QdrantSetting _setting;
2025-03-12 21:33:20 +00:00
private readonly BotSharpOptions _options;
2023-06-27 23:36:50 +00:00
private readonly IServiceProvider _services;
2024-09-10 19:02:25 +00:00
private readonly ILogger<QdrantDb> _logger;
2023-06-27 23:36:50 +00:00
public QdrantDb(
QdrantSetting setting,
2025-03-12 21:33:20 +00:00
BotSharpOptions options,
2024-09-10 19:02:25 +00:00
ILogger<QdrantDb> logger,
2023-06-27 23:36:50 +00:00
IServiceProvider services)
2023-06-18 02:56:22 +00:00
{
_setting = setting;
2025-03-12 21:33:20 +00:00
_options = options;
2024-09-10 19:02:25 +00:00
_logger = logger;
2023-06-27 23:36:50 +00:00
_services = services;
2024-01-06 03:24:13 +00:00
}
2024-08-31 00:31:18 +00:00
public string Provider => "Qdrant";
2024-01-06 03:24:13 +00:00
private QdrantClient GetClient()
{
if (_client == null)
{
_client = new QdrantClient
(
host: _setting.Url,
2024-07-02 14:52:16 +00:00
https: true,
2024-01-06 03:24:13 +00:00
apiKey: _setting.ApiKey
);
}
return _client;
2023-06-18 02:56:22 +00:00
}
2025-03-12 21:33:20 +00:00
#region Collection
2024-09-24 20:34:47 +00:00
public async Task<bool> DoesCollectionExist(string collectionName)
2024-08-29 19:30:47 +00:00
{
var client = GetClient();
2024-09-24 20:34:47 +00:00
return await client.CollectionExistsAsync(collectionName);
}
2025-08-15 03:33:22 +00:00
public async Task<bool> CreateCollection(string collectionName, VectorCollectionCreateOptions options)
2024-09-24 20:34:47 +00:00
{
var exist = await DoesCollectionExist(collectionName);
2024-08-29 19:30:47 +00:00
if (exist) return false;
2024-09-10 19:02:25 +00:00
try
2024-08-29 19:30:47 +00:00
{
2024-09-10 19:02:25 +00:00
// Create a new collection
2024-09-24 20:34:47 +00:00
var client = GetClient();
2024-09-10 19:02:25 +00:00
await client.CreateCollectionAsync(collectionName, new VectorParams()
{
2025-08-15 03:33:22 +00:00
Size = (ulong)options.Dimension,
2024-09-10 19:02:25 +00:00
Distance = Distance.Cosine
});
return true;
}
catch (Exception ex)
{
2025-08-15 03:33:22 +00:00
_logger.LogWarning($"Error when create collection (Name: {collectionName}, Dimension: {options.Dimension}).");
2024-09-10 19:02:25 +00:00
return false;
}
2024-08-29 19:30:47 +00:00
}
public async Task<bool> DeleteCollection(string collectionName)
{
2024-09-24 20:34:47 +00:00
var exist = await DoesCollectionExist(collectionName);
2024-08-29 19:30:47 +00:00
if (!exist) return false;
2024-09-24 20:34:47 +00:00
var client = GetClient();
2024-08-29 19:30:47 +00:00
await client.DeleteCollectionAsync(collectionName);
return true;
}
2024-08-08 22:15:51 +00:00
public async Task<IEnumerable<string>> GetCollections()
2023-06-18 02:56:22 +00:00
{
// List all the collections
2024-07-02 14:52:16 +00:00
var collections = await GetClient().ListCollectionsAsync();
2023-11-14 01:25:25 +00:00
return collections.ToList();
2023-06-18 02:56:22 +00:00
}
2025-04-30 16:55:25 +00:00
public async Task<VectorCollectionDetails?> GetCollectionDetails(string collectionName)
{
var exist = await DoesCollectionExist(collectionName);
if (!exist) return null;
var client = GetClient();
var details = await client.GetCollectionInfoAsync(collectionName);
if (details == null) return null;
2025-08-14 22:51:09 +00:00
var payloadSchema = details.PayloadSchema?.Select(x => new PayloadSchemaDetail
{
FieldName = x.Key,
FieldDataType = x.Value.DataType.ToString().ToLowerInvariant(),
DataCount = x.Value.Points
})?.ToList() ?? [];
2025-04-30 16:55:25 +00:00
return new VectorCollectionDetails
{
Status = details.Status.ToString(),
OptimizerStatus = details.OptimizerStatus.ToString(),
SegmentsCount = details.SegmentsCount,
InnerConfig = new VectorCollectionDetailConfig
{
Param = new VectorCollectionDetailConfigParam
{
ShardNumber = details.Config?.Params?.ShardNumber,
ShardingMethod = details.Config?.Params?.ShardingMethod.ToString(),
ReplicationFactor = details.Config?.Params?.ReplicationFactor,
WriteConsistencyFactor = details.Config?.Params?.WriteConsistencyFactor,
ReadFanOutFactor = details.Config?.Params?.ReadFanOutFactor
}
},
VectorsCount = details.VectorsCount,
IndexedVectorsCount = details.IndexedVectorsCount,
2025-08-14 22:51:09 +00:00
PointsCount = details.PointsCount,
PayloadSchema = payloadSchema
2025-04-30 16:55:25 +00:00
};
}
2025-03-12 21:33:20 +00:00
#endregion
2023-06-18 02:56:22 +00:00
2025-03-12 21:33:20 +00:00
#region Collection data
2024-08-23 16:25:44 +00:00
public async Task<StringIdPagedItems<VectorCollectionData>> GetPagedCollectionData(string collectionName, VectorFilter filter)
2024-08-06 22:43:11 +00:00
{
2024-09-24 20:34:47 +00:00
var exist = await DoesCollectionExist(collectionName);
if (!exist)
2024-08-06 22:43:11 +00:00
{
2024-08-15 23:19:10 +00:00
return new StringIdPagedItems<VectorCollectionData>();
2024-08-06 22:43:11 +00:00
}
2025-08-08 20:27:38 +00:00
Filter? queryFilter = BuildQueryFilter(filter.FilterGroups);
2025-08-06 21:36:36 +00:00
WithPayloadSelector? payloadSelector = BuildPayloadSelector(filter.Fields);
2025-08-12 02:51:33 +00:00
OrderBy? orderBy = BuildOrderBy(filter.OrderBy);
2024-09-12 22:48:47 +00:00
2024-09-24 20:34:47 +00:00
var client = GetClient();
2025-08-06 21:36:36 +00:00
var totalCountTask = client.CountAsync(collectionName, filter: queryFilter);
var dataResponseTask = client.ScrollAsync(
collectionName,
limit: (uint)filter.Size,
2024-08-28 22:45:33 +00:00
offset: !string.IsNullOrWhiteSpace(filter.StartId) ? new PointId { Uuid = filter.StartId } : null,
filter: queryFilter,
2025-08-12 02:51:33 +00:00
orderBy: orderBy,
2024-09-12 22:48:47 +00:00
payloadSelector: payloadSelector,
2024-08-06 22:43:11 +00:00
vectorsSelector: filter.WithVector);
2024-08-28 22:45:33 +00:00
2025-08-06 21:36:36 +00:00
await Task.WhenAll([totalCountTask, dataResponseTask]);
var totalPointCount = totalCountTask.Result;
var response = dataResponseTask.Result;
2024-08-15 23:19:10 +00:00
var points = response?.Result?.Select(x => new VectorCollectionData
2024-08-06 22:43:11 +00:00
{
Id = x.Id?.Uuid ?? string.Empty,
2025-08-15 14:50:09 +00:00
Data = MapPayload(x.Payload),
2024-08-06 22:43:11 +00:00
Vector = filter.WithVector ? x.Vectors?.Vector?.Data?.ToArray() : null
2024-08-15 23:19:10 +00:00
})?.ToList() ?? new List<VectorCollectionData>();
2024-08-06 22:43:11 +00:00
2024-08-15 23:19:10 +00:00
return new StringIdPagedItems<VectorCollectionData>
2024-08-06 22:43:11 +00:00
{
Count = totalPointCount,
NextId = response?.NextPageOffset?.Uuid,
Items = points
};
}
2024-08-23 16:25:44 +00:00
2025-08-06 22:40:47 +00:00
public async Task<IEnumerable<VectorCollectionData>> GetCollectionData(string collectionName, IEnumerable<Guid> ids, VectorQueryOptions? options = null)
2024-08-23 16:25:44 +00:00
{
2024-09-24 20:34:47 +00:00
if (ids.IsNullOrEmpty())
{
return Enumerable.Empty<VectorCollectionData>();
}
var exist = await DoesCollectionExist(collectionName);
2024-08-23 16:25:44 +00:00
if (!exist)
{
return Enumerable.Empty<VectorCollectionData>();
}
2024-09-24 20:34:47 +00:00
var client = GetClient();
2024-08-23 16:25:44 +00:00
var pointIds = ids.Select(x => new PointId { Uuid = x.ToString() }).Distinct().ToList();
2025-08-06 22:40:47 +00:00
var points = await client.RetrieveAsync(collectionName, pointIds, options?.WithPayload ?? false, options?.WithVector ?? false);
2024-08-23 16:25:44 +00:00
return points.Select(x => new VectorCollectionData
{
Id = x.Id?.Uuid ?? string.Empty,
2025-08-15 14:50:09 +00:00
Data = MapPayload(x.Payload),
2024-08-23 16:25:44 +00:00
Vector = x.Vectors?.Vector?.Data?.ToArray()
});
}
2025-08-15 04:40:15 +00:00
public async Task<bool> Upsert(string collectionName, Guid id, float[] vector, string text, Dictionary<string, VectorPayloadValue>? payload = null)
2023-06-18 02:56:22 +00:00
{
// Insert vectors
2024-07-02 14:52:16 +00:00
var point = new PointStruct()
2023-06-18 02:56:22 +00:00
{
2024-07-02 14:52:16 +00:00
Id = new PointId()
2023-11-14 01:25:25 +00:00
{
Uuid = id.ToString()
2024-07-02 14:52:16 +00:00
},
Vectors = vector,
2024-08-06 22:43:11 +00:00
Payload =
2024-07-17 21:03:46 +00:00
{
2024-08-06 19:01:26 +00:00
{ KnowledgePayloadName.Text, text }
2024-07-17 21:03:46 +00:00
}
2024-07-02 14:52:16 +00:00
};
2023-06-27 23:36:50 +00:00
2024-07-17 21:03:46 +00:00
if (payload != null)
2024-07-02 14:52:16 +00:00
{
2024-07-17 21:03:46 +00:00
foreach (var item in payload)
{
2025-08-15 15:01:01 +00:00
var value = item.Value.DataValue?.ToString();
2025-08-08 20:27:38 +00:00
if (value == null || item.Key.IsEqualTo(KnowledgePayloadName.Text))
{
continue;
}
2024-10-07 18:10:48 +00:00
2025-08-15 14:50:09 +00:00
switch (item.Value.DataType)
2024-10-07 18:10:48 +00:00
{
2025-08-15 14:50:09 +00:00
case VectorPayloadDataType.Boolean when bool.TryParse(value, out var boolVal):
point.Payload[item.Key] = boolVal;
break;
case VectorPayloadDataType.Integer when long.TryParse(value, out var longVal):
point.Payload[item.Key] = longVal;
break;
case VectorPayloadDataType.Double when double.TryParse(value, out var doubleVal):
point.Payload[item.Key] = doubleVal;
break;
case VectorPayloadDataType.Datetime when DateTime.TryParse(value, out var dt):
point.Payload[item.Key] = dt.ToUniversalTime().ToString("o");
break;
case VectorPayloadDataType.String:
point.Payload[item.Key] = value;
break;
default:
break;
2024-10-07 18:10:48 +00:00
}
2024-07-17 21:03:46 +00:00
}
2024-07-02 14:52:16 +00:00
}
2024-07-17 21:03:46 +00:00
var client = GetClient();
var result = await client.UpsertAsync(collectionName, points: new List<PointStruct>
2024-07-02 14:52:16 +00:00
{
point
});
2024-07-17 21:03:46 +00:00
return result.Status == UpdateStatus.Completed;
2023-06-18 02:56:22 +00:00
}
2025-08-05 20:46:07 +00:00
public async Task<IEnumerable<VectorCollectionData>> Search(string collectionName, float[] vector, VectorSearchOptions? options = null)
2023-06-18 02:56:22 +00:00
{
2024-08-15 23:19:10 +00:00
var results = new List<VectorCollectionData>();
2024-08-13 18:26:57 +00:00
2024-09-24 20:34:47 +00:00
var exist = await DoesCollectionExist(collectionName);
2024-08-13 18:26:57 +00:00
if (!exist)
{
return results;
}
2023-06-27 23:36:50 +00:00
2025-08-05 20:46:07 +00:00
options ??= VectorSearchOptions.Default();
2025-08-08 20:27:38 +00:00
Filter? queryFilter = BuildQueryFilter(options.FilterGroups);
2025-08-06 21:36:36 +00:00
WithPayloadSelector? payloadSelector = BuildPayloadSelector(options.Fields);
2024-09-24 20:34:47 +00:00
var client = GetClient();
var points = await client.SearchAsync(collectionName,
2024-08-28 22:45:33 +00:00
vector,
2025-08-05 20:46:07 +00:00
limit: (ulong)options.Limit.GetValueOrDefault(),
scoreThreshold: options.Confidence,
filter: queryFilter,
2024-08-28 22:45:33 +00:00
payloadSelector: payloadSelector,
2025-08-05 20:46:07 +00:00
vectorsSelector: options.WithVector);
2024-08-15 03:46:01 +00:00
2024-08-28 22:45:33 +00:00
results = points.Select(x => new VectorCollectionData
{
2024-08-28 22:45:33 +00:00
Id = x.Id.Uuid,
2025-08-15 14:50:09 +00:00
Data = MapPayload(x.Payload),
2024-08-28 22:45:33 +00:00
Score = x.Score,
Vector = x.Vectors?.Vector?.Data?.ToArray()
}).ToList();
return results;
2023-06-18 02:56:22 +00:00
}
2024-08-08 22:15:51 +00:00
2024-09-10 19:02:25 +00:00
public async Task<bool> DeleteCollectionData(string collectionName, List<Guid> ids)
2024-08-08 22:15:51 +00:00
{
2024-09-10 19:02:25 +00:00
if (ids.IsNullOrEmpty()) return false;
2024-09-24 20:34:47 +00:00
var exist = await DoesCollectionExist(collectionName);
2024-09-18 21:17:54 +00:00
if (!exist)
{
return false;
}
2024-09-24 20:34:47 +00:00
var client = GetClient();
2024-09-10 19:02:25 +00:00
var result = await client.DeleteAsync(collectionName, ids);
2024-08-08 22:15:51 +00:00
return result.Status == UpdateStatus.Completed;
}
2024-09-18 21:17:54 +00:00
public async Task<bool> DeleteCollectionAllData(string collectionName)
{
2024-09-24 20:34:47 +00:00
var exist = await DoesCollectionExist(collectionName);
2024-09-18 21:17:54 +00:00
if (!exist)
{
return false;
}
2024-09-24 20:34:47 +00:00
var client = GetClient();
2024-09-18 21:17:54 +00:00
var result = await client.DeleteAsync(collectionName, new Filter());
return result.Status == UpdateStatus.Completed;
}
2025-08-06 18:52:24 +00:00
#endregion
2025-08-05 20:46:07 +00:00
2025-08-06 18:52:24 +00:00
#region Payload index
2025-08-06 15:14:22 +00:00
public async Task<bool> CreateCollectionPayloadIndex(string collectionName, CreateVectorCollectionIndexOptions options)
{
var exist = await DoesCollectionExist(collectionName);
if (!exist)
{
return false;
}
var client = GetClient();
var schemaType = ConvertPayloadSchemaType(options.FieldSchemaType);
2025-08-12 03:32:58 +00:00
var result = await client.CreatePayloadIndexAsync(collectionName, options.FieldName, schemaType);
2025-08-06 15:14:22 +00:00
return result.Status == UpdateStatus.Completed;
}
public async Task<bool> DeleteCollectionPayloadIndex(string collectionName, DeleteVectorCollectionIndexOptions options)
{
var exist = await DoesCollectionExist(collectionName);
if (!exist)
{
return false;
}
var client = GetClient();
var result = await client.DeletePayloadIndexAsync(collectionName, options.FieldName);
return result.Status == UpdateStatus.Completed;
}
2025-03-12 21:33:20 +00:00
#endregion
#region Snapshots
public async Task<IEnumerable<VectorCollectionSnapshot>> GetCollectionSnapshots(string collectionName)
{
var exist = await DoesCollectionExist(collectionName);
if (!exist)
{
return Enumerable.Empty<VectorCollectionSnapshot>();
}
var client = GetClient();
var data = await client.ListSnapshotsAsync(collectionName);
var snapshots = data.Select(x => new VectorCollectionSnapshot
{
Name = x.Name,
Size = x.Size,
CreatedTime = x.CreationTime.ToDateTime(),
CheckSum = x.Checksum
});
return snapshots;
}
public async Task<VectorCollectionSnapshot?> CreateCollectionShapshot(string collectionName)
{
var exist = await DoesCollectionExist(collectionName);
if (!exist)
{
return null;
}
var client = GetClient();
var desc = await client.CreateSnapshotAsync(collectionName);
if (desc == null)
{
return null;
}
return new VectorCollectionSnapshot
{
Name = desc.Name,
Size = desc.Size,
CreatedTime = desc.CreationTime.ToDateTime(),
CheckSum = desc.Checksum
};
}
public async Task<BinaryData> DownloadCollectionSnapshot(string collectionName, string snapshotFileName)
{
var exist = await DoesCollectionExist(collectionName);
if (!exist)
{
return BinaryData.Empty;
}
var domain = $"https://{_setting.Url}:6333";
var url = $"{domain}/collections/{collectionName}/snapshots/{snapshotFileName}";
var http = _services.GetRequiredService<IHttpClientFactory>();
using (var client = http.CreateClient())
{
try
{
var uri = new Uri(url);
var message = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = uri
};
client.DefaultRequestHeaders.Add("api-key", _setting.ApiKey);
var rawResponse = await client.SendAsync(message);
rawResponse.EnsureSuccessStatusCode();
using var contentStream = await rawResponse.Content.ReadAsStreamAsync();
return BinaryData.FromStream(contentStream);
}
catch (Exception ex)
{
2025-05-02 16:31:28 +00:00
_logger.LogError(ex, $"Error when downloading Qdrant snapshot (Endpoint: {url}, Snapshot: {snapshotFileName}).");
2025-03-12 21:33:20 +00:00
return BinaryData.Empty;
}
}
}
public async Task<bool> RecoverCollectionFromShapshot(string collectionName, string snapshotFileName, BinaryData snapshotData)
{
var domain = $"https://{_setting.Url}:6333";
var url = $"{domain}/collections/{collectionName}/snapshots/upload";
var http = _services.GetRequiredService<IHttpClientFactory>();
using (var client = http.CreateClient())
{
try
{
var uri = new Uri(url);
var data = new MultipartFormDataContent
{
{ new StringContent(snapshotFileName), "name" },
{ new StringContent(MediaTypeNames.Application.Octet), "type" },
{ new StreamContent(snapshotData.ToStream()), "snapshot", snapshotFileName }
};
var message = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = uri,
Content = data
};
client.DefaultRequestHeaders.Add("api-key", _setting.ApiKey);
var rawResponse = await client.SendAsync(message);
rawResponse.EnsureSuccessStatusCode();
var responseStr = await rawResponse.Content.ReadAsStringAsync();
var response = JsonSerializer.Deserialize<RecoverFromSnapshotResponse>(responseStr, _options.JsonSerializerOptions);
return response?.Result == true;
}
catch (Exception ex)
{
2025-05-02 16:31:28 +00:00
_logger.LogError(ex, $"Error when uploading Qdrant snapshot (Endpoint: {url}, Snapshot: {snapshotFileName}).");
2025-03-12 21:33:20 +00:00
return false;
}
}
}
public async Task<bool> DeleteCollectionShapshot(string collectionName, string snapshotName)
{
var exist = await DoesCollectionExist(collectionName);
if (!exist)
{
return false;
}
try
{
var client = GetClient();
await client.DeleteSnapshotAsync(collectionName, snapshotName);
return true;
}
catch
{
return false;
}
}
#endregion
2025-08-06 15:14:22 +00:00
#region Private methods
2025-08-20 19:48:11 +00:00
#region Query filter
2025-08-08 20:27:38 +00:00
private Filter? BuildQueryFilter(IEnumerable<VectorFilterGroup>? filterGroups)
2025-08-06 18:52:24 +00:00
{
2025-08-08 20:27:38 +00:00
if (filterGroups.IsNullOrEmpty())
2025-08-06 18:52:24 +00:00
{
2025-08-15 22:19:18 +00:00
return null;
}
var groupConditions = filterGroups.Select(x => BuildFilterGroupCondition(x))
.Where(c => c != null)
.ToList();
if (groupConditions.IsNullOrEmpty())
{
return null;
}
// If there's only one group, return it directly to avoid unnecessary nesting
if (groupConditions.Count == 1 && groupConditions[0].Filter != null)
{
return groupConditions[0].Filter;
}
// Multiple groups are combined with AND by default
// This follows Qdrant's convention where multiple top-level conditions are ANDed
return new Filter
{
Must = { groupConditions }
};
}
private Condition? BuildFilterGroupCondition(VectorFilterGroup group)
{
if (group.Filters.IsNullOrEmpty())
{
return null;
}
var subGroupConditions = group.Filters
.Select(x => BuildSubGroupCondition(x))
.Where(c => c != null)
.ToList();
if (subGroupConditions.IsNullOrEmpty())
{
return null;
}
// If there's only one subgroup, return it directly
if (subGroupConditions.Count == 1 && subGroupConditions[0].Filter != null)
{
return subGroupConditions[0];
2025-08-08 20:27:38 +00:00
}
2025-08-15 22:19:18 +00:00
// Apply the group operator to combine subgroups
var filter = new Filter();
if (group.LogicalOperator.IsEqualTo("and"))
2025-08-08 20:27:38 +00:00
{
2025-08-15 22:19:18 +00:00
filter = new Filter
2025-08-06 18:52:24 +00:00
{
2025-08-15 22:19:18 +00:00
Must = { subGroupConditions }
};
}
else // "or"
{
filter = new Filter
{
Should = { subGroupConditions }
};
}
2025-08-06 18:52:24 +00:00
2025-08-15 22:19:18 +00:00
return new Condition { Filter = filter };
}
2025-08-06 18:52:24 +00:00
2025-08-15 22:19:18 +00:00
private Condition? BuildSubGroupCondition(VectorFilterSubGroup subGroup)
{
if (subGroup.Operands.IsNullOrEmpty())
{
return null;
}
var operandConditions = subGroup.Operands
.Select(x => BuildOperandCondition(x))
.Where(c => c != null)
.ToList();
2025-08-06 18:52:24 +00:00
2025-08-15 22:19:18 +00:00
if (operandConditions.IsNullOrEmpty())
{
return null;
}
// If there's only one operand, return it directly
if (operandConditions.Count == 1 && operandConditions[0].Filter != null)
{
return operandConditions[0];
}
// Apply the subgroup operator to combine operands
var filter = new Filter();
if (subGroup.LogicalOperator.IsEqualTo("and"))
{
filter = new Filter
2025-08-06 18:52:24 +00:00
{
2025-08-15 22:19:18 +00:00
Must = { operandConditions }
};
}
else // "or"
{
filter = new Filter
2025-08-06 21:36:36 +00:00
{
2025-08-15 22:19:18 +00:00
Should = { operandConditions }
};
}
return new Condition { Filter = filter };
}
private Condition? BuildOperandCondition(VectorFilterOperand operand)
{
Condition? condition = null;
if (operand.Match != null)
{
condition = BuildMatchCondition(operand.Match);
}
else if (operand.Range != null)
{
condition = BuildRangeCondition(operand.Range);
}
2025-08-08 20:27:38 +00:00
2025-08-15 22:19:18 +00:00
return condition;
}
private Condition? BuildMatchCondition(VectorFilterMatch match)
{
var fieldCondition = BuildMatchFieldCondition(match);
if (fieldCondition == null)
{
return null;
}
Condition condition;
if (match.Operator.IsEqualTo("eq"))
{
var filter = new Filter()
2025-08-08 20:27:38 +00:00
{
2025-08-15 22:19:18 +00:00
Must = { new Condition { Field = fieldCondition } }
2025-08-08 20:27:38 +00:00
};
2025-08-15 22:19:18 +00:00
condition = new Condition { Filter = filter };
}
else
{
var filter = new Filter()
{
MustNot = { new Condition { Field = fieldCondition } }
};
condition = new Condition { Filter = filter };
}
return condition;
}
private FieldCondition? BuildMatchFieldCondition(VectorFilterMatch match)
{
if (string.IsNullOrEmpty(match.Key) || match.Value == null)
{
return null;
}
var fieldCondition = new FieldCondition { Key = match.Key };
2025-08-08 20:27:38 +00:00
2025-08-15 22:19:18 +00:00
if (match.DataType == VectorPayloadDataType.Boolean
&& bool.TryParse(match.Value, out var boolVal))
{
fieldCondition.Match = new Match { Boolean = boolVal };
}
else if (match.DataType == VectorPayloadDataType.Integer
&& long.TryParse(match.Value, out var longVal))
2025-08-08 20:27:38 +00:00
{
2025-08-15 22:19:18 +00:00
fieldCondition.Match = new Match { Integer = longVal };
}
else
{
fieldCondition.Match = new Match { Text = match.Value };
}
return fieldCondition;
}
private Condition? BuildRangeCondition(VectorFilterRange range)
{
var fieldCondition = BuildRangeFieldCondition(range);
if (fieldCondition == null)
{
return null;
}
return new Condition
{
Field = fieldCondition
};
}
private FieldCondition? BuildRangeFieldCondition(VectorFilterRange range)
{
if (string.IsNullOrEmpty(range.Key) || range.Conditions.IsNullOrEmpty())
{
return null;
}
FieldCondition? fieldCondition = null;
if (range.DataType == VectorPayloadDataType.Datetime)
{
fieldCondition = new FieldCondition { Key = range.Key, DatetimeRange = new() };
foreach (var condition in range.Conditions)
2025-08-08 20:27:38 +00:00
{
2025-08-15 22:19:18 +00:00
if (!DateTime.TryParse(condition.Value, out var dt))
{
continue;
}
var utc = dt.ToUniversalTime();
var seconds = new DateTimeOffset(utc).ToUnixTimeSeconds();
var nanos = (int)((utc.Ticks % TimeSpan.TicksPerSecond) * 100);
var timestamp = new Google.Protobuf.WellKnownTypes.Timestamp { Seconds = seconds, Nanos = nanos };
switch (condition.Operator.ToLower())
{
case "lt":
fieldCondition.DatetimeRange.Lt = timestamp;
break;
case "lte":
fieldCondition.DatetimeRange.Lte = timestamp;
break;
case "gt":
fieldCondition.DatetimeRange.Gt = timestamp;
break;
case "gte":
fieldCondition.DatetimeRange.Gte = timestamp;
break;
}
2025-08-08 20:27:38 +00:00
}
2025-08-15 22:19:18 +00:00
}
else if (range.DataType == VectorPayloadDataType.Integer
|| range.DataType == VectorPayloadDataType.Double)
{
fieldCondition = new FieldCondition { Key = range.Key, Range = new() };
foreach (var condition in range.Conditions)
{
if (!double.TryParse(condition.Value, out var doubleVal))
{
continue;
}
switch (condition.Operator.ToLower())
{
case "lt":
fieldCondition.Range.Lt = doubleVal;
break;
case "lte":
fieldCondition.Range.Lte = doubleVal;
break;
case "gt":
fieldCondition.Range.Gt = doubleVal;
break;
case "gte":
fieldCondition.Range.Gte = doubleVal;
break;
}
}
}
2025-08-06 18:52:24 +00:00
2025-08-15 22:19:18 +00:00
return fieldCondition;
2025-08-06 18:52:24 +00:00
}
2025-08-20 19:48:11 +00:00
#endregion
2025-08-06 18:52:24 +00:00
2025-08-06 21:36:36 +00:00
private WithPayloadSelector? BuildPayloadSelector(IEnumerable<string>? payloads)
2025-08-06 18:52:24 +00:00
{
WithPayloadSelector? payloadSelector = null;
if (!payloads.IsNullOrEmpty())
{
payloadSelector = new WithPayloadSelector
{
Enable = true,
Include = new PayloadIncludeSelector
{
Fields = { payloads.ToArray() }
}
};
}
return payloadSelector;
}
2025-08-12 02:51:33 +00:00
private OrderBy? BuildOrderBy(VectorSort? sort)
{
if (string.IsNullOrWhiteSpace(sort?.Field))
{
return null;
}
return new OrderBy
{
Key = sort.Field,
2025-08-12 15:22:19 +00:00
Direction = sort.Order.IsEqualTo("asc") ? Direction.Asc : Direction.Desc
2025-08-12 02:51:33 +00:00
};
}
2025-08-06 15:14:22 +00:00
private PayloadSchemaType ConvertPayloadSchemaType(string schemaType)
{
PayloadSchemaType res;
switch (schemaType.ToLower())
{
case "text":
res = PayloadSchemaType.Text;
break;
case "keyword":
res = PayloadSchemaType.Keyword;
break;
case "integer":
res = PayloadSchemaType.Integer;
break;
case "float":
res = PayloadSchemaType.Float;
break;
case "bool":
2025-08-15 04:40:15 +00:00
case "boolean":
2025-08-06 15:14:22 +00:00
res = PayloadSchemaType.Bool;
break;
case "geo":
res = PayloadSchemaType.Geo;
break;
case "datetime":
res = PayloadSchemaType.Datetime;
break;
case "uuid":
res = PayloadSchemaType.Uuid;
break;
default:
res = PayloadSchemaType.UnknownType;
break;
}
return res;
}
2025-08-15 14:50:09 +00:00
private Dictionary<string, VectorPayloadValue> MapPayload(MapField<string, Value>? payload)
{
return payload?.ToDictionary(p => p.Key, p => p.Value.KindCase switch
{
Value.KindOneofCase.StringValue => VectorPayloadValue.BuildStringValue(p.Value.StringValue),
Value.KindOneofCase.BoolValue => VectorPayloadValue.BuildBooleanValue(p.Value.BoolValue),
Value.KindOneofCase.IntegerValue => VectorPayloadValue.BuildIntegerValue(p.Value.IntegerValue),
Value.KindOneofCase.DoubleValue => VectorPayloadValue.BuildDoubleValue(p.Value.DoubleValue),
_ => VectorPayloadValue.BuildUnkownValue(string.Empty)
}) ?? [];
}
2025-08-06 15:14:22 +00:00
#endregion
2023-06-18 02:56:22 +00:00
}