-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathDocumentRepository.cs
More file actions
207 lines (166 loc) · 9.24 KB
/
DocumentRepository.cs
File metadata and controls
207 lines (166 loc) · 9.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT License.
using Microsoft.GS.DPS.Storage.Components;
using System.Collections.Specialized;
using MongoDB.Driver;
using System.ComponentModel;
using MongoDB.Bson;
namespace Microsoft.GS.DPS.Storage.Document
{
public class DocumentRepository
{
private readonly IMongoCollection<Entities.Document> _collection;
public DocumentRepository(IMongoDatabase database, string collectionName)
{
_collection = database.GetCollection<Entities.Document>(collectionName);
// if Database is empty, create a new collection
if (_collection == null)
{
database.CreateCollection(collectionName);
_collection = database.GetCollection<Entities.Document>(collectionName);
}
// Ensure indexs
EnsureIndexesOnField("ImportedTime");
EnsureIndexesOnField("DocumentId");
EnsureIndexesOnField("FileName");
}
private void EnsureIndexesOnField(string indexFieldName)
{
var indexKeysDefinition = Builders<Entities.Document>.IndexKeys.Descending(indexFieldName);
var indexModel = new CreateIndexModel<Entities.Document>(indexKeysDefinition);
// Check if the index already exists
var indexes = _collection.Indexes.List().ToList();
var indexExists = indexes.Any(index => index["key"].AsBsonDocument.Contains(indexFieldName));
if (!indexExists)
{
_collection.Indexes.CreateOne(indexModel);
}
}
public async Task<IEnumerable<Entities.Document>> GetAllDocuments()
{
//Get All Records then get only Keywords field.
//This is to avoid getting the whole document and only get the keywords field
return await _collection.Find(Builders<Entities.Document>.Filter.Empty)
.Project<Entities.Document>(Builders<Entities.Document>.Projection.Include(x => x.Keywords))
.ToListAsync();
}
public async Task<QueryResultSet> GetAllDocumentsByPageAsync(int pageNumber, int pageSize, DateTime? startDate, DateTime? endDate)
{
//Make filter by StartDate and EndDate
//Just in case StartDate is null and EndDate only, define filter between Current and EndDate
//Just in case StartDate and EndDate is not null, define filter between StartDate and EndDate
//endDate should be converted from datetime to DateTime of end of day Day:23:59:59
//FilterDefinition<Entities.Document> filter = Builders<Entities.Document>.Filter.Empty;
List<FilterDefinition<Entities.Document>> filters = new List<FilterDefinition<Entities.Document>>();
if (startDate.HasValue) {
// startDate = startDate?.Date.AddHours(0).AddMinutes(0).AddSeconds(0);
// UI itself is calculates the start date so we dont need to add above line -bugID:8948
filters.Add(Builders<Entities.Document>.Filter.Gte(x => x.ImportedTime, startDate));
filters.Add(Builders<Entities.Document>.Filter.Lte(x => x.ImportedTime, endDate ?? DateTime.Now));
}
var combinedFilter = filters.Count > 0 ? Builders<Entities.Document>.Filter.And(filters) : Builders<Entities.Document>.Filter.Empty;
return await this.GetDocumentsByPageAsync(combinedFilter,
Builders<Entities.Document>.Sort.Descending(x => x.ImportedTime),
pageNumber,
pageSize);
}
public async Task<QueryResultSet> FindByTagsAsync(Dictionary<string,string> keywords, int pageNumber, int pageSize)
{
//Define filter from keywords
var filters = new List<FilterDefinition<Entities.Document>>();
foreach (var kvp in keywords)
{
var values = kvp.Value.Split(',').Select(v => v.Trim()).ToArray();
var regexPattern = string.Join("|", values.Select(v => $"\\b{v}\\b"));
var filter = Builders<Entities.Document>.Filter.Regex($"Keywords.{kvp.Key}", new BsonRegularExpression(regexPattern, "i"));
filters.Add(filter);
}
var combinedFilter = Builders<Entities.Document>.Filter.And(filters);
return await this.GetDocumentsByPageAsync(combinedFilter,
Builders<Entities.Document>.Sort.Descending(x => x.ImportedTime),
pageNumber,
pageSize);
}
private async Task<QueryResultSet> GetDocumentsByPageAsync(FilterDefinition<Entities.Document> filterDefinition,
SortDefinition<Entities.Document> sortDefinition,
int pageNumber,
int pageSize)
{
var skip = (pageNumber - 1) * pageSize;
var documents = await _collection.Find(filterDefinition)
.Sort(sortDefinition)
.Skip(skip)
.Limit(pageSize)
.ToListAsync();
var totalCount = await GetTotalCountAsync(filterDefinition);
return new QueryResultSet() {
Results = documents,
TotalPages = GetTotalPages(pageSize, totalCount),
TotalRecords = totalCount,
CurrentPage = pageNumber
};
}
private async Task<int> GetTotalCountAsync(FilterDefinition<Entities.Document> filterDefinition)
{
return (int)await _collection.CountDocumentsAsync(filterDefinition);
}
private int GetTotalPages(int pageSize, double recordsCount)
{
return (int)Math.Ceiling((double)recordsCount / pageSize);
}
public async Task<Entities.Document> RegisterAsync(Entities.Document document)
{
await _collection.InsertOneAsync(document);
return document;
}
public async Task<Entities.Document> UpdateAsync(Entities.Document document)
{
var result = await _collection.ReplaceOneAsync(Builders<Entities.Document>.Filter.Eq(x => x.id, document.id), document);
if (result.IsAcknowledged && result.ModifiedCount > 0)
{
return document;
}
else
{
return null;
}
}
public async Task DeleteAsync(Guid id)
{
await _collection.DeleteOneAsync(Builders<Entities.Document>.Filter.Eq(x => x.id, id));
}
async public Task<Entities.Document> FindByIdAsync(Guid id)
{
return await _collection.Find(Builders<Entities.Document>.Filter.Eq(x => x.id, id)).FirstOrDefaultAsync();
}
async public Task<Entities.Document> FindByDocumentIdAsync(string documentId)
{
var filterDefinition = Builders<Entities.Document>.Filter.Eq(x => x.DocumentId, documentId);
return await _collection.Find(filterDefinition).FirstOrDefaultAsync();
}
async public Task<QueryResultSet> FindByDocumentIdsAsync(string[] documentIds)
{
return await this.FindByDocumentIdsAsync(documentIds, 1, 100);
}
async public Task<QueryResultSet> FindByDocumentIdsAsync(string[] documentIds,
int pageNumber,
int pageSize,
DateTime? startDate = null,
DateTime? endDate = null)
{
var filterDefinition = Builders<Entities.Document>.Filter.In(x => x.DocumentId, documentIds);
//Make filter by StartDate and EndDate
//Just in case StartDate is null and EndDate only, define filter between Current and EndDate
//Just in case StartDate and EndDate is not null, define filter between StartDate and EndDate
//endDate should be converted from datetime to DateTime of end of day Day:23:59:59
if (endDate.HasValue)
{
endDate = endDate?.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
var timeFilter = Builders<Entities.Document>.Filter.Gte(x => x.ImportedTime, startDate ?? DateTime.Now) &
Builders<Entities.Document>.Filter.Lte(x => x.ImportedTime, endDate.Value);
filterDefinition &= timeFilter;
}
return await this.GetDocumentsByPageAsync(filterDefinition, Builders<Entities.Document>.Sort.Descending(x => x.ImportedTime), pageNumber, pageSize);
}
}
}