forked from apache/lucenenet
/
DrillDownQuery.cs
409 lines (366 loc) · 14.9 KB
/
DrillDownQuery.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
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
// Lucene version compatibility level 4.8.1
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Facet
{
/*
* 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.
*/
using BooleanClause = Lucene.Net.Search.BooleanClause;
using BooleanQuery = Lucene.Net.Search.BooleanQuery;
using ConstantScoreQuery = Lucene.Net.Search.ConstantScoreQuery;
using Filter = Lucene.Net.Search.Filter;
using FilteredQuery = Lucene.Net.Search.FilteredQuery;
using IndexReader = Lucene.Net.Index.IndexReader;
using MatchAllDocsQuery = Lucene.Net.Search.MatchAllDocsQuery;
using Occur = Lucene.Net.Search.Occur;
using Query = Lucene.Net.Search.Query;
using Term = Lucene.Net.Index.Term;
using TermQuery = Lucene.Net.Search.TermQuery;
/// <summary>
/// A <see cref="Query"/> for drill-down over facet categories. You
/// should call <see cref="Add(string, string[])"/> for every group of categories you
/// want to drill-down over.
/// <para/>
/// <b>NOTE:</b> if you choose to create your own <see cref="Query"/> by calling
/// <see cref="Term"/>, it is recommended to wrap it with <see cref="ConstantScoreQuery"/>
/// and set the <see cref="Query.Boost">boost</see> to <c>0.0f</c>,
/// so that it does not affect the scores of the documents.
/// <para/>
/// Collection initializer note: To create and populate a <see cref="DrillDownQuery"/>
/// in a single statement, you can use the following example as a guide:
///
/// <code>
/// var drillDownQuery = new DrillDownQuery(config)
/// {
/// { "Publish Date", "2019" },
/// { "Publish Date", "2020" },
/// { "Publish Date", "2021" },
/// { "timestamp", NumericRangeQuery.NewInt64Range("timestamp", range.Min, range.Max, range.MinInclusive, range.MaxInclusive) },
/// { "filter", GetFilter() }
/// };
/// </code>
/// <para/>
/// @lucene.experimental
/// </summary>
public sealed class DrillDownQuery : Query, IEnumerable<BooleanClause>, IEnumerable<KeyValuePair<string, int>> // LUCENENET specific - Added collection initializer to make populating easier
{
/// <summary>
/// Creates a drill-down term.
/// </summary>
public static Term Term(string field, string dim, params string[] path)
{
return new Term(field, FacetsConfig.PathToString(dim, path));
}
private readonly FacetsConfig config;
private readonly BooleanQuery query;
private readonly IDictionary<string, int> drillDownDims = new JCG.LinkedDictionary<string, int>();
/// <summary>
/// Used by <see cref="Clone"/>
/// </summary>
internal DrillDownQuery(FacetsConfig config, BooleanQuery query, IDictionary<string, int> drillDownDims)
{
this.query = (BooleanQuery)query.Clone();
this.drillDownDims.PutAll(drillDownDims);
this.config = config;
}
/// <summary>
/// Used by <see cref="DrillSideways"/>
/// </summary>
internal DrillDownQuery(FacetsConfig config, Filter filter, DrillDownQuery other)
{
query = new BooleanQuery(true); // disable coord
BooleanClause[] clauses = other.query.GetClauses();
if (clauses.Length == other.drillDownDims.Count)
{
throw new ArgumentException("cannot apply filter unless baseQuery isn't null; pass ConstantScoreQuery instead");
}
if (Debugging.AssertsEnabled) Debugging.Assert(clauses.Length == 1 + other.drillDownDims.Count, "{0} vs {1}", clauses.Length, (1 + other.drillDownDims.Count));
drillDownDims.PutAll(other.drillDownDims);
query.Add(new FilteredQuery(clauses[0].Query, filter), Occur.MUST);
for (int i = 1; i < clauses.Length; i++)
{
query.Add(clauses[i].Query, Occur.MUST);
}
this.config = config;
}
/// <summary>
/// Used by <see cref="DrillSideways"/>
/// </summary>
internal DrillDownQuery(FacetsConfig config, Query baseQuery, IList<Query> clauses, IDictionary<string, int> drillDownDims)
{
query = new BooleanQuery(true);
if (baseQuery != null)
{
query.Add(baseQuery, Occur.MUST);
}
foreach (Query clause in clauses)
{
query.Add(clause, Occur.MUST);
}
this.drillDownDims.PutAll(drillDownDims);
this.config = config;
}
/// <summary>
/// Creates a new <see cref="DrillDownQuery"/> without a base query,
/// to perform a pure browsing query (equivalent to using
/// <see cref="MatchAllDocsQuery"/> as base).
/// </summary>
public DrillDownQuery(FacetsConfig config)
: this(config, null)
{
}
/// <summary>
/// Creates a new <see cref="DrillDownQuery"/> over the given base query. Can be
/// <c>null</c>, in which case the result <see cref="Query"/> from
/// <see cref="Rewrite(IndexReader)"/> will be a pure browsing query, filtering on
/// the added categories only.
/// </summary>
public DrillDownQuery(FacetsConfig config, Query baseQuery)
{
query = new BooleanQuery(true); // disable coord
if (baseQuery != null)
{
query.Add(baseQuery, Occur.MUST);
}
this.config = config;
}
/// <summary>
/// Merges (ORs) a new path into an existing AND'd
/// clause.
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
private void Merge(string dim, string[] path)
{
int index = 0;
if (drillDownDims.TryGetValue(dim, out int idx))
{
index = idx;
}
if (query.GetClauses().Length == drillDownDims.Count + 1)
{
index++;
}
ConstantScoreQuery q = (ConstantScoreQuery)query.GetClauses()[index].Query;
if ((q.Query is BooleanQuery) == false)
{
// App called .add(dim, customQuery) and then tried to
// merge a facet label in:
throw RuntimeException.Create("cannot merge with custom Query");
}
string indexedField = config.GetDimConfig(dim).IndexFieldName;
BooleanQuery bq = (BooleanQuery)q.Query;
bq.Add(new TermQuery(Term(indexedField, dim, path)), Occur.SHOULD);
}
/// <summary>
/// Adds one dimension of drill downs; if you pass the same
/// dimension more than once it is OR'd with the previous
/// cofnstraints on that dimension, and all dimensions are
/// AND'd against each other and the base query.
/// </summary>
public void Add(string dim, params string[] path)
{
if (drillDownDims.ContainsKey(dim))
{
Merge(dim, path);
return;
}
string indexedField = config.GetDimConfig(dim).IndexFieldName;
BooleanQuery bq = new BooleanQuery(true)
{
{ new TermQuery(Term(indexedField, dim, path)), Occur.SHOULD }
}; // disable coord
Add(dim, bq);
}
/// <summary>
/// Expert: add a custom drill-down subQuery. Use this
/// when you have a separate way to drill-down on the
/// dimension than the indexed facet ordinals.
/// </summary>
public void Add(string dim, Query subQuery)
{
if (drillDownDims.ContainsKey(dim))
{
throw new ArgumentException("dimension \"" + dim + "\" already has a drill-down");
}
// TODO: we should use FilteredQuery?
// So scores of the drill-down query don't have an
// effect:
ConstantScoreQuery drillDownQuery = new ConstantScoreQuery(subQuery);
drillDownQuery.Boost = 0.0f;
query.Add(drillDownQuery, Occur.MUST);
drillDownDims[dim] = drillDownDims.Count;
}
/// <summary>
/// Expert: add a custom drill-down Filter, e.g. when
/// drilling down after range faceting.
/// </summary>
public void Add(string dim, Filter subFilter)
{
if (drillDownDims.ContainsKey(dim))
{
throw new ArgumentException("dimension \"" + dim + "\" already has a drill-down");
}
// TODO: we should use FilteredQuery?
// So scores of the drill-down query don't have an
// effect:
ConstantScoreQuery drillDownQuery = new ConstantScoreQuery(subFilter);
drillDownQuery.Boost = 0.0f;
query.Add(drillDownQuery, Occur.MUST);
drillDownDims[dim] = drillDownDims.Count;
}
internal static Filter GetFilter(Query query)
{
if (query is ConstantScoreQuery scoreQuery)
{
ConstantScoreQuery csq = scoreQuery;
Filter filter = csq.Filter;
if (filter != null)
{
return filter;
}
else
{
return GetFilter(csq.Query);
}
}
else
{
return null;
}
}
public override object Clone()
{
return new DrillDownQuery(config, query, drillDownDims);
}
public override int GetHashCode()
{
const int prime = 31;
int result = base.GetHashCode();
return prime * result + query.GetHashCode();
}
public override bool Equals(object obj)
{
if (!(obj is DrillDownQuery))
{
return false;
}
DrillDownQuery other = (DrillDownQuery)obj;
return query.Equals(other.query) && base.Equals(other);
}
public override Query Rewrite(IndexReader r)
{
if (query.Clauses.Count == 0)
{
return new MatchAllDocsQuery();
}
IList<Filter> filters = new JCG.List<Filter>();
IList<Query> queries = new JCG.List<Query>();
IList<BooleanClause> clauses = query.Clauses;
Query baseQuery;
int startIndex;
if (drillDownDims.Count == query.Clauses.Count)
{
baseQuery = new MatchAllDocsQuery();
startIndex = 0;
}
else
{
baseQuery = clauses[0].Query;
startIndex = 1;
}
for (int i = startIndex; i < clauses.Count; i++)
{
BooleanClause clause = clauses[i];
Query queryClause = clause.Query;
Filter filter = GetFilter(queryClause);
if (filter != null)
{
filters.Add(filter);
}
else
{
queries.Add(queryClause);
}
}
if (filters.Count == 0)
{
return query;
}
else
{
// Wrap all filters using FilteredQuery
// TODO: this is hackish; we need to do it because
// BooleanQuery can't be trusted to handle the
// "expensive filter" case. Really, each Filter should
// know its cost and we should take that more
// carefully into account when picking the right
// strategy/optimization:
Query wrapped;
if (queries.Count == 0)
{
wrapped = baseQuery;
}
else
{
// disable coord
BooleanQuery wrappedBQ = new BooleanQuery(true);
if ((baseQuery is MatchAllDocsQuery) == false)
{
wrappedBQ.Add(baseQuery, Occur.MUST);
}
foreach (Query q in queries)
{
wrappedBQ.Add(q, Occur.MUST);
}
wrapped = wrappedBQ;
}
foreach (Filter filter in filters)
{
wrapped = new FilteredQuery(wrapped, filter, FilteredQuery.QUERY_FIRST_FILTER_STRATEGY);
}
return wrapped;
}
}
public override string ToString(string field)
{
return query.ToString(field);
}
internal BooleanQuery BooleanQuery => query;
internal IDictionary<string, int> Dims => drillDownDims;
// LUCENENET specific - added for collection initializer to work with Add() methods.
IEnumerator IEnumerable.GetEnumerator() => query.GetEnumerator();
/// <summary>
/// Returns an iterator on the clauses in this query. It implements the <see cref="T:IEnumerable{BooleanClause}"/> interface to
/// make it possible to do:
/// <code>foreach (BooleanClause clause in drillDownQuery) {}</code>
/// </summary>
public IEnumerator<BooleanClause> GetEnumerator() => query.GetEnumerator();
/// <summary>
/// Returns an iterator on the dims in this query. It implements the <see cref="T:IEnumerable{KeyValuePair{string, int}}"/> interface to
/// make it possible to do:
/// <code>
/// foreach (KeyValuePair<string, int> dimensionAndCount in (IEnumerable<KeyValuePair<string, int>>)drillDownQuery) {}
/// </code>
/// </summary>
IEnumerator<KeyValuePair<string, int>> IEnumerable<KeyValuePair<string, int>>.GetEnumerator() => drillDownDims.GetEnumerator();
}
}