/
Solr4QueryParser.java
5563 lines (5150 loc) · 234 KB
/
Solr4QueryParser.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
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
/*
* #%L
* Alfresco Search Services
* %%
* Copyright (C) 2005 - 2020 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.solr.query;
import edu.umd.cs.findbugs.annotations.SuppressWarnings;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.dictionary.IndexTokenisationMode;
import org.alfresco.repo.search.MLAnalysisMode;
import org.alfresco.repo.search.adaptor.AnalysisMode;
import org.alfresco.repo.search.adaptor.LuceneFunction;
import org.alfresco.repo.search.adaptor.QueryConstants;
import org.alfresco.repo.search.impl.QueryParserUtils;
import org.alfresco.repo.search.impl.lucene.analysis.MLTokenDuplicator;
import org.alfresco.repo.search.impl.parsers.FTSQueryException;
import org.alfresco.repo.search.impl.parsers.FTSQueryParser;
import org.alfresco.repo.search.impl.parsers.FTSQueryParser.RerankPhase;
import org.alfresco.repo.tenant.TenantService;
import org.alfresco.service.cmr.dictionary.AspectDefinition;
import org.alfresco.service.cmr.dictionary.ClassDefinition;
import org.alfresco.service.cmr.dictionary.DataTypeDefinition;
import org.alfresco.service.cmr.dictionary.DictionaryService;
import org.alfresco.service.cmr.dictionary.PropertyDefinition;
import org.alfresco.service.cmr.dictionary.TypeDefinition;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.SearchParameters;
import org.alfresco.service.namespace.NamespacePrefixResolver;
import org.alfresco.service.namespace.QName;
import org.alfresco.solr.AlfrescoAnalyzerWrapper;
import org.alfresco.solr.AlfrescoSolrDataModel;
import org.alfresco.solr.AlfrescoSolrDataModel.SpecializedFieldType;
import org.alfresco.solr.AlfrescoSolrDataModel.FieldInstance;
import org.alfresco.solr.AlfrescoSolrDataModel.FieldUse;
import org.alfresco.solr.AlfrescoSolrDataModel.IndexedField;
import org.alfresco.solr.component.FingerPrintComponent;
import org.alfresco.solr.utils.ThrowingFunction;
import org.alfresco.util.CachingDateFormat;
import org.alfresco.util.Pair;
import org.alfresco.util.SearchLanguageConversion;
import org.antlr.misc.OrderedHashSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.commongrams.CommonGramsFilter;
import org.apache.lucene.analysis.shingle.ShingleFilterFactory;
import org.apache.lucene.analysis.synonym.SynonymFilter;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.PackedTokenAttributeImpl;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.analysis.tokenattributes.TermToBytesRefAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.lucene.analysis.util.TokenFilterFactory;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.BooleanQuery.Builder;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.LegacyNumericRangeQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.MultiTermQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.RegexpQuery;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TermRangeQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.spans.SpanMultiTermQueryWrapper;
import org.apache.lucene.search.spans.SpanMultiTermQueryWrapper.TopTermsSpanBooleanQueryRewrite;
import org.apache.lucene.search.spans.SpanNearQuery;
import org.apache.lucene.search.spans.SpanOrQuery;
import org.apache.lucene.search.spans.SpanQuery;
import org.apache.lucene.search.spans.SpanTermQuery;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.Version;
import org.apache.solr.analysis.TokenizerChain;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.impl.HttpClientUtil;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.SolrCore;
import org.apache.solr.handler.component.HttpShardHandlerFactory;
import org.apache.solr.handler.component.ShardHandlerFactory;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.DocsStreamer;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.SchemaField;
import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.update.UpdateShardHandlerConfig;
import org.jaxen.saxpath.SAXPathException;
import org.jaxen.saxpath.base.XPathReader;
import org.json.JSONObject;
import org.springframework.extensions.surf.util.I18NUtil;
import java.io.IOException;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.apache.solr.search.QueryParsing.DEFTYPE;
/**
* @author Andy
*
*/
public class Solr4QueryParser extends QueryParser implements QueryConstants
{
private static final String CMIS_REQUEST_HANDLER = "cmis";
public Solr4QueryParser(SolrQueryRequest req, Version matchVersion, String f, Analyzer a,
FTSQueryParser.RerankPhase rerankPhase)
{
super(f, a);
setAllowLeadingWildcard(true);
setAnalyzeRangeTerms(true);
this.rerankPhase = rerankPhase;
this.schema = req.getSchema();
this.solrParams = req.getParams();
SolrCore core = req.getCore();
if(core != null) {
this.shardHandlerFactory = core.getCoreContainer().getShardHandlerFactory();
}
this.request = req;
}
private RerankPhase rerankPhase;
private SolrParams solrParams;
private ShardHandlerFactory shardHandlerFactory;
private SolrQueryRequest request;
IndexSchema schema;
@SuppressWarnings("unused")
private static Log logger = LogFactory.getLog(Solr4QueryParser.class);
protected NamespacePrefixResolver namespacePrefixResolver;
protected DictionaryService dictionaryService;
private TenantService tenantService;
private SearchParameters searchParameters;
private MLAnalysisMode mlAnalysisMode = MLAnalysisMode.EXACT_LANGUAGE_AND_ALL;
private int internalSlop = 0;
int topTermSpanRewriteLimit = 1000;
/**
* @param topTermSpanRewriteLimit
* the topTermSpanRewriteLimit to set
*/
public void setTopTermSpanRewriteLimit(int topTermSpanRewriteLimit)
{
this.topTermSpanRewriteLimit = topTermSpanRewriteLimit;
}
/**
* @param searchParameters
*/
public void setSearchParameters(SearchParameters searchParameters)
{
this.searchParameters = searchParameters;
}
/**
* @param namespacePrefixResolver
*/
public void setNamespacePrefixResolver(NamespacePrefixResolver namespacePrefixResolver)
{
this.namespacePrefixResolver = namespacePrefixResolver;
}
/**
* @param tenantService
*/
public void setTenantService(TenantService tenantService)
{
this.tenantService = tenantService;
}
public SearchParameters getSearchParameters()
{
return searchParameters;
}
@Override
protected Query getFieldQuery(String field, String queryText, int slop) throws ParseException
{
try
{
internalSlop = slop;
Query query;
query = getFieldQuery(field, queryText);
return query;
}
finally
{
internalSlop = 0;
}
}
/**
* @param field
* @param queryText
* @param analysisMode
* @param slop
* @param luceneFunction
* @return the query
* @throws ParseException
* @throws IOException
*/
public Query getFieldQuery(String field, String queryText, AnalysisMode analysisMode, int slop,
LuceneFunction luceneFunction) throws ParseException
{
try
{
internalSlop = slop;
Query query = getFieldQuery(field, queryText, analysisMode, luceneFunction);
return query;
}
finally
{
internalSlop = 0;
}
}
/**
* @param field
* @param sqlLikeClause
* @param analysisMode
* @return the query
* @throws ParseException
*/
public Query getLikeQuery(String field, String sqlLikeClause, AnalysisMode analysisMode) throws ParseException
{
String luceneWildCardExpression = translate(sqlLikeClause);
return getWildcardQuery(field, luceneWildCardExpression, AnalysisMode.LIKE);
}
private String translate(String string)
{
StringBuilder builder = new StringBuilder(string.length());
boolean lastWasEscape = false;
for (int i = 0; i < string.length(); i++)
{
char c = string.charAt(i);
if (lastWasEscape)
{
builder.append(c);
lastWasEscape = false;
} else
{
if (c == '\\')
{
lastWasEscape = true;
} else if (c == '%')
{
builder.append('*');
} else if (c == '_')
{
builder.append('?');
} else if (c == '*')
{
builder.append('\\');
builder.append(c);
} else if (c == '?')
{
builder.append('\\');
builder.append(c);
} else
{
builder.append(c);
}
}
}
if (lastWasEscape)
{
throw new FTSQueryException("Escape character at end of string " + string);
}
return builder.toString();
}
/**
* @param field
* @param queryText
* @param analysisMode
* @param luceneFunction
* @return the query
* @throws ParseException
* @throws IOException
*/
public Query getDoesNotMatchFieldQuery(String field, String queryText, AnalysisMode analysisMode,
LuceneFunction luceneFunction) throws ParseException
{
BooleanQuery.Builder query = new BooleanQuery.Builder();
Query allQuery = new MatchAllDocsQuery();
Query matchQuery = getFieldQuery(field, queryText, analysisMode, luceneFunction);
if ((matchQuery != null))
{
query.add(allQuery, Occur.MUST);
query.add(matchQuery, Occur.MUST_NOT);
} else
{
throw new UnsupportedOperationException();
}
return query.build();
}
public Query getFieldQuery(String field, String queryText) throws ParseException
{
return getFieldQuery(field, queryText, AnalysisMode.DEFAULT, LuceneFunction.FIELD);
}
/**
* @param field
* @param first
* @param last
* @param slop
* @param inOrder
* @return the query
* @throws ParseException
*/
public Query getSpanQuery(String field, String first, String last, int slop, boolean inOrder) throws ParseException
{
if (field.equals(FIELD_PATH))
{
throw new UnsupportedOperationException("Span is not supported for " + FIELD_PATH);
}
else if (field.equals(FIELD_PATHWITHREPEATS))
{
throw new UnsupportedOperationException("Span is not supported for " + FIELD_PATHWITHREPEATS);
} else if (field.equals(FIELD_TEXT))
{
return createDefaultTextQuery(textField -> getSpanQuery(textField, first, last, slop, inOrder));
} else if (field.equals(FIELD_CLASS))
{
throw new UnsupportedOperationException("Span is not supported for " + FIELD_CLASS);
} else if (field.equals(FIELD_TYPE))
{
throw new UnsupportedOperationException("Span is not supported for " + FIELD_TYPE);
} else if (field.equals(FIELD_EXACTTYPE))
{
throw new UnsupportedOperationException("Span is not supported for " + FIELD_EXACTTYPE);
} else if (field.equals(FIELD_ASPECT))
{
throw new UnsupportedOperationException("Span is not supported for " + FIELD_ASPECT);
} else if (field.equals(FIELD_EXACTASPECT))
{
throw new UnsupportedOperationException("Span is not supported for " + FIELD_EXACTASPECT);
} else if (isPropertyField(field))
{
return spanQueryBuilder(field, first, last, slop, inOrder);
} else if (field.equals(FIELD_ALL))
{
Set<String> all = searchParameters.getAllAttributes();
if ((all == null) || (all.size() == 0))
{
Collection<QName> contentAttributes = dictionaryService.getAllProperties(null);
BooleanQuery.Builder query = new BooleanQuery.Builder();
for (QName qname : contentAttributes)
{
Query part = getSpanQuery(PROPERTY_FIELD_PREFIX + qname.toString(), first, last, slop, inOrder);
query.add(part, Occur.SHOULD);
}
return query.build();
} else
{
BooleanQuery.Builder query = new BooleanQuery.Builder();
for (String fieldName : all)
{
Query part = getSpanQuery(fieldName, first, last, slop, inOrder);
query.add(part, Occur.SHOULD);
}
return query.build();
}
} else if (field.equals(FIELD_ISUNSET))
{
throw new UnsupportedOperationException("Span is not supported for " + FIELD_ISUNSET);
} else if (field.equals(FIELD_ISNULL))
{
throw new UnsupportedOperationException("Span is not supported for " + FIELD_ISNULL);
} else if (field.equals(FIELD_ISNOTNULL))
{
throw new UnsupportedOperationException("Span is not supported for " + FIELD_ISNOTNULL);
} else if (field.equals(FIELD_EXISTS))
{
throw new UnsupportedOperationException("Span is not supported for " + FIELD_EXISTS);
} else if (QueryParserUtils.matchDataTypeDefinition(searchParameters.getNamespace(), namespacePrefixResolver,
dictionaryService, field) != null)
{
Collection<QName> contentAttributes = dictionaryService
.getAllProperties(QueryParserUtils.matchDataTypeDefinition(searchParameters.getNamespace(),
namespacePrefixResolver, dictionaryService, field).getName());
BooleanQuery.Builder query = new BooleanQuery.Builder();
for (QName qname : contentAttributes)
{
Query part = getSpanQuery(PROPERTY_FIELD_PREFIX + qname.toString(), first, last, slop, inOrder);
query.add(part, Occur.SHOULD);
}
return query.build();
} else if (field.equals(FIELD_FTSSTATUS))
{
throw new UnsupportedOperationException("Span is not supported for " + FIELD_FTSSTATUS);
} else if (field.equals(FIELD_TAG))
{
return null;
} else if (isPropertyField(field))
{
return spanQueryBuilder(field, first, last, slop, inOrder);
} else
{
BytesRef firstBytes = analyzeMultitermTerm(field, first);
BytesRef lastBytes = analyzeMultitermTerm(field, last);
SpanQuery firstTerm = new SpanTermQuery(new Term(field, firstBytes));
SpanQuery lastTerm = new SpanTermQuery(new Term(field, lastBytes));
return new SpanNearQuery(new SpanQuery[]
{ firstTerm, lastTerm }, slop, inOrder);
}
}
protected Query getFieldQuery(String field, String queryText, boolean quoted) throws ParseException
{
return getFieldQuery(field, queryText, AnalysisMode.DEFAULT, LuceneFunction.FIELD);
}
/**
* @param field
* @param queryText
* @param analysisMode
* @param luceneFunction
* @return the query
* @throws ParseException
* @throws IOException
*/
@SuppressWarnings("deprecation")
public Query getFieldQuery(String field, String queryText, AnalysisMode analysisMode, LuceneFunction luceneFunction)
throws ParseException
{
try
{
if (field.equals(FIELD_PATH))
{
return createPathQuery(queryText, false);
} else if (field.equals(FIELD_PATHWITHREPEATS))
{
return createPathQuery(queryText, true);
} else if (field.equals(FIELD_TEXT))
{
return createTextQuery(queryText, analysisMode, luceneFunction);
} else if (field.equals(FIELD_ID))
{
return createIdQuery(queryText);
} else if (field.equals(FIELD_SOLR4_ID))
{
return createSolr4IdQuery(queryText);
} else if (field.equals(FIELD_DBID))
{
return createDbidQuery(queryText);
} else if (field.equals(FIELD_ACLID))
{
return createAclIdQuery(queryText);
} else if (field.equals(FIELD_OWNER))
{
return createOwnerQuery(queryText);
} else if (field.equals(FIELD_OWNERSET))
{
return createOwnerSetQuery(queryText);
} else if (field.equals(FIELD_READER))
{
return createReaderQuery(queryText);
} else if (field.equals(FIELD_READERSET))
{
return createReaderSetQuery(queryText);
} else if (field.equals(FIELD_AUTHORITY))
{
/*
* ACL DOCUMENTATION STARTS HERE
* This creates the query that applies the ACL filter
*/
return createAuthorityQuery(queryText);
} else if (field.equals(FIELD_AUTHORITYSET))
{
/*
* ACL DOCUMENTATION STARTS HERE
* This creates the query that applies the ACL filter
*/
return createAuthoritySetQuery(queryText);
} else if (field.equals(FIELD_DENIED))
{
return createDeniedQuery(queryText);
} else if (field.equals(FIELD_DENYSET))
{
return createDenySetQuery(queryText);
} else if (field.equals(FIELD_ISROOT))
{
return createIsRootQuery(queryText);
} else if (field.equals(FIELD_ISCONTAINER))
{
return createIsContainerQuery(queryText);
} else if (field.equals(FIELD_ISNODE))
{
return createIsNodeQuery(queryText);
} else if (field.equals(FIELD_TX))
{
return createTransactionQuery(queryText);
} else if (field.equals(FIELD_INTXID))
{
return createInTxIdQuery(queryText);
} else if (field.equals(FIELD_INACLTXID))
{
return createInAclTxIdQuery(queryText);
} else if (field.equals(FIELD_PARENT))
{
return createParentQuery(queryText);
} else if (field.equals(FIELD_PRIMARYPARENT))
{
return createPrimaryParentQuery(queryText);
} else if (field.equals(FIELD_QNAME))
{
return createQNameQuery(queryText);
} else if (field.equals(FIELD_PRIMARYASSOCQNAME))
{
return createPrimaryAssocQNameQuery(queryText);
} else if (field.equals(FIELD_PRIMARYASSOCTYPEQNAME))
{
return createPrimaryAssocTypeQNameQuery(queryText);
} else if (field.equals(FIELD_ASSOCTYPEQNAME))
{
return createAssocTypeQNameQuery(queryText);
} else if (field.equals(FIELD_CLASS))
{
ClassDefinition target = QueryParserUtils.matchClassDefinition(searchParameters.getNamespace(),
namespacePrefixResolver, dictionaryService, queryText);
if (target == null)
{
return new TermQuery(new Term(FIELD_TYPE, "_unknown_"));
}
return getFieldQuery(target.isAspect() ? FIELD_ASPECT : FIELD_TYPE, queryText, analysisMode,
luceneFunction);
} else if (field.equals(FIELD_TYPE))
{
return createTypeQuery(queryText, false);
} else if (field.equals(FIELD_EXACTTYPE))
{
return createTypeQuery(queryText, true);
} else if (field.equals(FIELD_ASPECT))
{
return createAspectQuery(queryText, false);
} else if (field.equals(FIELD_EXACTASPECT))
{
return createAspectQuery(queryText, true);
} else if (isPropertyField(field))
{
Query query = attributeQueryBuilder(field, queryText, new FieldQuery(), analysisMode, luceneFunction);
return query;
} else if (field.equals(FIELD_ALL))
{
return createAllQuery(queryText, analysisMode, luceneFunction);
} else if (field.equals(FIELD_ISUNSET))
{
return createIsUnsetQuery(queryText, analysisMode, luceneFunction);
} else if (field.equals(FIELD_ISNULL))
{
return createIsNullQuery(queryText, analysisMode, luceneFunction);
} else if (field.equals(FIELD_ISNOTNULL))
{
return createIsNotNull(queryText, analysisMode, luceneFunction);
} else if (field.equals(FIELD_EXISTS))
{
return createExistsQuery(queryText, analysisMode, luceneFunction);
} else if (QueryParserUtils.matchDataTypeDefinition(searchParameters.getNamespace(),
namespacePrefixResolver, dictionaryService, field) != null)
{
return createDataTypeDefinitionQuery(field, queryText, analysisMode, luceneFunction);
} else if (field.equals(FIELD_TXID))
{
return createTxIdQuery(queryText);
} else if (field.equals(FIELD_ACLTXID))
{
return createAclTxIdQuery(queryText);
} else if (field.equals(FIELD_TXCOMMITTIME))
{
return createTxCommitTimeQuery(queryText);
} else if (field.equals(FIELD_ACLTXCOMMITTIME))
{
return createAclTxCommitTimeQuery(queryText);
} else if (field.equals(FIELD_TAG))
{
return createTagQuery(queryText);
} else if (field.equals(FIELD_SITE))
{
return createSiteQuery(queryText);
} else if (field.equals(FIELD_PNAME))
{
return createPNameQuery(queryText);
} else if (field.equals(FIELD_NPATH))
{
return createNPathQuery(queryText);
} else if (field.equals(FIELD_TENANT))
{
return createTenantQuery(queryText);
} else if (field.equals(FIELD_ANCESTOR))
{
return createAncestorQuery(queryText);
} else if (field.equals(FIELD_FINGERPRINT))
{
String[] parts = queryText.split("_");
Collection values = null;
String nodeId = parts[0];
JSONObject json = (JSONObject)request.getContext().get(AbstractQParser.ALFRESCO_JSON);
String fingerPrint = null;
if(json != null) {
//Was the fingerprint passed in
String fingerPrintKey = "fingerprint." + nodeId;
if(json.has(fingerPrintKey)) {
fingerPrint = (String) json.get("fingerprint." + nodeId);
if (fingerPrint != null) {
List l = new ArrayList();
String[] hashes = fingerPrint.split(" ");
for (String hash : hashes) {
l.add(hash);
}
values = l;
}
}
} else {
json = new JSONObject();
}
if (values == null) {
values = fetchMinHash(nodeId);
}
String shards = this.solrParams.get("shards");
if(values == null && shards != null) {
//we are in distributed mode
//Fetch the fingerPrint from the shards.
//The UUID and DBID will both work for method call.
values = fetchFingerPrint(shards, nodeId);
}
//If we're in distributed mode then add the fingerprint to the json
if(values != null && shards != null && fingerPrint == null) {
ModifiableSolrParams newParams = new ModifiableSolrParams();
newParams.add(solrParams);
solrParams = newParams;
json.put("fingerprint." + nodeId, join(values, " "));
String jsonString = json.toString();
newParams.add(AbstractQParser.ALFRESCO_JSON, jsonString);
request.getContext().put(AbstractQParser.ALFRESCO_JSON, json);
request.setParams(newParams);
}
return createFingerPrintQuery(field, queryText, values, analysisMode, luceneFunction);
} else
{
return getFieldQueryImpl(field, queryText, analysisMode, luceneFunction);
}
} catch (SAXPathException e)
{
throw new ParseException("Failed to parse XPath...\n" + e.getMessage());
} catch (IOException e)
{
throw new ParseException("IO: " + e.getMessage());
}
}
private boolean isNumber(String s) {
for(int i=0; i<s.length(); i++) {
if(!Character.isDigit(s.charAt(i))) {
return false;
}
}
return true;
}
private String join(Collection col, String delimiter){
StringBuilder builder = new StringBuilder();
for(Object o : col){
if(builder.length() > 0) {
builder.append(" ");
}
builder.append(o.toString());
}
return builder.toString();
}
/**
* fetch MINHASH values from lucene index
* @param id argument of search. It is taken as DBID if is numberic, LID otherwise
* @return List of minhashes
* @throws IOException
*/
private Collection fetchMinHash(String id) throws IOException {
SolrIndexSearcher searcher = request.getSearcher();
Query q;
if(isNumber(id))
{
long dbid = Long.parseLong(id);
q = LegacyNumericRangeQuery.newLongRange("DBID", dbid, dbid + 1, true, false);
}
else
{
String query = id.startsWith("workspace") ? id : "workspace://SpacesStore/"+id;
q = new TermQuery(new Term(FIELD_LID, query));
}
TopDocs docs = searcher.search(q, 1);
Set<String> fields = new HashSet();
fields.add(FIELD_FINGERPRINT);
if(docs.totalHits == 1) {
ScoreDoc scoreDoc = docs.scoreDocs[0];
Document doc = searcher.doc(scoreDoc.doc, fields);
List<Object> values = new ArrayList<>();
IndexableField[] minHashes = doc.getFields("MINHASH");
for (IndexableField minHash : minHashes)
{
SchemaField sf = schema.getFieldOrNull(minHash.name());
Object value = DocsStreamer.getValue(sf, minHash);
values.add(value);
}
return values;
}
return null;
}
private Collection fetchFingerPrint(String shards, String nodeId) {
shards = shards.replace(",", "|");
List<String> urls = ((HttpShardHandlerFactory)shardHandlerFactory).buildURLList(shards);
ExecutorService executorService = null;
List<Future> futures = new ArrayList();
Collection fingerPrint = null;
try {
executorService = Executors.newCachedThreadPool();
for (String url : urls) {
futures.add(executorService.submit(new FingerPrintFetchTask(url, nodeId)));
}
for (Future<Collection> future : futures) {
Collection col = future.get();
if(col != null) {
fingerPrint = col;
}
}
}catch(Exception e) {
logger.error(e);
} finally {
if (executorService != null)
{
executorService.shutdown();
}
}
return fingerPrint;
}
private class FingerPrintFetchTask implements Callable<Collection> {
private String url;
private String id;
public FingerPrintFetchTask(String url, String id) {
this.url = url;
this.id = id;
}
public Collection call() throws Exception {
HttpSolrClient solrClient = null;
CloseableHttpClient closeableHttpClient = null;
try {
ModifiableSolrParams params = new ModifiableSolrParams();
params.add(FingerPrintComponent.COMPONENT_NAME, "true");
params.add("id", id);
params.add("qt","/fingerprint");
closeableHttpClient = HttpClientUtil.createClient(getClientParams());
solrClient = new HttpSolrClient.Builder(url).withHttpClient(closeableHttpClient).build();;
QueryRequest request = new QueryRequest(params, SolrRequest.METHOD.POST);
QueryResponse response = request.process(solrClient);
NamedList dataResponse = response.getResponse();
NamedList fingerprint = (NamedList) dataResponse.get("fingerprint");
return (Collection)fingerprint.get("MINHASH");
} finally {
if (closeableHttpClient != null)
{
closeableHttpClient.close();
}
if (solrClient != null)
{
solrClient.close();
}
}
}
protected ModifiableSolrParams getClientParams() {
ModifiableSolrParams clientParams = new ModifiableSolrParams();
clientParams.set(HttpClientUtil.PROP_SO_TIMEOUT, UpdateShardHandlerConfig.DEFAULT_DISTRIBUPDATESOTIMEOUT);
clientParams.set(HttpClientUtil.PROP_CONNECTION_TIMEOUT, UpdateShardHandlerConfig.DEFAULT_DISTRIBUPDATECONNTIMEOUT);
return clientParams;
}
}
/**
* @param field
* @param queryText
* @param analysisMode
*
* @param luceneFunction
* @return
* @throws IOException
* @throws ParseException
*/
private Query createFingerPrintQuery(String field, String queryText, Collection values, AnalysisMode analysisMode,
LuceneFunction luceneFunction) throws IOException, ParseException
{
String[] parts = queryText.split("_");
if (parts.length == 0)
{
return createIsNodeQuery("T");
}
if (values != null)
{
int bandSize = 1;
float fraction = -1;
float truePositive = 1;
if (parts.length > 1)
{
fraction = Float.parseFloat(parts[1]);
if (fraction > 1)
{
fraction /= 100;
}
}
if (parts.length > 2)
{
truePositive = Float.parseFloat(parts[2]);
if (truePositive > 1)
{
truePositive /= 100;
}
bandSize = computeBandSize(values.size(), fraction, truePositive);
}
BooleanQuery.Builder builder = new BooleanQuery.Builder();
BooleanQuery.Builder childBuilder = new BooleanQuery.Builder();
int rowInBand = 0;
for (Object token : values)
{
TermQuery tq = new TermQuery(new Term("MINHASH", token.toString()));
if (bandSize == 1)
{
builder.add(new ConstantScoreQuery(tq), Occur.SHOULD);
} else
{
childBuilder.add(new ConstantScoreQuery(tq), Occur.MUST);
rowInBand++;
if (rowInBand == bandSize)
{
builder.add(new ConstantScoreQuery(childBuilder.setDisableCoord(true).build()),
Occur.SHOULD);
childBuilder = new BooleanQuery.Builder();
rowInBand = 0;
}
}
}
// Avoid a dubious narrow band .... wrap around and pad with the
// start
if (childBuilder.build().clauses().size() > 0)
{
for (Object token : values)
{
TermQuery tq = new TermQuery(new Term("MINHASH", token.toString()));
childBuilder.add(new ConstantScoreQuery(tq), Occur.MUST);
rowInBand++;
if (rowInBand == bandSize)
{
builder.add(new ConstantScoreQuery(childBuilder.setDisableCoord(true).build()),
Occur.SHOULD);
break;
}
}
}
builder.setDisableCoord(true);
if (parts.length == 2)
{
builder.setMinimumNumberShouldMatch((int) (Math.ceil(values.size() * fraction)));
}
Query q = builder.build();
return q;
} else
{
return getFieldQueryImpl(field, queryText, analysisMode, luceneFunction);
}
}
private int computeBandSize(int numHash, double sim, double expectedTruePositive)
{
for (int bands = 1; bands <= numHash; bands++)
{
int rowsInBand = numHash / bands;
double truePositive = 1 - Math.pow(1 - Math.pow(sim, rowsInBand), bands);
if (truePositive > expectedTruePositive)
{
return rowsInBand;
}
}
return 1;
}
private ArrayList<String> getTokens(IndexableField indexableField) throws IOException
{
ArrayList<String> tokens = new ArrayList<String>();
TokenStream ts = indexableField.tokenStream(schema.getIndexAnalyzer(), null);
CharTermAttribute termAttribute = ts.getAttribute(CharTermAttribute.class);
ts.reset();
while (ts.incrementToken())
{
String token = new String(termAttribute.buffer(), 0, termAttribute.length());
tokens.add(token);
}
ts.end();