Repository navigation
Expand file tree
/
Copy pathQuery.cs
More file actions
701 lines (624 loc) · 20.3 KB
/
Copy pathQuery.cs
File metadata and controls
701 lines (624 loc) · 20.3 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
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
using System.Globalization;
using NRedisStack.Search.Literals;
using StackExchange.Redis;
namespace NRedisStack.Search;
/// <summary>
/// Query represents query parameters and filters to load results from the engine
/// </summary>
public sealed class Query : IDialectAwareParam
{
/// <summary>
/// Filter represents a filtering rules in a query
/// </summary>
public abstract class Filter
{
public string Property { get; }
internal abstract void SerializeRedisArgs(List<object> args);
internal Filter(string property)
{
Property = property;
}
}
/// <summary>
/// NumericFilter wraps a range filter on a numeric field. It can be inclusive or exclusive
/// </summary>
public class NumericFilter : Filter
{
private readonly double min, max;
private readonly bool exclusiveMin, exclusiveMax;
public NumericFilter(string property, double min, bool exclusiveMin, double max, bool exclusiveMax) : base(property)
{
this.min = min;
this.max = max;
this.exclusiveMax = exclusiveMax;
this.exclusiveMin = exclusiveMin;
}
public NumericFilter(string property, double min, double max) : this(property, min, false, max, false) { }
internal override void SerializeRedisArgs(List<object> args)
{
static RedisValue FormatNum(double num, bool exclude)
{
if (!exclude || double.IsInfinity(num))
{
return (RedisValue)num; // can use directly
}
// need to add leading bracket
return "(" + num.ToString("G17", NumberFormatInfo.InvariantInfo);
}
args.Add(SearchArgs.FILTER);
args.Add(Property);
args.Add(FormatNum(min, exclusiveMin));
args.Add(FormatNum(max, exclusiveMax));
}
}
/// <summary>
/// GeoFilter encapsulates a radius filter on a geographical indexed fields
/// </summary>
public class GeoFilter : Filter
{
public static readonly string KILOMETERS = "km";
public static readonly string METERS = "m";
public static readonly string FEET = "ft";
public static readonly string MILES = "mi";
private readonly double lon, lat, radius;
private readonly string unit; // TODO: think about implementing this as an enum
public GeoFilter(string property, double lon, double lat, double radius, string unit) : base(property)
{
this.lon = lon;
this.lat = lat;
this.radius = radius;
this.unit = unit;
}
internal override void SerializeRedisArgs(List<object> args)
{
args.Add("GEOFILTER");
args.Add(Property);
args.Add(lon);
args.Add(lat);
args.Add(radius);
args.Add(unit);
}
}
internal readonly struct Paging
{
public int Offset { get; }
public int Count { get; }
public Paging(int offset, int count)
{
Offset = offset;
Count = count;
}
}
public readonly struct HighlightTags
{
public HighlightTags(string open, string close)
{
Open = open;
Close = close;
}
public string Open { get; }
public string Close { get; }
}
/// <summary>
/// The query's filter list. We only support AND operation on all those filters
/// </summary>
internal readonly List<Filter> _filters = [];
/// <summary>
/// The textual part of the query
/// </summary>
public string QueryString { get; }
/// <summary>
/// The sorting parameters
/// </summary>
internal Paging _paging = new(0, 10);
/// <summary>
/// Set the query to verbatim mode, disabling stemming and query expansion
/// </summary>
public bool Verbatim { get; set; }
/// <summary>
/// Set the query not to return the contents of documents, and rather just return the ids
/// </summary>
public bool NoContent { get; set; }
/// <summary>
/// Set the query not to filter for stopwords. In general this should not be used
/// </summary>
public bool NoStopwords { get; set; }
/// <summary>
/// Set the query to return a factored score for each results. This is useful to merge results from multiple queries.
/// </summary>
public bool WithScores { get; set; }
/// <summary>
/// Set the query to return object payloads, if any were given
/// </summary>
public bool WithPayloads { get; set; }
/// <summary>
/// Set the query language, for stemming purposes; see http://redisearch.io for documentation on languages and stemming
/// </summary>
public string? Language { get; set; }
internal string[]? _fields;
internal string[]? _keys;
internal string[]? _returnFields;
internal FieldName[]? _returnFieldsNames;
internal string[]? _highlightFields;
internal string[]? _summarizeFields;
internal HighlightTags? _highlightTags;
internal string? _summarizeSeparator;
internal int _summarizeNumFragments = -1, _summarizeFragmentLen = -1;
/// <summary>
/// Set the query payload to be evaluated by the scoring function
/// </summary>
public string? Payload { get; set; } // TODO: should this be a byte[]?
// TODO: Check if I need to add here WITHSORTKEYS
/// <summary>
/// Set the query parameter to sort by
/// </summary>
public string? SortBy { get; set; }
/// <summary>
/// Set the query parameter to sort by ASC by default
/// </summary>
public bool? SortAscending { get; set; } = null;
// highlight and summarize
internal bool _wantsHighlight = false, _wantsSummarize = false;
/// <summary>
/// Set the query scoring. see https://oss.redislabs.com/redisearch/Scoring.html for documentation
/// </summary>
public string? Scorer { get; set; }
// public bool ExplainScore { get; set; } // TODO: Check if this is needed because Jedis doesn't have it
private readonly Dictionary<string, object> _params = new();
public int? dialect { get; private set; } = null;
private int _slop = -1;
private long _timeout = -1;
private bool _inOrder = false;
private string? _expander = null;
public Query() : this("*") { }
/// <summary>
/// Create a new index
/// </summary>
/// <param name="queryString">The query string to use for this query.</param>
public Query(string queryString)
{
QueryString = queryString;
}
internal void SerializeRedisArgs(List<object> args)
{
args.Add(QueryString);
if (Verbatim)
{
args.Add(SearchArgs.VERBATIM);
}
if (NoContent)
{
args.Add(SearchArgs.NOCONTENT);
}
if (NoStopwords)
{
args.Add(SearchArgs.NOSTOPWORDS);
}
if (WithScores)
{
args.Add(SearchArgs.WITHSCORES);
// if (ExplainScore)
// {
// args.Add("EXPLAINSCORE"); // TODO: Check Why Jedis doesn't have it
// }
}
if (WithPayloads)
{
args.Add(SearchArgs.WITHPAYLOADS);
}
if (Language != null)
{
args.Add(SearchArgs.LANGUAGE);
args.Add(Language);
}
if (Scorer != null)
{
args.Add(SearchArgs.SCORER);
args.Add(Scorer);
}
if (_fields?.Length > 0)
{
args.Add(SearchArgs.INFIELDS);
args.Add(_fields.Length);
args.AddRange(_fields);
}
if (SortBy != null)
{
args.Add(SearchArgs.SORTBY);
args.Add(SortBy);
if (SortAscending != null)
args.Add(((bool)SortAscending ? SearchArgs.ASC : SearchArgs.DESC));
}
if (Payload != null)
{
args.Add(SearchArgs.PAYLOAD);
args.Add(Payload);
}
if (_paging.Offset != 0 || _paging.Count != 10)
{
args.Add(SearchArgs.LIMIT);
args.Add(_paging.Offset);
args.Add(_paging.Count);
}
if (_filters?.Count > 0)
{
foreach (var f in _filters)
{
f.SerializeRedisArgs(args);
}
}
if (_wantsHighlight)
{
args.Add(SearchArgs.HIGHLIGHT);
if (_highlightFields != null)
{
args.Add(SearchArgs.FIELDS);
args.Add(_highlightFields.Length);
foreach (var s in _highlightFields)
{
args.Add(s);
}
}
if (_highlightTags != null)
{
args.Add(SearchArgs.TAGS);
var tags = _highlightTags.GetValueOrDefault();
args.Add(tags.Open);
args.Add(tags.Close);
}
}
if (_wantsSummarize)
{
args.Add(SearchArgs.SUMMARIZE);
if (_summarizeFields != null)
{
args.Add(SearchArgs.FIELDS);
args.Add(_summarizeFields.Length);
foreach (var s in _summarizeFields)
{
args.Add(s);
}
}
if (_summarizeNumFragments != -1)
{
args.Add(SearchArgs.FRAGS);
args.Add(_summarizeNumFragments);
}
if (_summarizeFragmentLen != -1)
{
args.Add(SearchArgs.LEN);
args.Add(_summarizeFragmentLen);
}
if (_summarizeSeparator != null)
{
args.Add(SearchArgs.SEPARATOR);
args.Add(_summarizeSeparator);
}
}
if (_keys != null && _keys.Length > 0)
{
args.Add(SearchArgs.INKEYS);
args.Add(_keys.Length);
foreach (var key in _keys)
{
args.Add(key);
}
}
if (_returnFields?.Length > 0)
{
args.Add(SearchArgs.RETURN);
args.Add(_returnFields.Length);
args.AddRange(_returnFields);
}
else if (_returnFieldsNames?.Length > 0)
{
args.Add(SearchArgs.RETURN);
int returnCountIndex = args.Count;
int returnCount = 0;
foreach (FieldName fn in _returnFieldsNames)
{
returnCount += fn.AddCommandArguments(args);
}
args.Insert(returnCountIndex, returnCount);
}
if (_params != null && _params.Count > 0)
{
args.Add(SearchArgs.PARAMS);
args.Add(_params.Count * 2);
foreach (var entry in _params)
{
args.Add(entry.Key);
args.Add(entry.Value);
}
}
if (dialect >= 1)
{
args.Add(SearchArgs.DIALECT);
args.Add(dialect);
}
if (_slop >= 0)
{
args.Add(SearchArgs.SLOP);
args.Add(_slop);
}
if (_timeout >= 0)
{
args.Add(SearchArgs.TIMEOUT);
args.Add(_timeout);
}
if (_inOrder)
{
args.Add(SearchArgs.INORDER);
}
if (_expander != null)
{
args.Add(SearchArgs.EXPANDER);
args.Add(_expander);
}
}
// TODO: check if DelayedRawable is needed here (Jedis have it)
/// <summary>
/// Limit the results to a certain offset and limit
/// </summary>
/// <param name="offset">the first result to show, zero based indexing</param>
/// <param name="count">how many results we want to show</param>
/// <returns>the query itself, for builder-style syntax</returns>
public Query Limit(int offset, int count)
{
_paging = new(offset, count);
return this;
}
/// <summary>
/// Add a filter to the query's filter list
/// </summary>
/// <param name="f">either a numeric or geo filter object</param>
/// <returns>the query itself</returns>
public Query AddFilter(Filter f)
{
_filters.Add(f);
return this;
}
/// <summary>
/// Set the query payload to be evaluated by the scoring function
/// </summary>
/// <param name="payload">the payload</param>
/// <returns>the query itself</returns>
public Query SetPayload(string payload)
{
Payload = payload;
return this;
}
/// <summary>
/// Set the query to verbatim mode, disabling stemming and query expansion
/// </summary>
/// <returns>the query itself</returns>
public Query SetVerbatim(bool value = true)
{
Verbatim = value;
return this;
}
/// <summary>
/// Set the query not to return the contents of documents, and rather just return the ids
/// </summary>
/// <returns>the query itself</returns>
public Query SetNoContent(bool value = true)
{
NoContent = value;
return this;
}
/// <summary>
/// Set the query not to filter for stopwords. In general this should not be used
/// </summary>
/// <returns>the query itself</returns>
public Query SetNoStopwords(bool value = true)
{
NoStopwords = value;
return this;
}
/// <summary>
/// Set the query to return a factored score for each results. This is useful to merge results from
/// multiple queries.
/// </summary>
/// <returns>the query itself</returns>
public Query SetWithScores(bool value = true)
{
WithScores = value;
return this;
}
/// <summary>
/// Set the query to return object payloads, if any were given
/// </summary>
/// <returns>the query itself</returns>
public Query SetWithPayloads()
{
WithPayloads = true;
return this;
}
/// <summary>
/// Set the query language, for stemming purposes
/// </summary>
/// <param name="language">the language</param>
/// <returns>the query itself</returns>
public Query SetLanguage(string language)
{
Language = language;
return this;
}
/// <summary>
/// Set the query language, for stemming purposes
/// </summary>
/// <param name="scorer"></param>
/// <returns></returns>
public Query SetScorer(string scorer)
{
Scorer = scorer;
return this;
}
// TODO: check if this is needed (Jedis doesn't have it)
// /// <summary>
// /// returns a textual description of how the scores were calculated.
// /// Using this options requires the WITHSCORES option.
// /// </summary>
// /// <param name="explainScore"></param>
// /// <returns></returns>
// public Query SetExplainScore(bool explainScore = true)
// {
// ExplainScore = explainScore;
// return this;
// }
/// <summary>
/// Limit the query to results that are limited to a specific set of fields
/// </summary>
/// <param name="fields">a list of TEXT fields in the schemas</param>
/// <returns>the query object itself</returns>
public Query LimitFields(params string[] fields)
{
_fields = fields;
return this;
}
/// <summary>
/// Limit the query to results that are limited to a specific set of keys
/// </summary>
/// <param name="keys">a list of the TEXT fields in the schemas</param>
/// <returns>the query object itself</returns>
public Query LimitKeys(params string[] keys)
{
_keys = keys;
return this;
}
/// <summary>
/// Result's projection - the fields to return by the query
/// </summary>
/// <param name="fields">fields a list of TEXT fields in the schemas</param>
/// <returns>the query object itself</returns>
public Query ReturnFields(params string[] fields)
{
_returnFields = fields;
_returnFieldsNames = null;
return this;
}
/// <summary>
/// Result's projection - the fields to return by the query
/// </summary>
/// <param name="fields">field a list of TEXT fields in the schemas</param>
/// <returns>the query object itself</returns>
public Query ReturnFields(params FieldName[] fields)
{
_returnFields = null;
_returnFieldsNames = fields;
return this;
}
public Query HighlightFields(HighlightTags tags, params string[] fields) => HighlightFieldsImpl(tags, fields);
public Query HighlightFields(params string[] fields) => HighlightFieldsImpl(null, fields);
private Query HighlightFieldsImpl(HighlightTags? tags, string[] fields)
{
if (fields == null || fields.Length > 0)
{
_highlightFields = fields;
}
_highlightTags = tags;
_wantsHighlight = true;
return this;
}
public Query SummarizeFields(int contextLen, int fragmentCount, string? separator, params string[] fields)
{
if (fields == null || fields.Length > 0)
{
_summarizeFields = fields;
}
_summarizeFragmentLen = contextLen;
_summarizeNumFragments = fragmentCount;
_summarizeSeparator = separator;
_wantsSummarize = true;
return this;
}
public Query SummarizeFields(params string[] fields) => SummarizeFields(-1, -1, null, fields);
/// <summary>
/// Set the query to be sorted by a sortable field defined in the schema
/// </summary>
/// <param name="field">the sorting field's name</param>
/// <param name="ascending">if set to true, the sorting order is ascending, else descending</param>
/// <returns>the query object itself</returns>
public Query SetSortBy(string field, bool? ascending = null)
{
SortBy = field;
SortAscending = ascending;
return this;
}
/// <summary>
/// Parameters can be referenced in the query string by a $ , followed by the parameter name,
/// e.g., $user , and each such reference in the search query to a parameter name is substituted
/// by the corresponding parameter value.
/// Note: when calling this function with an externally supplied parameter, value should be a string.
/// </summary>
/// <param name="name"></param>
/// <param name="value"> can be String, long or float</param>
/// <returns>The query object itself</returns>
public Query AddParam(string name, object value)
{
_params.Add(name, value);
return this;
}
public Query Params(Dictionary<string, object> nameValue)
{
foreach (var entry in nameValue)
{
_params.Add(entry.Key, entry.Value);
}
return this;
}
/// <summary>
/// Set the dialect version to execute the query accordingly
/// </summary>
/// <param name="dialect"></param>
/// <returns>the query object itself</returns>
public Query Dialect(int dialect)
{
this.dialect = dialect;
return this;
}
/// <summary>
/// Set the slop to execute the query accordingly
/// </summary>
/// <param name="slop"></param>
/// <returns>the query object itself</returns>
public Query Slop(int slop)
{
_slop = slop;
return this;
}
/// <summary>
/// Set the timeout to execute the query accordingly
/// </summary>
/// <param name="timeout"></param>
/// <returns>the query object itself</returns>
public Query Timeout(long timeout)
{
_timeout = timeout;
return this;
}
/// <summary>
/// Set the query terms appear in the same order in the document as in the query, regardless of the offsets between them
/// </summary>
/// <returns>the query object</returns>
public Query SetInOrder()
{
_inOrder = true;
return this;
}
/// <summary>
/// Set the query to use a custom query expander instead of the stemmer
/// </summary>
/// <param name="field">the expander field's name</param>
/// <returns>the query object itself</returns>
public Query SetExpander(string field)
{
_expander = field;
return this;
}
int? IDialectAwareParam.Dialect
{
get { return dialect; }
set { dialect = value; }
}
}