forked from ravendb/ravendb
/
AbstractDocumentQuery.cs
1462 lines (1302 loc) · 45.1 KB
/
AbstractDocumentQuery.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
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-----------------------------------------------------------------------
// <copyright file="DocumentQuery.cs" company="Hibernating Rhinos LTD">
// Copyright (c) Hibernating Rhinos LTD. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
#if !NET_3_5
using Raven.Client.Connection.Async;
using System.Threading.Tasks;
using Raven.Client.Document.Batches;
#endif
using Raven.Abstractions;
using Raven.Abstractions.Data;
using Raven.Client.Connection;
using Raven.Client.Document.SessionOperations;
using Raven.Client.Exceptions;
using Raven.Client.Linq;
using Raven.Client.Listeners;
using Raven.Json.Linq;
using Newtonsoft.Json.Linq;
using Raven.Abstractions.Extensions;
using Raven.Abstractions.Indexing;
using Raven.Abstractions.Linq;
namespace Raven.Client.Document
{
/// <summary>
/// A query against a Raven index
/// </summary>
public abstract class AbstractDocumentQuery<T, TSelf> : IDocumentQueryCustomization, IRavenQueryInspector, IAbstractDocumentQuery<T>
{
/// <summary>
/// Whatever to negate the next operation
/// </summary>
protected bool negate;
#if !SILVERLIGHT
/// <summary>
/// The database commands to use
/// </summary>
protected readonly IDatabaseCommands theDatabaseCommands;
#endif
#if !NET_3_5
/// <summary>
/// Async database commands to use
/// </summary>
protected readonly IAsyncDatabaseCommands theAsyncDatabaseCommands;
#endif
/// <summary>
/// The index to query
/// </summary>
protected readonly string indexName;
private int currentClauseDepth;
private KeyValuePair<string, string> lastEquality;
/// <summary>
/// The list of fields to project directly from the index
/// </summary>
protected readonly string[] projectionFields;
/// <summary>
/// The query listeners for this query
/// </summary>
protected readonly IDocumentQueryListener[] queryListeners;
/// <summary>
/// The session for this query
/// </summary>
protected readonly InMemoryDocumentSessionOperations theSession;
/// <summary>
/// The cutoff date to use for detecting staleness in the index
/// </summary>
protected DateTime? cutoff;
/// <summary>
/// The fields to order the results by
/// </summary>
protected string[] orderByFields = new string[0];
/// <summary>
/// The types to sort the fields by (NULL if not specified)
/// </summary>
protected HashSet<KeyValuePair<string, Type>> sortByHints = new HashSet<KeyValuePair<string, Type>>();
/// <summary>
/// The page size to use when querying the index
/// </summary>
protected int? pageSize;
private QueryOperation queryOperation;
/// <summary>
/// The query to use
/// </summary>
protected StringBuilder theQueryText = new StringBuilder();
/// <summary>
/// which record to start reading from
/// </summary>
protected int start;
/// <summary>
/// Timeout for this query
/// </summary>
protected TimeSpan timeout;
/// <summary>
/// Should we wait for non stale results
/// </summary>
protected bool theWaitForNonStaleResults;
/// <summary>
/// The paths to include when loading the query
/// </summary>
protected HashSet<string> includes = new HashSet<string>();
/// <summary>
/// What aggregated operation to execute
/// </summary>
protected AggregationOperation aggregationOp;
/// <summary>
/// Fields to group on
/// </summary>
protected string[] groupByFields;
/// <summary>
/// Holds the query stats
/// </summary>
protected RavenQueryStatistics queryStats = new RavenQueryStatistics();
/// <summary>
/// Get the name of the index being queried
/// </summary>
public string IndexQueried
{
get { return indexName; }
}
#if !SILVERLIGHT
/// <summary>
/// Grant access to the database commands
/// </summary>
public IDatabaseCommands DatabaseCommands
{
get { return theDatabaseCommands; }
}
#endif
#if !NET_3_5
/// <summary>
/// Grant access to the async database commands
/// </summary>
public IAsyncDatabaseCommands AsyncDatabaseCommands
{
get { return theAsyncDatabaseCommands; }
}
#endif
/// <summary>
/// Gets the document convention from the query session
/// </summary>
public DocumentConvention DocumentConvention
{
get { return theSession.Conventions; }
}
#if !SILVERLIGHT
/// <summary>
/// Gets the session associated with this document query
/// </summary>
public IDocumentSession Session
{
get { return (IDocumentSession)theSession; }
}
#endif
/// <summary>
/// Gets the query text built so far
/// </summary>
protected StringBuilder QueryText
{
get { return theQueryText; }
}
private Action<QueryResult> afterQueryExecuted;
private Guid? cutoffEtag;
private TimeSpan DefaultTimeout
{
get
{
if (Debugger.IsAttached) // increase timeout if we are debugging
return TimeSpan.FromMinutes(15);
return TimeSpan.FromSeconds(15);
}
}
#if !SILVERLIGHT && !NET_3_5
/// <summary>
/// Initializes a new instance of the <see cref = "DocumentQuery<T>" /> class.
/// </summary>
protected AbstractDocumentQuery(InMemoryDocumentSessionOperations theSession,
IDatabaseCommands databaseCommands,
string indexName,
string[] projectionFields,
IDocumentQueryListener[] queryListeners)
: this(theSession, databaseCommands, null, indexName, projectionFields, queryListeners)
{
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref="DocumentQuery<T>"/> class.
/// </summary>
/// <param name="databaseCommands">The database commands.</param>
#if !NET_3_5
/// <param name="asyncDatabaseCommands">The async database commands</param>
#endif
/// <param name = "indexName">Name of the index.</param>
/// <param name = "projectionFields">The projection fields.</param>
/// <param name = "theSession">The session.</param>
public AbstractDocumentQuery(InMemoryDocumentSessionOperations theSession,
#if !SILVERLIGHT
IDatabaseCommands databaseCommands,
#endif
#if !NET_3_5
IAsyncDatabaseCommands asyncDatabaseCommands,
#endif
string indexName,
string[] projectionFields,
IDocumentQueryListener[] queryListeners)
{
#if !SILVERLIGHT
this.theDatabaseCommands = databaseCommands;
#endif
this.projectionFields = projectionFields;
this.queryListeners = queryListeners;
this.indexName = indexName;
this.theSession = theSession;
#if !NET_3_5
this.theAsyncDatabaseCommands = asyncDatabaseCommands;
#endif
this.AfterQueryExecuted(queryStats.UpdateQueryStats);
if (this.theSession != null && // tests may decide to send null here
this.theSession.DocumentStore.Conventions.DefaultQueryingConsistency == ConsistencyOptions.QueryYourWrites)
WaitForNonStaleResultsAsOfLastWrite();
}
/// <summary>
/// Initializes a new instance of the <see cref = "IDocumentQuery<T>" /> class.
/// </summary>
/// <param name = "other">The other.</param>
protected AbstractDocumentQuery(AbstractDocumentQuery<T, TSelf> other)
{
#if !SILVERLIGHT
theDatabaseCommands = other.theDatabaseCommands;
#endif
#if !NET_3_5
theAsyncDatabaseCommands = other.theAsyncDatabaseCommands;
#endif
indexName = other.indexName;
projectionFields = other.projectionFields;
theSession = other.theSession;
cutoff = other.cutoff;
orderByFields = other.orderByFields;
sortByHints = other.sortByHints;
pageSize = other.pageSize;
theQueryText = other.theQueryText;
start = other.start;
timeout = other.timeout;
theWaitForNonStaleResults = other.theWaitForNonStaleResults;
includes = other.includes;
queryListeners = other.queryListeners;
queryStats = other.queryStats;
AfterQueryExecuted(queryStats.UpdateQueryStats);
}
#region TSelf Members
/// <summary>
/// Includes the specified path in the query, loading the document specified in that path
/// </summary>
/// <param name = "path">The path.</param>
IDocumentQueryCustomization IDocumentQueryCustomization.Include(string path)
{
Include(path);
return this;
}
/// <summary>
/// EXPERT ONLY: Instructs the query to wait for non stale results for the specified wait timeout.
/// This shouldn't be used outside of unit tests unless you are well aware of the implications
/// </summary>
/// <param name = "waitTimeout">The wait timeout.</param>
IDocumentQueryCustomization IDocumentQueryCustomization.WaitForNonStaleResults(TimeSpan waitTimeout)
{
WaitForNonStaleResults(waitTimeout);
return this;
}
/// <summary>
/// Selects the specified fields directly from the index
/// </summary>
/// <typeparam name="TProjection">The type of the projection.</typeparam>
/// <param name="fields">The fields.</param>
IDocumentQueryCustomization IDocumentQueryCustomization.CreateQueryForSelectedFields<TProjection>(params string[] fields)
{
return CreateQueryForSelectedFields<TProjection>(fields);
}
/// <summary>
/// Selects the specified fields directly from the index
/// </summary>
protected abstract IDocumentQueryCustomization CreateQueryForSelectedFields<TProjection>(string[] fields);
/// <summary>
/// Filter matches to be inside the specified radius
/// </summary>
/// <param name = "radius">The radius.</param>
/// <param name = "latitude">The latitude.</param>
/// <param name = "longitude">The longitude.</param>
IDocumentQueryCustomization IDocumentQueryCustomization.WithinRadiusOf(double radius, double latitude,
double longitude)
{
GenerateQueryWithinRadiusOf(radius, latitude, longitude);
return this;
}
/// <summary>
/// Filter matches to be inside the specified radius
/// </summary>
/// <param name = "radius">The radius.</param>
/// <param name = "latitude">The latitude.</param>
/// <param name = "longitude">The longitude.</param>
protected abstract object GenerateQueryWithinRadiusOf(double radius, double latitude, double longitude);
/// <summary>
/// EXPERT ONLY: Instructs the query to wait for non stale results.
/// This shouldn't be used outside of unit tests unless you are well aware of the implications
/// </summary>
IDocumentQueryCustomization IDocumentQueryCustomization.WaitForNonStaleResults()
{
WaitForNonStaleResults();
return this;
}
/// <summary>
/// Includes the specified path in the query, loading the document specified in that path
/// </summary>
/// <param name = "path">The path.</param>
IDocumentQueryCustomization IDocumentQueryCustomization.Include<TResult>(Expression<Func<TResult, object>> path)
{
Include(path.ToPropertyPath());
return this;
}
/// <summary>
/// Instruct the query to wait for non stale result for the specified wait timeout.
/// </summary>
/// <param name = "waitTimeout">The wait timeout.</param>
/// <returns></returns>
public void WaitForNonStaleResults(TimeSpan waitTimeout)
{
theWaitForNonStaleResults = true;
timeout = waitTimeout;
}
private void InitializeQueryOperation(Action<string, string> setOperationHeaders)
{
foreach (var documentQueryListener in queryListeners)
{
documentQueryListener.BeforeQueryExecuted(this);
}
var query = theQueryText.ToString();
var indexQuery = GenerateIndexQuery(query);
queryOperation = new QueryOperation(theSession,
indexName,
indexQuery,
projectionFields,
sortByHints,
theWaitForNonStaleResults,
setOperationHeaders,
timeout);
}
#if !SILVERLIGHT
/// <summary>
/// Gets the query result
/// Execute the query the first time that this is called.
/// </summary>
/// <value>The query result.</value>
public QueryResult QueryResult
{
get
{
InitSync();
return queryOperation.CurrentQueryResults.CreateSnapshot();
}
}
private void InitSync()
{
if (queryOperation != null)
return;
theSession.IncrementRequestCount();
foreach (var key in DatabaseCommands.OperationsHeaders.AllKeys.Where(key => key.StartsWith("SortHint")).ToArray())
{
DatabaseCommands.OperationsHeaders.Remove(key);
}
InitializeQueryOperation(DatabaseCommands.OperationsHeaders.Set);
ExecuteActualQuery();
}
private void ExecuteActualQuery()
{
while (true)
{
using (queryOperation.EnterQueryContext())
{
queryOperation.LogQuery();
var result = theDatabaseCommands.Query(indexName, queryOperation.IndexQuery, includes.ToArray());
if (queryOperation.IsAcceptable(result) == false)
{
Thread.Sleep(100);
continue;
}
break;
}
}
InvokeAfterQueryExecuted(queryOperation.CurrentQueryResults);
}
#endif
#if !NET_3_5 && !SILVERLIGHT
/// <summary>
/// Register the query as a lazy query in the session and return a lazy
/// instance that will evaluate the query only when needed
/// </summary>
public Lazy<IEnumerable<T>> Lazily()
{
return Lazily(null);
}
/// <summary>
/// Register the query as a lazy query in the session and return a lazy
/// instance that will evaluate the query only when needed
/// </summary>
public Lazy<IEnumerable<T>> Lazily(Action<IEnumerable<T>> onEval)
{
if (queryOperation == null)
{
foreach (var key in DatabaseCommands.OperationsHeaders.AllKeys.Where(key => key.StartsWith("SortHint")).ToArray())
{
DatabaseCommands.OperationsHeaders.Remove(key);
}
InitializeQueryOperation(DatabaseCommands.OperationsHeaders.Set);
}
var lazyQueryOperation = new LazyQueryOperation<T>(queryOperation, afterQueryExecuted);
return ((DocumentSession)theSession).AddLazyOperation(lazyQueryOperation, onEval);
}
#endif
#if !NET_3_5
/// <summary>
/// Gets the query result
/// Execute the query the first time that this is called.
/// </summary>
/// <value>The query result.</value>
public Task<QueryResult> QueryResultAsync
{
get
{
return InitAsync()
.ContinueWith(x => x.Result.CurrentQueryResults.CreateSnapshot());
}
}
private Task<QueryOperation> InitAsync()
{
if (queryOperation != null)
return TaskEx.Run(() => queryOperation);
foreach (var key in AsyncDatabaseCommands.OperationsHeaders.Keys.Where(key => key.StartsWith("SortHint")).ToArray())
{
AsyncDatabaseCommands.OperationsHeaders.Remove(key);
}
InitializeQueryOperation((key, val) => AsyncDatabaseCommands.OperationsHeaders[key] = val);
theSession.IncrementRequestCount();
return ExecuteActualQueryAsync();
}
#endif
/// <summary>
/// Gets the fields for projection
/// </summary>
/// <returns></returns>
public IEnumerable<string> GetProjectionFields()
{
return projectionFields ?? Enumerable.Empty<string>();
}
/// <summary>
/// Adds an ordering for a specific field to the query
/// </summary>
/// <param name = "fieldName">Name of the field.</param>
/// <param name = "descending">if set to <c>true</c> [descending].</param>
public void AddOrder(string fieldName, bool descending)
{
AddOrder(fieldName, descending, null);
}
/// <summary>
/// Adds an ordering for a specific field to the query and specifies the type of field for sorting purposes
/// </summary>
/// <param name = "fieldName">Name of the field.</param>
/// <param name = "descending">if set to <c>true</c> [descending].</param>
/// <param name = "fieldType">the type of the field to be sorted.</param>
public void AddOrder(string fieldName, bool descending, Type fieldType)
{
fieldName = EnsureValidFieldName(new WhereParams
{
FieldName = fieldName
});
fieldName = descending ? "-" + fieldName : fieldName;
orderByFields = orderByFields.Concat(new[] { fieldName }).ToArray();
sortByHints.Add(new KeyValuePair<string, Type>(fieldName, fieldType));
}
#if !SILVERLIGHT
/// <summary>
/// Gets the enumerator.
/// </summary>
public IEnumerator<T> GetEnumerator()
{
InitSync();
while (true)
{
try
{
return queryOperation.Complete<T>().GetEnumerator();
}
catch (Exception e)
{
if (queryOperation.ShouldQueryAgain(e) == false)
throw;
ExecuteActualQuery(); // retry the query, not that we explicity not incrementing the session request cuont here
}
}
}
#endif
#if !NET_3_5
private Task<Tuple<QueryOperation,IList<T>>> ProcessEnumerator(Task<QueryOperation> task)
{
var currentQueryOperation = task.Result;
try
{
var list = currentQueryOperation.Complete<T>();
return TaskEx.Run(() => Tuple.Create(currentQueryOperation, list));
}
catch (Exception e)
{
if (queryOperation.ShouldQueryAgain(e) == false)
throw;
return ExecuteActualQueryAsync()
.ContinueWith(t => ProcessEnumerator(t))
.Unwrap();
}
}
#endif
/// <summary>
/// Includes the specified path in the query, loading the document specified in that path
/// </summary>
/// <param name = "path">The path.</param>
public void Include(string path)
{
includes.Add(path);
}
/// <summary>
/// This function exists solely to forbid in memory where clause on IDocumentQuery, because
/// that is nearly always a mistake.
/// </summary>
[Obsolete(
@"
You cannot issue an in memory filter - such as Where(x=>x.Name == ""Ayende"") - on IDocumentQuery.
This is likely a bug, because this will execute the filter in memory, rather than in RavenDB.
Consider using session.Query<T>() instead of session.LuceneQuery<T>. The session.Query<T>() method fully supports Linq queries, while session.LuceneQuery<T>() is intended for lower level API access.
If you really want to do in memory filtering on the data returned from the query, you can use: session.LuceneQuery<T>().ToList().Where(x=>x.Name == ""Ayende"")
"
, true)]
public IEnumerable<T> Where(Func<T, bool> predicate)
{
throw new NotSupportedException();
}
/// <summary>
/// This function exists solely to forbid in memory where clause on IDocumentQuery, because
/// that is nearly always a mistake.
/// </summary>
[Obsolete(
@"
You cannot issue an in memory filter - such as Count(x=>x.Name == ""Ayende"") - on IDocumentQuery.
This is likely a bug, because this will execute the filter in memory, rather than in RavenDB.
Consider using session.Query<T>() instead of session.LuceneQuery<T>. The session.Query<T>() method fully supports Linq queries, while session.LuceneQuery<T>() is intended for lower level API access.
If you really want to do in memory filtering on the data returned from the query, you can use: session.LuceneQuery<T>().ToList().Count(x=>x.Name == ""Ayende"")
"
, true)]
public int Count(Func<T, bool> predicate)
{
throw new NotSupportedException();
}
/// <summary>
/// This function exists solely to forbid in memory where clause on IDocumentQuery, because
/// that is nearly always a mistake.
/// </summary>
[Obsolete(
@"
You cannot issue an in memory filter - such as Count() - on IDocumentQuery.
This is likely a bug, because this will execute the filter in memory, rather than in RavenDB.
Consider using session.Query<T>() instead of session.LuceneQuery<T>. The session.Query<T>() method fully supports Linq queries, while session.LuceneQuery<T>() is intended for lower level API access.
If you really want to do in memory filtering on the data returned from the query, you can use: session.LuceneQuery<T>().ToList().Count()
"
, true)]
public int Count()
{
throw new NotSupportedException();
}
/// <summary>
/// Includes the specified path in the query, loading the document specified in that path
/// </summary>
/// <param name = "path">The path.</param>
public void Include(Expression<Func<T, object>> path)
{
Include(path.ToPropertyPath());
}
/// <summary>
/// Takes the specified count.
/// </summary>
/// <param name = "count">The count.</param>
/// <returns></returns>
public void Take(int count)
{
pageSize = count;
}
/// <summary>
/// Skips the specified count.
/// </summary>
/// <param name = "count">The count.</param>
/// <returns></returns>
public void Skip(int count)
{
start = count;
}
/// <summary>
/// Filter the results from the index using the specified where clause.
/// </summary>
/// <param name = "whereClause">The where clause.</param>
public void Where(string whereClause)
{
if (theQueryText.Length > 0)
{
theQueryText.Append(" ");
}
theQueryText.Append(whereClause);
}
/// <summary>
/// Matches exact value
/// </summary>
/// <remarks>
/// Defaults to NotAnalyzed
/// </remarks>
public void WhereEquals(string fieldName, object value)
{
WhereEquals(new WhereParams
{
FieldName = fieldName,
Value = value
});
}
/// <summary>
/// Matches exact value
/// </summary>
/// <remarks>
/// Defaults to allow wildcards only if analyzed
/// </remarks>
public void WhereEquals(string fieldName, object value, bool isAnalyzed)
{
WhereEquals(new WhereParams
{
AllowWildcards = isAnalyzed,
IsAnalyzed = isAnalyzed,
FieldName = fieldName,
Value = value
});
}
/// <summary>
/// Simplified method for opening a new clause within the query
/// </summary>
/// <returns></returns>
public void OpenSubclause()
{
currentClauseDepth++;
if (theQueryText.Length > 0 && theQueryText[theQueryText.Length - 1] != '(')
{
theQueryText.Append(" ");
}
NegateIfNeeded();
theQueryText.Append("(");
}
///<summary>
/// Instruct the index to group by the specified fields using the specified aggregation operation
///</summary>
///<remarks>
/// This is only valid on dynamic indexes queries
///</remarks>
public void GroupBy(AggregationOperation aggregationOperation, params string[] fieldsToGroupBy)
{
groupByFields = fieldsToGroupBy;
aggregationOp = aggregationOperation;
}
/// <summary>
/// Simplified method for closing a clause within the query
/// </summary>
/// <returns></returns>
public void CloseSubclause()
{
currentClauseDepth--;
theQueryText.Append(")");
}
/// <summary>
/// Matches exact value
/// </summary>
public void WhereEquals(WhereParams whereParams)
{
EnsureValidFieldName(whereParams);
var transformToEqualValue = TransformToEqualValue(whereParams);
lastEquality = new KeyValuePair<string, string>(whereParams.FieldName, transformToEqualValue);
if (theQueryText.Length > 0 && theQueryText[theQueryText.Length - 1] != '(')
{
theQueryText.Append(" ");
}
NegateIfNeeded();
theQueryText.Append(whereParams.FieldName);
theQueryText.Append(":");
theQueryText.Append(transformToEqualValue);
}
private string EnsureValidFieldName(WhereParams whereParams)
{
if (theSession == null || theSession.Conventions == null || whereParams.IsNestedPath)
return whereParams.FieldName;
var identityProperty = theSession.Conventions.GetIdentityProperty(typeof(T));
if (identityProperty == null || identityProperty.Name != whereParams.FieldName)
return whereParams.FieldName;
return whereParams.FieldName = Constants.DocumentIdFieldName;
}
///<summary>
/// Negate the next operation
///</summary>
public void NegateNext()
{
negate = !negate;
}
private void NegateIfNeeded()
{
if (negate == false)
return;
negate = false;
theQueryText.Append("-");
}
/// <summary>
/// Matches substrings of the field
/// </summary>
public void WhereContains(string fieldName, object value)
{
WhereEquals(new WhereParams
{
AllowWildcards = true,
IsAnalyzed = true,
FieldName = fieldName,
Value = value
});
}
/// <summary>
/// Matches substrings of the field
/// </summary>
public void WhereContains(string fieldName, params object [] values)
{
if (values == null || values.Length == 0)
return;
OpenSubclause();
WhereContains(fieldName, values[0]);
for (var i = 1; i < values.Length; i++)
{
OrElse();
WhereContains(fieldName, values[i]);
}
CloseSubclause();
}
/// <summary>
/// Matches substrings of the field
/// </summary>
public void WhereContains(string fieldName, IEnumerable<object> values)
{
WhereContains(fieldName, values.ToArray());
}
/// <summary>
/// Matches fields which starts with the specified value.
/// </summary>
/// <param name = "fieldName">Name of the field.</param>
/// <param name = "value">The value.</param>
public void WhereStartsWith(string fieldName, object value)
{
// NOTE: doesn't fully match StartsWith semantics
WhereEquals(
new WhereParams
{
FieldName = fieldName,
Value = String.Concat(value, "*"),
IsAnalyzed = true,
AllowWildcards = true
});
}
/// <summary>
/// Matches fields which ends with the specified value.
/// </summary>
/// <param name = "fieldName">Name of the field.</param>
/// <param name = "value">The value.</param>
public void WhereEndsWith(string fieldName, object value)
{
// http://lucene.apache.org/java/2_4_0/queryparsersyntax.html#Wildcard%20Searches
// You cannot use a * or ? symbol as the first character of a search
// NOTE: doesn't fully match EndsWith semantics
WhereEquals(
new WhereParams
{
FieldName = fieldName,
Value = String.Concat("*", value),
AllowWildcards = true,
IsAnalyzed = true
});
}
/// <summary>
/// Matches fields where the value is between the specified start and end, exclusive
/// </summary>
/// <param name = "fieldName">Name of the field.</param>
/// <param name = "start">The start.</param>
/// <param name = "end">The end.</param>
/// <returns></returns>
public void WhereBetween(string fieldName, object start, object end)
{
if (theQueryText.Length > 0)
{
theQueryText.Append(" ");
}
if ((start ?? end) != null)
sortByHints.Add(new KeyValuePair<string, Type>(fieldName, (start ?? end).GetType()));
NegateIfNeeded();
fieldName = EnsureValidFieldName(new WhereParams { FieldName = fieldName });
theQueryText.Append(fieldName).Append(":{");
theQueryText.Append(start == null ? "*" : TransformToRangeValue(new WhereParams{Value = start, FieldName = fieldName}));
theQueryText.Append(" TO ");
theQueryText.Append(end == null ? "NULL" : TransformToRangeValue(new WhereParams{Value = end, FieldName = fieldName}));
theQueryText.Append("}");
}
/// <summary>
/// Matches fields where the value is between the specified start and end, inclusive
/// </summary>
/// <param name = "fieldName">Name of the field.</param>
/// <param name = "start">The start.</param>
/// <param name = "end">The end.</param>
/// <returns></returns>
public void WhereBetweenOrEqual(string fieldName, object start, object end)
{
if (theQueryText.Length > 0)
{
theQueryText.Append(" ");
}
if ((start ?? end) != null)
sortByHints.Add(new KeyValuePair<string, Type>(fieldName, (start ?? end).GetType()));
NegateIfNeeded();
fieldName = EnsureValidFieldName(new WhereParams { FieldName = fieldName });
theQueryText.Append(fieldName).Append(":[");
theQueryText.Append(start == null ? "*" : TransformToRangeValue(new WhereParams { Value = start, FieldName = fieldName }));
theQueryText.Append(" TO ");
theQueryText.Append(end == null ? "NULL" : TransformToRangeValue(new WhereParams { Value = end, FieldName = fieldName }));
theQueryText.Append("]");
}
/// <summary>
/// Matches fields where the value is greater than the specified value
/// </summary>
/// <param name = "fieldName">Name of the field.</param>
/// <param name = "value">The value.</param>
public void WhereGreaterThan(string fieldName, object value)
{
WhereBetween(fieldName, value, null);
}
/// <summary>
/// Matches fields where the value is greater than or equal to the specified value
/// </summary>
/// <param name = "fieldName">Name of the field.</param>
/// <param name = "value">The value.</param>
public void WhereGreaterThanOrEqual(string fieldName, object value)
{
WhereBetweenOrEqual(fieldName, value, null);
}
/// <summary>
/// Matches fields where the value is less than the specified value
/// </summary>
/// <param name = "fieldName">Name of the field.</param>
/// <param name = "value">The value.</param>
public void WhereLessThan(string fieldName, object value)
{
WhereBetween(fieldName, null, value);
}
/// <summary>
/// Matches fields where the value is less than or equal to the specified value
/// </summary>
/// <param name = "fieldName">Name of the field.</param>
/// <param name = "value">The value.</param>
public void WhereLessThanOrEqual(string fieldName, object value)
{
WhereBetweenOrEqual(fieldName, null, value);
}
/// <summary>
/// Add an AND to the query
/// </summary>
public void AndAlso()
{
if (theQueryText.Length < 1)
{
throw new InvalidOperationException("Missing where clause");
}
theQueryText.Append(" AND");