-
Notifications
You must be signed in to change notification settings - Fork 0
/
BLSpanOrQuery.java
604 lines (527 loc) · 17.6 KB
/
BLSpanOrQuery.java
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
package nl.inl.blacklab.search.lucene;
/*
* 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.
*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermContext;
import org.apache.lucene.search.DisiPriorityQueue;
import org.apache.lucene.search.DisiWrapper;
import org.apache.lucene.search.DisjunctionDISIApproximation;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TwoPhaseIterator;
import org.apache.lucene.search.spans.ScoringWrapperSpans;
import org.apache.lucene.search.spans.SpanCollector;
import org.apache.lucene.search.spans.SpanOrQuery;
import org.apache.lucene.search.spans.SpanQuery;
import org.apache.lucene.search.spans.SpanWeight;
import org.apache.lucene.search.spans.Spans;
import org.apache.lucene.util.PriorityQueue;
import nl.inl.blacklab.search.Span;
import nl.inl.blacklab.search.fimatch.NfaFragment;
import nl.inl.blacklab.search.fimatch.NfaState;
import nl.inl.blacklab.search.fimatch.ForwardIndexAccessor;
/** Matches the union of its clauses.
*/
public final class BLSpanOrQuery extends BLSpanQuery {
SpanOrQuery inner;
String field;
private String luceneField;
/** Construct a SpanOrQuery merging the provided clauses.
* All clauses must have the same field.
* @param clauses clauses to OR together
*/
public BLSpanOrQuery(BLSpanQuery... clauses) {
inner = new SpanOrQuery(clauses);
this.field = inner.getField();
this.luceneField = clauses.length > 0 ? clauses[0].getRealField() : field;
}
static BLSpanOrQuery from(SpanOrQuery in) {
SpanQuery[] clauses = in.getClauses();
BLSpanQuery[] blClauses = new BLSpanQuery[clauses.length];
for (int i = 0; i < clauses.length; i++) {
blClauses[i] = BLSpanQuery.wrap(clauses[i]);
}
BLSpanOrQuery out = new BLSpanOrQuery(blClauses);
return out;
}
/** Return the clauses whose spans are matched.
* @return the clauses
*/
public SpanQuery[] getClauses() {
return inner.getClauses();
}
/**
* Explicitly set the field for this query. Required because some queries
* rewrite to 0-clause or queries, and we need to be able to call getField()
* later.
*
* @param field
* the field for this query
*/
public void setField(String field) {
this.field = field;
}
@Override
public String getField() {
return field;
}
@Override
public String getRealField() {
return luceneField;
}
@Override
public BLSpanQuery rewrite(IndexReader reader) throws IOException {
// Flatten nested OR queries.
// This doesn't change the query because the OR operator is associative.
boolean anyRewritten = false;
boolean onlyNotClauses = true;
boolean allClausesSingleToken = true;
List<BLSpanQuery> rewrittenCl = new ArrayList<>();
for (SpanQuery ch: inner.getClauses()) {
BLSpanQuery child = (BLSpanQuery)ch;
BLSpanQuery rewritten = child.rewrite(reader);
if (rewritten instanceof BLSpanOrQuery) {
// Flatten.
// Child OR operation we want to flatten into this OR operation.
// Replace the child, incorporating its children into this OR operation.
for (SpanQuery cl: ((BLSpanOrQuery)rewritten).getClauses()) {
BLSpanQuery clause = (BLSpanQuery)cl;
if (!clause.hitsAllSameLength() || clause.hitsLengthMax() != 1)
allClausesSingleToken = false;
if (!clause.isSingleTokenNot())
onlyNotClauses = false;
rewrittenCl.add(clause);
}
anyRewritten = true;
} else {
if (!rewritten.hitsAllSameLength() || rewritten.hitsLengthMax() != 1)
allClausesSingleToken = false;
if (!rewritten.isSingleTokenNot())
onlyNotClauses = false;
// Just add it.
rewrittenCl.add(rewritten);
if (rewritten != child)
anyRewritten = true;
}
}
// Rewrites OR queries containing only NOT children into "NAND" queries.
// (only possible if all OR queries have token length 1!)
// This saves on NOT queries and helps us isolate problematic subclauses which
// we can then rewrite to more efficient NOTCONTAINING clauses.
if (rewrittenCl.size() > 0 && onlyNotClauses && allClausesSingleToken) {
// At least one clause starts with NOT.
// Node should be rewritten to AND. Invert all clauses.
for (int i = 0; i < rewrittenCl.size(); i++) {
rewrittenCl.set(i, rewrittenCl.get(i).inverted());
}
// Note extra rewrite at the end to make sure AND NOT structure is correctly built.
if (rewrittenCl.size() == 1)
return rewrittenCl.get(0).inverted();
return (new SpanQueryAnd(rewrittenCl).inverted()).rewrite(reader);
}
if (anyRewritten) {
// Some clauses were rewritten.
if (rewrittenCl.size() == 1)
return rewrittenCl.get(0);
return new BLSpanOrQuery(rewrittenCl.toArray(new BLSpanQuery[0]));
}
// Node need not be rewritten; return as-is
if (inner.getClauses().length == 1)
return BLSpanQuery.wrap(inner.getClauses()[0]);
return this;
}
@Override
public boolean matchesEmptySequence() {
for (SpanQuery cl: getClauses()) {
BLSpanQuery clause = (BLSpanQuery)cl;
if (clause.matchesEmptySequence())
return true;
}
return false;
}
@Override
public BLSpanQuery noEmpty() {
if (!matchesEmptySequence())
return this;
List<BLSpanQuery> newCl = new ArrayList<>();
for (SpanQuery cl: inner.getClauses()) {
newCl.add(((BLSpanQuery)cl).noEmpty());
}
return new BLSpanOrQuery(newCl.toArray(new BLSpanQuery[0]));
}
@Override
public boolean hitsAllSameLength() {
if (getClauses().length == 0)
return true;
int l = ((BLSpanQuery)getClauses()[0]).hitsLengthMin();
for (SpanQuery cl: getClauses()) {
BLSpanQuery clause = (BLSpanQuery)cl;
if (!clause.hitsAllSameLength() || clause.hitsLengthMin() != l)
return false;
}
return true;
}
@Override
public int hitsLengthMin() {
int n = Integer.MAX_VALUE;
for (SpanQuery cl: getClauses()) {
BLSpanQuery clause = (BLSpanQuery)cl;
n = Math.min(n, clause.hitsLengthMin());
}
return n == Integer.MAX_VALUE ? 0 : n;
}
@Override
public int hitsLengthMax() {
int n = 0;
for (SpanQuery cl: getClauses()) {
BLSpanQuery clause = (BLSpanQuery)cl;
int l = clause.hitsLengthMax();
n = Math.max(n, l);
if (n == Integer.MAX_VALUE)
return n; // infinite
}
return n;
}
@Override
public boolean hitsEndPointSorted() {
// Cannot guarantee because we're merging from different sources.
return false;
}
@Override
public boolean hitsStartPointSorted() {
// Our way of merging guarantees this, as it should for almost all BLSpans
return true;
}
@Override
public boolean hitsHaveUniqueStart() {
// Cannot guarantee because we're merging from different sources.
return false;
}
@Override
public boolean hitsHaveUniqueEnd() {
// Cannot guarantee because we're merging from different sources.
return false;
}
@Override
public boolean hitsAreUnique() {
// Cannot guarantee because we're merging from different sources.
return false;
}
@Override
public String toString(String field) {
return "OR(" + clausesToString(field, inner.getClauses()) + ")";
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o instanceof BLSpanOrQuery) {
return inner.equals(((BLSpanOrQuery)o).inner);
}
return false;
}
@Override
public int hashCode() {
return inner.hashCode() ^ 0xB1ACC1AB;
}
@Override
public BLSpanWeight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException {
List<BLSpanWeight> subWeights = new ArrayList<>(inner.getClauses().length);
for (SpanQuery q: inner.getClauses()) {
BLSpanWeight weight = ((BLSpanQuery)q).createWeight(searcher, false);
subWeights.add(weight);
}
Map<Term, TermContext> contexts = needsScores ? getTermContexts(subWeights.toArray(new SpanWeight[0])) : null;
return new SpanOrWeight(searcher, contexts, subWeights);
}
public class SpanOrWeight extends BLSpanWeight {
final List<BLSpanWeight> subWeights;
public SpanOrWeight(IndexSearcher searcher, Map<Term, TermContext> terms, List<BLSpanWeight> subWeights) throws IOException {
super(BLSpanOrQuery.this, searcher, terms);
this.subWeights = subWeights;
}
@Override
public void extractTerms(Set<Term> terms) {
for (final BLSpanWeight w: subWeights) {
w.extractTerms(terms);
}
}
@Override
public void extractTermContexts(Map<Term, TermContext> contexts) {
for (BLSpanWeight w: subWeights) {
w.extractTermContexts(contexts);
}
}
class SpanPositionQueue extends PriorityQueue<Spans> {
SpanPositionQueue(int maxSize) {
super(maxSize, false); // do not prepopulate
}
@Override
protected boolean lessThan(Spans s1, Spans s2) {
int start1 = s1.startPosition();
int start2 = s2.startPosition();
return (start1 < start2) ? true : (start1 == start2) ? s1.endPosition() < s2.endPosition() : false;
}
}
@Override
public BLSpans getSpans(final LeafReaderContext context, Postings requiredPostings) throws IOException {
final ArrayList<Spans> subSpans = new ArrayList<>(inner.getClauses().length);
for (SpanWeight w: subWeights) {
Spans spans = w.getSpans(context, requiredPostings);
if (spans != null) {
subSpans.add(spans);
}
}
if (subSpans.isEmpty()) {
return null;
} else if (subSpans.size() == 1) {
return new BLSpansWrapper(new ScoringWrapperSpans(subSpans.get(0), getSimScorer(context)));
}
final DisiPriorityQueue byDocQueue = new DisiPriorityQueue(subSpans.size());
for (Spans spans: subSpans) {
byDocQueue.add(new DisiWrapper(spans));
}
final SpanPositionQueue byPositionQueue = new SpanPositionQueue(subSpans.size()); // when
// empty
// use
// -1
return new BLSpans() {
Spans topPositionSpans = null;
@Override
public int nextDoc() throws IOException {
topPositionSpans = null;
DisiWrapper topDocSpans = byDocQueue.top();
int currentDoc = topDocSpans.doc;
do {
topDocSpans.doc = topDocSpans.iterator.nextDoc();
topDocSpans = byDocQueue.updateTop();
} while (topDocSpans.doc == currentDoc);
return topDocSpans.doc;
}
@Override
public int advance(int target) throws IOException {
topPositionSpans = null;
DisiWrapper topDocSpans = byDocQueue.top();
do {
topDocSpans.doc = topDocSpans.iterator.advance(target);
topDocSpans = byDocQueue.updateTop();
} while (topDocSpans.doc < target);
return topDocSpans.doc;
}
@Override
public int docID() {
DisiWrapper topDocSpans = byDocQueue.top();
return topDocSpans.doc;
}
@Override
public TwoPhaseIterator asTwoPhaseIterator() {
float sumMatchCost = 0; // See also DisjunctionScorer.asTwoPhaseIterator()
long sumApproxCost = 0;
for (DisiWrapper w: byDocQueue) {
if (w.twoPhaseView != null) {
long costWeight = (w.cost <= 1) ? 1 : w.cost;
sumMatchCost += w.twoPhaseView.matchCost() * costWeight;
sumApproxCost += costWeight;
}
}
if (sumApproxCost == 0) { // no sub spans supports approximations
computePositionsCost();
return null;
}
final float matchCost = sumMatchCost / sumApproxCost;
return new TwoPhaseIterator(new DisjunctionDISIApproximation(byDocQueue)) {
@Override
public boolean matches() throws IOException {
return twoPhaseCurrentDocMatches();
}
@Override
public float matchCost() {
return matchCost;
}
};
}
float positionsCost = -1;
void computePositionsCost() {
float sumPositionsCost = 0;
long sumCost = 0;
for (DisiWrapper w: byDocQueue) {
long costWeight = (w.cost <= 1) ? 1 : w.cost;
sumPositionsCost += w.spans.positionsCost() * costWeight;
sumCost += costWeight;
}
positionsCost = sumPositionsCost / sumCost;
}
@Override
public float positionsCost() {
// This may be called when asTwoPhaseIterator returned null,
// which happens when none of the sub spans supports approximations.
assert positionsCost > 0;
return positionsCost;
}
int lastDocTwoPhaseMatched = -1;
boolean twoPhaseCurrentDocMatches() throws IOException {
DisiWrapper listAtCurrentDoc = byDocQueue.topList();
// remove the head of the list as long as it does not match
final int currentDoc = listAtCurrentDoc.doc;
while (listAtCurrentDoc.twoPhaseView != null) {
if (listAtCurrentDoc.twoPhaseView.matches()) {
// use this spans for positions at current doc:
listAtCurrentDoc.lastApproxMatchDoc = currentDoc;
break;
}
// do not use this spans for positions at current doc:
listAtCurrentDoc.lastApproxNonMatchDoc = currentDoc;
listAtCurrentDoc = listAtCurrentDoc.next;
if (listAtCurrentDoc == null) {
return false;
}
}
lastDocTwoPhaseMatched = currentDoc;
topPositionSpans = null;
return true;
}
void fillPositionQueue() throws IOException { // called at first nextStartPosition
assert byPositionQueue.size() == 0;
// add all matching Spans at current doc to byPositionQueue
DisiWrapper listAtCurrentDoc = byDocQueue.topList();
while (listAtCurrentDoc != null) {
Spans spansAtDoc = listAtCurrentDoc.spans;
if (lastDocTwoPhaseMatched == listAtCurrentDoc.doc) { // matched by
// DisjunctionDisiApproximation
if (listAtCurrentDoc.twoPhaseView != null) { // matched by approximation
if (listAtCurrentDoc.lastApproxNonMatchDoc == listAtCurrentDoc.doc) { // matches()
// returned
// false
spansAtDoc = null;
} else {
if (listAtCurrentDoc.lastApproxMatchDoc != listAtCurrentDoc.doc) {
if (!listAtCurrentDoc.twoPhaseView.matches()) {
spansAtDoc = null;
}
}
}
}
}
if (spansAtDoc != null) {
assert spansAtDoc.docID() == listAtCurrentDoc.doc;
assert spansAtDoc.startPosition() == -1;
spansAtDoc.nextStartPosition();
assert spansAtDoc.startPosition() != NO_MORE_POSITIONS;
byPositionQueue.add(spansAtDoc);
}
listAtCurrentDoc = listAtCurrentDoc.next;
}
assert byPositionQueue.size() > 0;
}
@Override
public int nextStartPosition() throws IOException {
if (topPositionSpans == null) {
byPositionQueue.clear();
fillPositionQueue(); // fills byPositionQueue at first position
topPositionSpans = byPositionQueue.top();
} else {
topPositionSpans.nextStartPosition();
topPositionSpans = byPositionQueue.updateTop();
}
return topPositionSpans.startPosition();
}
@Override
public int startPosition() {
return topPositionSpans == null ? -1 : topPositionSpans.startPosition();
}
@Override
public int endPosition() {
return topPositionSpans == null ? -1 : topPositionSpans.endPosition();
}
@Override
public int width() {
return topPositionSpans.width();
}
@Override
public void collect(SpanCollector collector) throws IOException {
topPositionSpans.collect(collector);
}
@Override
public String toString() {
return "BLspanOr(" + BLSpanOrQuery.this + ")@" + docID() + ": " + startPosition() + " - " + endPosition();
}
long cost = -1;
@Override
public long cost() {
if (cost == -1) {
cost = 0;
for (Spans spans: subSpans) {
cost += spans.cost();
}
}
return cost;
}
// BL
@Override
public void passHitQueryContextToClauses(HitQueryContext theContext) {
for (Spans spans : subSpans) {
((BLSpans)spans).setHitQueryContext(theContext);
}
}
@Override
public void getCapturedGroups(Span[] capturedGroups) {
if (!childClausesCaptureGroups)
return;
((BLSpans) topPositionSpans).getCapturedGroups(capturedGroups);
}
};
}
}
@Override
public NfaFragment getNfa(ForwardIndexAccessor fiAccessor, int direction) {
List<NfaState> states = new ArrayList<>();
List<NfaState> dangling = new ArrayList<>();
for (SpanQuery cl: getClauses()) {
BLSpanQuery clause = (BLSpanQuery)cl;
NfaFragment frag = clause.getNfa(fiAccessor, direction);
states.add(frag.getStartingState());
dangling.addAll(frag.getDanglingArrows());
}
return new NfaFragment(NfaState.or(states), dangling);
}
@Override
public boolean canMakeNfa() {
for (SpanQuery cl: getClauses()) {
BLSpanQuery clause = (BLSpanQuery)cl;
if (!clause.canMakeNfa())
return false;
}
return true;
}
@Override
public long estimatedNumberOfHits(IndexReader reader) {
// Add the costs of our clauses, since we won't
// be able to skip any hits.
int cost = 0;
for (SpanQuery cl: getClauses()) {
BLSpanQuery clause = (BLSpanQuery)cl;
cost += clause.estimatedNumberOfHits(reader);
}
return cost;
}
}