-
Notifications
You must be signed in to change notification settings - Fork 644
/
LuceneSearchService.cs
347 lines (300 loc) · 14.9 KB
/
LuceneSearchService.cs
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
using Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Search.Function;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using NuGetGallery.Helpers;
using NuGetGallery.Infrastructure.Lucene;
namespace NuGetGallery
{
public class LuceneSearchService : ISearchService
{
private Lucene.Net.Store.Directory _directory;
private static readonly string[] FieldAliases = new[] { "Id", "Title", "Tag", "Tags", "Description", "Author", "Authors", "Owner", "Owners" };
private static readonly string[] Fields = new[] { "Id", "Title", "Tags", "Description", "Authors", "Owners" };
public LuceneSearchService(Lucene.Net.Store.Directory directory)
{
_directory = directory;
}
public IQueryable<Package> Search(SearchFilter searchFilter, out int totalHits, IQueryable<Package> filterToPackageSet = null)
{
if (searchFilter == null)
{
throw new ArgumentNullException("searchFilter");
}
if (searchFilter.Skip < 0)
{
throw new ArgumentOutOfRangeException("searchFilter");
}
if (searchFilter.Take < 0)
{
throw new ArgumentOutOfRangeException("searchFilter");
}
return SearchCore(searchFilter, out totalHits, filterToPackageSet);
}
private IQueryable<Package> SearchCore(SearchFilter searchFilter, out int totalHits, IQueryable<Package> filterToPackageSet)
{
int numRecords = searchFilter.Skip + searchFilter.Take;
var searcher = new IndexSearcher(_directory, readOnly: true);
var query = ParseQuery(searchFilter);
// IF searching by relevance, boost scores by download count.
if (searchFilter.SortProperty == SortProperty.Relevance)
{
var downloadCountBooster = new FieldScoreQuery("DownloadCount", FieldScoreQuery.Type.INT);
query = new CustomScoreQuery(query, downloadCountBooster);
}
var filterTerm = searchFilter.IncludePrerelease ? "IsLatest" : "IsLatestStable";
var termQuery = new TermQuery(new Term(filterTerm, Boolean.TrueString));
Filter filter = new QueryWrapperFilter(termQuery);
if (filterToPackageSet != null)
{
filter = new IntersectionFilter(new PackageSetFilter(filterToPackageSet), filter);
}
var results = searcher.Search(query, filter: filter, n: numRecords, sort: new Sort(GetSortField(searchFilter)));
totalHits = results.totalHits;
if (results.totalHits == 0 || searchFilter.CountOnly)
{
return Enumerable.Empty<Package>().AsQueryable();
}
var packages = results.scoreDocs
.Skip(searchFilter.Skip)
.Select(sd => PackageFromDoc(searcher.Doc(sd.doc)))
.ToList();
return packages.AsQueryable();
}
private static Package PackageFromDoc(Document doc)
{
int downloadCount = Int32.Parse(doc.Get("DownloadCount"), CultureInfo.InvariantCulture);
int versionDownloadCount = Int32.Parse(doc.Get("VersionDownloadCount"), CultureInfo.InvariantCulture);
int key = Int32.Parse(doc.Get("Key"), CultureInfo.InvariantCulture);
int packageRegistrationKey = Int32.Parse(doc.Get("PackageRegistrationKey"), CultureInfo.InvariantCulture);
int packageSize = Int32.Parse(doc.Get("PackageFileSize"), CultureInfo.InvariantCulture);
bool isLatest = Boolean.Parse(doc.Get("IsLatest"));
bool isLatestStable = Boolean.Parse(doc.Get("IsLatestStable"));
bool requiresLicenseAcceptance = Boolean.Parse(doc.Get("RequiresLicenseAcceptance"));
DateTime created = DateTime.Parse(doc.Get("Created"), CultureInfo.InvariantCulture);
DateTime published = DateTime.Parse(doc.Get("Published"), CultureInfo.InvariantCulture);
DateTime lastUpdated = DateTime.Parse(doc.Get("LastUpdated"), CultureInfo.InvariantCulture);
var owners = doc.Get("FlattenedOwners")
.SplitSafe(new[] {';'}, StringSplitOptions.RemoveEmptyEntries)
.Select(o => new User {Username = o})
.ToArray();
var authors = doc.Get("FlattenedAuthors")
.SplitSafe(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
.Select(a => new PackageAuthor {Name = a.Trim()})
.ToArray();
var frameworks =
doc.Get("JoinedSupportedFrameworks")
.SplitSafe(new[] {';'}, StringSplitOptions.RemoveEmptyEntries)
.Select(s => new PackageFramework {TargetFramework = s})
.ToArray();
var dependencies =
doc.Get("FlattenedDependencies")
.SplitSafe(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries)
.Select(s => CreateDependency(s))
.ToArray();
return new Package
{
Authors = authors,
Copyright = doc.Get("Copyright"),
Created = created,
Description = doc.Get("Description"),
Dependencies = dependencies,
DownloadCount = versionDownloadCount,
FlattenedAuthors = doc.Get("FlattenedAuthors"),
FlattenedDependencies = doc.Get("FlattenedDependencies"),
Hash = doc.Get("Hash"),
HashAlgorithm = doc.Get("HashAlgorithm"),
IconUrl = doc.Get("IconUrl"),
IsLatest = isLatest,
IsLatestStable = isLatestStable,
Key = key,
Language = doc.Get("Language"),
LastUpdated = lastUpdated,
LicenseUrl = doc.Get("LicenseUrl"),
PackageRegistration = new PackageRegistration
{
Id = doc.Get("Id-Original"),
DownloadCount = downloadCount,
Key = packageRegistrationKey,
Owners = owners
},
PackageRegistrationKey = packageRegistrationKey,
PackageFileSize = packageSize,
ProjectUrl = doc.Get("ProjectUrl"),
Published = published,
ReleaseNotes = doc.Get("ReleaseNotes"),
RequiresLicenseAcceptance = requiresLicenseAcceptance,
Summary = doc.Get("Summary"),
Tags = doc.Get("Tags"),
Title = doc.Get("Title"),
Version = doc.Get("Version"),
SupportedFrameworks = frameworks,
MinClientVersion = doc.Get("MinClientVersion"),
};
}
private static PackageDependency CreateDependency(string s)
{
string[] parts = s.SplitSafe(new[] {':'}, StringSplitOptions.RemoveEmptyEntries);
return new PackageDependency
{
Id = parts.Length > 0 ? parts[0] : null,
VersionSpec = parts.Length > 1 ? parts[1] : null,
TargetFramework = parts.Length > 2 ? parts[2] : null,
};
}
private static Query ParseQuery(SearchFilter searchFilter)
{
// 1. parse the query into field clauses and general terms
// We imagine that mostly, field clauses are meant to 'filter' results found searching for general terms.
// The resulting clause collections may be empty.
var queryParser = new NuGetQueryParser();
var clauses = queryParser.Parse(searchFilter.SearchTerm).Select(StandardizeSearchTerms).ToList();
var fieldSpecificTerms = clauses.Where(a => a.Field != null);
var generalTerms = clauses.Where(a => a.Field == null);
// Convert terms to appropriate Lucene Query objects
var analyzer = new PerFieldAnalyzer();
var fieldSpecificQueries = fieldSpecificTerms
.Select(c => AnalysisHelper.GetFieldQuery(analyzer, c.Field, c.TermOrPhrase))
.Where(q => !IsDegenerateQuery(q))
.ToList();
var generalQueries = generalTerms
.Select(c => AnalysisHelper.GetMultiFieldQuery(analyzer, Fields, c.TermOrPhrase))
.Where(q => !IsDegenerateQuery(q))
.ToList();
if (fieldSpecificQueries.Count == 0 &&
generalQueries.Count == 0)
{
return new MatchAllDocsQuery();
}
// At this point we try to detect user intent...
// a) General search? [foo bar]
// b) Id-targeted search? [id:Foo bar]
// c) Other Field-targeted search? [author:Foo bar]
bool doExactId = !fieldSpecificQueries.Any();
Query generalQuery = BuildGeneralQuery(doExactId, searchFilter.SearchTerm, analyzer, generalTerms, generalQueries);
// IF field targeting is done, we should basically want to AND their field specific queries with all other query terms
if (fieldSpecificQueries.Any())
{
var combinedQuery = new BooleanQuery();
if (!IsDegenerateQuery(generalQuery))
{
combinedQuery.Add(generalQuery, BooleanClause.Occur.MUST);
}
foreach (var fieldQuery in fieldSpecificQueries)
{
if (!IsDegenerateQuery(fieldQuery))
{
combinedQuery.Add(fieldQuery, BooleanClause.Occur.MUST);
}
}
generalQuery = combinedQuery;
}
return generalQuery;
}
private static Query BuildGeneralQuery(
bool doExactId,
string originalSearchText,
Analyzer analyzer,
IEnumerable<NuGetSearchTerm> generalTerms,
IEnumerable<Query> generalQueries)
{
// All terms in the multi-term query appear in at least one of the target fields.
var conjuctionQuery = new BooleanQuery();
conjuctionQuery.SetBoost(2.0f);
// Some terms in the multi-term query appear in at least one of the target fields.
var disjunctionQuery = new BooleanQuery();
disjunctionQuery.SetBoost(0.1f);
// Suffix wildcard search e.g. jquer*
var wildCardQuery = new BooleanQuery();
wildCardQuery.SetBoost(0.5f);
string escapedExactId = originalSearchText.ToLowerInvariant();
Query exactIdQuery = null;
Query wildCardIdQuery = null;
if (doExactId)
{
exactIdQuery = new TermQuery(new Term("Id-Exact", escapedExactId));
exactIdQuery.SetBoost(7.5f);
wildCardIdQuery = new WildcardQuery(new Term("Id-Exact", "*" + escapedExactId + "*"));
}
Query nearlyExactIdQuery = null;
if (generalTerms.Any())
{
string escapedApproximateId = string.Join(" ", generalTerms.Select(c => c.TermOrPhrase));
nearlyExactIdQuery = AnalysisHelper.GetFieldQuery(analyzer, "Id", escapedApproximateId);
nearlyExactIdQuery.SetBoost(2.0f);
}
foreach (var termQuery in generalQueries)
{
conjuctionQuery.Add(termQuery, BooleanClause.Occur.MUST);
disjunctionQuery.Add(termQuery, BooleanClause.Occur.SHOULD);
}
var sanitizedTerms = generalTerms.Select(c => c.TermOrPhrase.ToLowerInvariant());
foreach (var sanitizedTerm in sanitizedTerms)
{
foreach (var field in Fields)
{
var wildCardTermQuery = new WildcardQuery(new Term(field, sanitizedTerm + "*"));
wildCardTermQuery.SetBoost(0.7f);
wildCardQuery.Add(wildCardTermQuery, BooleanClause.Occur.SHOULD);
}
}
// OR of all the applicable queries
var queries = new Query[]
{
exactIdQuery, wildCardIdQuery, nearlyExactIdQuery, conjuctionQuery, disjunctionQuery, wildCardQuery
};
var queriesToCombine = queries.Where(q => !IsDegenerateQuery(q));
var query = conjuctionQuery.Combine(queriesToCombine.ToArray());
return query;
}
// Helper function
// 1) fix cases of field names: ID -> Id
// 2) null out field names that we don't understand (so we will search them as non-field-specific terms)
// 3) For ID search, split search terms such as Id:"Foo.Bar" and "Foo-Bar" into a phrase "Foo Bar" which will work better for analyzed field search
private static NuGetSearchTerm StandardizeSearchTerms(NuGetSearchTerm input)
{
var fieldName = FieldAliases
.FirstOrDefault(f => f.Equals(input.Field, StringComparison.OrdinalIgnoreCase));
if (string.Equals(fieldName, "Author", StringComparison.OrdinalIgnoreCase))
{
fieldName = "Authors";
}
else if (string.Equals(fieldName, "Owner", StringComparison.OrdinalIgnoreCase))
{
fieldName = "Owners";
}
else if (string.Equals(fieldName, "Tag", StringComparison.OrdinalIgnoreCase))
{
fieldName = "Tags";
}
var searchTerm = new NuGetSearchTerm { Field = fieldName, TermOrPhrase = input.TermOrPhrase };
if (fieldName == "Id")
{
searchTerm.TermOrPhrase = LuceneIndexingService.SplitId(searchTerm.TermOrPhrase);
}
return searchTerm;
}
private static bool IsDegenerateQuery(Query q)
{
return q == null || (q is MatchAllDocsQuery) || ((q is BooleanQuery) && (q as BooleanQuery).Clauses().Count == 0);
}
private static SortField GetSortField(SearchFilter searchFilter)
{
switch (searchFilter.SortProperty)
{
case SortProperty.DisplayName:
return new SortField("DisplayName", SortField.STRING, reverse: searchFilter.SortDirection == SortDirection.Descending);
case SortProperty.DownloadCount:
return new SortField("DownloadCount", SortField.INT, reverse: true);
case SortProperty.Recent:
return new SortField("PublishedDate", SortField.LONG, reverse: true);
}
return SortField.FIELD_SCORE;
}
}
}