Skip to content

Commit 2fc4747

Browse files
committed
Reimplement compound index
1 parent ccccabe commit 2fc4747

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

Backend/Repositories/SemanticDomainCountRepository.cs

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,33 @@ namespace BackendFramework.Repositories
1010
{
1111
/// <summary> Atomic database functions for <see cref="ProjectSemanticDomainCount"/>s. </summary>
1212
[ExcludeFromCodeCoverage]
13-
public class SemanticDomainCountRepository(IMongoDbContext dbContext) : ISemanticDomainCountRepository
13+
public class SemanticDomainCountRepository : ISemanticDomainCountRepository
1414
{
15-
private readonly IMongoCollection<ProjectSemanticDomainCount> _counts =
16-
dbContext.Db.GetCollection<ProjectSemanticDomainCount>("SemanticDomainCountCollection");
15+
private readonly IMongoCollection<ProjectSemanticDomainCount> _counts;
1716

1817
private const string otelTagName = "otel.SemanticDomainCountRepository";
1918

19+
public SemanticDomainCountRepository(IMongoDbContext dbContext)
20+
{
21+
_counts = dbContext.Db.GetCollection<ProjectSemanticDomainCount>("SemanticDomainCountCollection");
22+
23+
// Create unique compound index on (ProjectId, DomainId) to optimize queries and enforce uniqueness
24+
var indexKeys =
25+
Builders<ProjectSemanticDomainCount>.IndexKeys.Ascending(p => p.ProjectId).Ascending(p => p.DomainId);
26+
var indexModel = new CreateIndexModel<ProjectSemanticDomainCount>(indexKeys, new() { Unique = true });
27+
28+
// Create the index if it doesn't already exist
29+
_counts.Indexes.CreateOne(indexModel);
30+
}
31+
2032
private static FilterDefinition<ProjectSemanticDomainCount> ProjectFilter(string projectId)
2133
{
2234
var filterDef = new FilterDefinitionBuilder<ProjectSemanticDomainCount>();
2335
return filterDef.Eq(c => c.ProjectId, projectId);
2436
}
2537

26-
private static FilterDefinition<ProjectSemanticDomainCount> ProjectDomainFilter(string projectId, string domainId)
38+
private static FilterDefinition<ProjectSemanticDomainCount> ProjectDomainFilter(
39+
string projectId, string domainId)
2740
{
2841
var filterDef = new FilterDefinitionBuilder<ProjectSemanticDomainCount>();
2942
return filterDef.And(filterDef.Eq(c => c.ProjectId, projectId), filterDef.Eq(c => c.DomainId, domainId));

0 commit comments

Comments
 (0)