forked from apache/lucenenet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchGroup.cs
More file actions
505 lines (447 loc) · 20.1 KB
/
Copy pathSearchGroup.cs
File metadata and controls
505 lines (447 loc) · 20.1 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
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Search.Grouping
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Represents a group that is found during the first pass search.
///
/// @lucene.experimental
/// </summary>
/// <typeparam name="TGroupValue"></typeparam>
public class SearchGroup<TGroupValue> : ISearchGroup
{
/// <summary>
/// The value that defines this group
/// </summary>
public TGroupValue GroupValue { get; set; }
/// <summary>
/// The sort values used during sorting. These are the
/// groupSort field values of the highest rank document
/// (by the groupSort) within the group. Can be
/// <c>null</c> if <c>fillFields=false</c> had
/// been passed to <see cref="AbstractFirstPassGroupingCollector{TGroupValue}.GetTopGroups(int, bool)"/>
/// </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public object[] SortValues { get; set; }
public override string ToString()
{
return ("SearchGroup(groupValue=" + GroupValue + " sortValues=" + Arrays.ToString(SortValues) + ")");
}
public override bool Equals(object o)
{
if (this == o) return true;
if (o is null || GetType() != o.GetType()) return false;
SearchGroup<TGroupValue> that = (SearchGroup<TGroupValue>)o;
if (GroupValue is null)
{
if (that.GroupValue != null)
{
return false;
}
}
else if (!GroupValue.Equals(that.GroupValue))
{
return false;
}
return true;
}
public override int GetHashCode()
{
return GroupValue != null ? GroupValue.GetHashCode() : 0;
}
#region Explicit interface implementations
/// <summary>
/// LUCENENET specific implementation to provide an object-based implementation of <see cref="GroupValue"/>.
/// </summary>
object ISearchGroup.GroupValue => GroupValue;
#endregion
}
/// <summary>
/// LUCENENET specific class used to nest types to mimic the syntax used
/// by Lucene (that is, without specifying the generic closing type of <see cref="SearchGroup{TGroupValue}"/>)
/// </summary>
public static class SearchGroup // LUCENENET specific: CA1052 Static holder types should be Static or NotInheritable
{
private class ShardIter<T>
{
public IEnumerator<SearchGroup<T>> Iter => iter;
private readonly IEnumerator<SearchGroup<T>> iter;
public int ShardIndex => shardIndex;
private readonly int shardIndex;
public ShardIter(ICollection<SearchGroup<T>> shard, int shardIndex)
{
this.shardIndex = shardIndex;
iter = shard.GetEnumerator();
//if (Debugging.AssertsEnabled) Debugging.Assert(iter.hasNext()); // No reasonable way to do this in .NET
}
public SearchGroup<T> Next()
{
//if (Debugging.AssertsEnabled) Debugging.Assert(iter.hasNext()); // No reasonable way to do this in .NET
SearchGroup<T> group = iter.Current;
if (group.SortValues is null)
{
throw new ArgumentException("group.sortValues is null; you must pass fillFields=true to the first pass collector");
}
return group;
}
public override string ToString()
{
return "ShardIter(shard=" + shardIndex + ")";
}
}
/// <summary>
/// Holds all shards currently on the same group
/// </summary>
/// <typeparam name="T"></typeparam>
private class MergedGroup<T>
{
// groupValue may be null!
public T GroupValue => groupValue;
private readonly T groupValue;
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public object[] TopValues
{
get => topValues;
set => topValues = value;
}
private object[] topValues;
public IList<ShardIter<T>> Shards => shards;
private readonly IList<ShardIter<T>> shards = new JCG.List<ShardIter<T>>();
public int MinShardIndex
{
get => minShardIndex;
set => minShardIndex = value;
}
private int minShardIndex;
public bool IsProcessed
{
get => processed;
set => processed = value;
}
private bool processed;
public bool IsInQueue
{
get => inQueue;
set => inQueue = value;
}
private bool inQueue;
// LUCENENET specific - store whether T is value type
// for optimization of GetHashCode() and Equals()
private readonly static bool groupValueIsValueType = typeof(T).IsValueType;
public MergedGroup(T groupValue)
{
this.groupValue = groupValue;
}
// Only for assert
private bool NeverEquals(object other)
{
if (other is MergedGroup<T> otherMergedGroup)
{
if (groupValue is null)
{
if (Debugging.AssertsEnabled) Debugging.Assert(otherMergedGroup.groupValue != null);
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert(!groupValueIsValueType
? JCG.EqualityComparer<T>.Default.Equals(groupValue, otherMergedGroup.groupValue)
// LUCENENET specific - use J2N.Collections.StructuralEqualityComparer.Default.Equals() if we have a reference type
// to ensure if it is a collection its contents are compared
: J2N.Collections.StructuralEqualityComparer.Default.Equals(groupValue, otherMergedGroup.groupValue));
}
}
return true;
}
public override bool Equals(object other)
{
// We never have another MergedGroup instance with
// same groupValue
if (Debugging.AssertsEnabled) Debugging.Assert(NeverEquals(other));
if (other is MergedGroup<T> otherMergedGroup)
{
if (groupValue is null)
{
return otherMergedGroup is null;
}
else
{
// LUCENENET specific - use J2N.Collections.StructuralEqualityComparer.Default.Equals() if we have a reference type
// to ensure if it is a collection its contents are compared
return groupValueIsValueType ?
JCG.EqualityComparer<T>.Default.Equals(groupValue, otherMergedGroup.groupValue) :
J2N.Collections.StructuralEqualityComparer.Default.Equals(groupValue, otherMergedGroup.groupValue);
}
}
else
{
return false;
}
}
public override int GetHashCode()
{
if (groupValue is null)
{
return 0;
}
else
{
// LUCENENET specific - use J2N.Collections.StructuralEqualityComparer.Default.GetHashCode() if we have a reference type
// to ensure if it is a collection its contents are compared
return groupValueIsValueType ?
JCG.EqualityComparer<T>.Default.GetHashCode(groupValue) :
J2N.Collections.StructuralEqualityComparer.Default.GetHashCode(groupValue);
}
}
}
private class GroupComparer<T> : IComparer<MergedGroup<T>>
{
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public FieldComparer[] Comparers => comparers;
private readonly FieldComparer[] comparers;
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public int[] Reversed => reversed;
private readonly int[] reversed;
public GroupComparer(Sort groupSort)
{
SortField[] sortFields = groupSort.GetSort();
comparers = new FieldComparer[sortFields.Length];
reversed = new int[sortFields.Length];
for (int compIDX = 0; compIDX < sortFields.Length; compIDX++)
{
SortField sortField = sortFields[compIDX];
comparers[compIDX] = sortField.GetComparer(1, compIDX);
reversed[compIDX] = sortField.IsReverse ? -1 : 1;
}
}
public virtual int Compare(MergedGroup<T> group, MergedGroup<T> other)
{
if (group == other)
{
return 0;
}
//System.out.println("compare group=" + group + " other=" + other);
object[] groupValues = group.TopValues;
object[] otherValues = other.TopValues;
//System.out.println(" groupValues=" + groupValues + " otherValues=" + otherValues);
for (int compIDX = 0; compIDX < comparers.Length; compIDX++)
{
int c = reversed[compIDX] * comparers[compIDX].CompareValues(groupValues[compIDX],
otherValues[compIDX]);
if (c != 0)
{
return c;
}
}
// Tie break by min shard index:
if (Debugging.AssertsEnabled) Debugging.Assert(group.MinShardIndex != other.MinShardIndex);
return group.MinShardIndex - other.MinShardIndex;
}
}
private class GroupMerger<T>
{
private readonly GroupComparer<T> groupComp;
private readonly JCG.SortedSet<MergedGroup<T>> queue;
private readonly IDictionary<T, MergedGroup<T>> groupsSeen;
public GroupMerger(Sort groupSort)
{
groupComp = new GroupComparer<T>(groupSort);
queue = new JCG.SortedSet<MergedGroup<T>>(groupComp);
groupsSeen = new JCG.Dictionary<T, MergedGroup<T>>();
}
private void UpdateNextGroup(int topN, ShardIter<T> shard)
{
while (shard.Iter.MoveNext())
{
SearchGroup<T> group = shard.Next();
bool isNew = !groupsSeen.TryGetValue(group.GroupValue, out MergedGroup<T> mergedGroup) || mergedGroup is null;
//System.out.println(" next group=" + (group.groupValue is null ? "null" : ((BytesRef) group.groupValue).utf8ToString()) + " sort=" + Arrays.toString(group.sortValues));
if (isNew)
{
// Start a new group:
//System.out.println(" new");
mergedGroup = new MergedGroup<T>(group.GroupValue);
mergedGroup.MinShardIndex = shard.ShardIndex;
if (Debugging.AssertsEnabled) Debugging.Assert(group.SortValues != null);
mergedGroup.TopValues = group.SortValues;
groupsSeen[group.GroupValue] = mergedGroup;
mergedGroup.IsInQueue = true;
queue.Add(mergedGroup);
}
else if (mergedGroup.IsProcessed)
{
// This shard produced a group that we already
// processed; move on to next group...
continue;
}
else
{
//System.out.println(" old");
bool competes = false;
for (int compIDX = 0; compIDX < groupComp.Comparers.Length; compIDX++)
{
int cmp = groupComp.Reversed[compIDX] * groupComp.Comparers[compIDX].CompareValues(group.SortValues[compIDX],
mergedGroup.TopValues[compIDX]);
if (cmp < 0)
{
// Definitely competes
competes = true;
break;
}
else if (cmp > 0)
{
// Definitely does not compete
break;
}
else if (compIDX == groupComp.Comparers.Length - 1)
{
if (shard.ShardIndex < mergedGroup.MinShardIndex)
{
competes = true;
}
}
}
//System.out.println(" competes=" + competes);
if (competes)
{
// Group's sort changed -- remove & re-insert
if (mergedGroup.IsInQueue)
{
queue.Remove(mergedGroup);
}
mergedGroup.TopValues = group.SortValues;
mergedGroup.MinShardIndex = shard.ShardIndex;
queue.Add(mergedGroup);
mergedGroup.IsInQueue = true;
}
}
mergedGroup.Shards.Add(shard);
break;
}
// Prune un-competitive groups:
while (queue.Count > topN)
{
queue.RemoveLast(out MergedGroup<T> group);
//System.out.println("PRUNE: " + group);
group.IsInQueue = false;
}
}
public virtual ICollection<SearchGroup<T>> Merge(IList<ICollection<SearchGroup<T>>> shards, int offset, int topN)
{
int maxQueueSize = offset + topN;
//System.out.println("merge");
// Init queue:
for (int shardIDX = 0; shardIDX < shards.Count; shardIDX++)
{
ICollection<SearchGroup<T>> shard = shards[shardIDX];
if (shard.Count > 0)
{
//System.out.println(" insert shard=" + shardIDX);
UpdateNextGroup(maxQueueSize, new ShardIter<T>(shard, shardIDX));
}
}
// Pull merged topN groups:
IList<SearchGroup<T>> newTopGroups = new JCG.List<SearchGroup<T>>();
int count = 0;
while (queue.Count != 0)
{
queue.RemoveFirst(out MergedGroup<T> group);
group.IsProcessed = true;
//System.out.println(" pop: shards=" + group.shards + " group=" + (group.groupValue is null ? "null" : (((BytesRef) group.groupValue).utf8ToString())) + " sortValues=" + Arrays.toString(group.topValues));
if (count++ >= offset)
{
SearchGroup<T> newGroup = new SearchGroup<T>();
newGroup.GroupValue = group.GroupValue;
newGroup.SortValues = group.TopValues;
newTopGroups.Add(newGroup);
if (newTopGroups.Count == topN)
{
break;
}
//} else {
// System.out.println(" skip < offset");
}
// Advance all iters in this group:
foreach (ShardIter<T> shardIter in group.Shards)
{
UpdateNextGroup(maxQueueSize, shardIter);
}
}
if (newTopGroups.Count == 0)
{
return null;
}
else
{
return newTopGroups;
}
}
}
/// <summary>
/// Merges multiple collections of top groups, for example
/// obtained from separate index shards. The provided
/// groupSort must match how the groups were sorted, and
/// the provided SearchGroups must have been computed
/// with <c>fillFields=true</c> passed to
/// <see cref="AbstractFirstPassGroupingCollector{TGroupValue}.GetTopGroups(int, bool)"/>.
/// <para>
/// NOTE: this returns null if the topGroups is empty.
/// </para>
/// </summary>
public static ICollection<SearchGroup<T>> Merge<T>(IList<ICollection<SearchGroup<T>>> topGroups, int offset, int topN, Sort groupSort)
{
if (topGroups.Count == 0)
{
return null;
}
else
{
return new GroupMerger<T>(groupSort).Merge(topGroups, offset, topN);
}
}
}
/// <summary>
/// LUCENENET specific interface to provide a non-generic abstraction
/// for <see cref="SearchGroup{TGroupValue}"/>.
/// </summary>
public interface ISearchGroup
{
/// <summary>
/// The value that defines this group
/// </summary>
object GroupValue { get; }
/// <summary>
/// The sort values used during sorting. These are the
/// groupSort field values of the highest rank document
/// (by the groupSort) within the group. Can be
/// <c>null</c> if <c>fillFields=false</c> had
/// been passed to <see cref="AbstractFirstPassGroupingCollector{TGroupValue}.GetTopGroups(int, bool)"/>
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
[WritableArray]
object[] SortValues { get; set; }
}
}