1
|
/**
|
2
|
* Copyright (C) 2012 EDIT
|
3
|
* European Distributed Institute of Taxonomy
|
4
|
* http://www.e-taxonomy.eu
|
5
|
*
|
6
|
* The contents of this file are subject to the Mozilla Public License Version 1.1
|
7
|
* See LICENSE.TXT at the top of this package for the full license terms.
|
8
|
*/
|
9
|
package eu.etaxonomy.cdm.api.service.search;
|
10
|
|
11
|
import java.io.IOException;
|
12
|
import java.util.Collection;
|
13
|
import java.util.HashMap;
|
14
|
import java.util.HashSet;
|
15
|
import java.util.List;
|
16
|
import java.util.Map;
|
17
|
import java.util.Set;
|
18
|
import java.util.UUID;
|
19
|
|
20
|
import org.apache.log4j.Logger;
|
21
|
import org.apache.lucene.index.IndexReader;
|
22
|
import org.apache.lucene.index.Term;
|
23
|
import org.apache.lucene.queryparser.classic.ParseException;
|
24
|
import org.apache.lucene.search.BooleanClause;
|
25
|
import org.apache.lucene.search.BooleanClause.Occur;
|
26
|
import org.apache.lucene.search.BooleanQuery;
|
27
|
import org.apache.lucene.search.BooleanQuery.Builder;
|
28
|
import org.apache.lucene.search.FilteredQuery;
|
29
|
import org.apache.lucene.search.IndexSearcher;
|
30
|
import org.apache.lucene.search.MatchAllDocsQuery;
|
31
|
import org.apache.lucene.search.NumericRangeQuery;
|
32
|
import org.apache.lucene.search.Query;
|
33
|
import org.apache.lucene.search.QueryWrapperFilter;
|
34
|
import org.apache.lucene.search.ScoreDoc;
|
35
|
import org.apache.lucene.search.TermQuery;
|
36
|
import org.apache.lucene.search.TopDocs;
|
37
|
import org.apache.lucene.search.WildcardQuery;
|
38
|
import org.apache.lucene.search.join.JoinUtil;
|
39
|
import org.apache.lucene.search.join.ScoreMode;
|
40
|
import org.hibernate.search.engine.ProjectionConstants;
|
41
|
import org.hibernate.search.spatial.impl.Point;
|
42
|
import org.hibernate.search.spatial.impl.Rectangle;
|
43
|
|
44
|
import eu.etaxonomy.cdm.hibernate.search.DefinedTermBaseClassBridge;
|
45
|
import eu.etaxonomy.cdm.hibernate.search.MultilanguageTextFieldBridge;
|
46
|
import eu.etaxonomy.cdm.hibernate.search.NotNullAwareIdBridge;
|
47
|
import eu.etaxonomy.cdm.model.common.CdmBase;
|
48
|
import eu.etaxonomy.cdm.model.common.IdentifiableEntity;
|
49
|
import eu.etaxonomy.cdm.model.common.Language;
|
50
|
|
51
|
/**
|
52
|
* QueryFactory creates queries for a specific lucene index that means queries
|
53
|
* specific to the various CDM base types. Therefore the QueryFactory hold a
|
54
|
* reference to a {@link LuceneSearch} instance which has been created for a
|
55
|
* CDM base type.<br>
|
56
|
* The field names used in queries created on free text fields are remembered
|
57
|
* and can be accessed by {@link #getTextFieldNames()} or {@link #getTextFieldNamesAsArray()}.
|
58
|
* This is useful for highlighting the matches with {@link LuceneSearch#setHighlightFields(String[])}
|
59
|
* <p>
|
60
|
* The index specific methods from {@link LuceneSearch} which are
|
61
|
* used by QueryFactory directly or indirectly are:
|
62
|
* <ul>
|
63
|
* <li>{@link LuceneSearch#getAnalyzer()}</li>
|
64
|
* </ul>
|
65
|
*
|
66
|
*
|
67
|
* @author a.kohlbecker
|
68
|
\* @since Sep 14, 2012
|
69
|
*
|
70
|
*/
|
71
|
public class QueryFactory {
|
72
|
|
73
|
public static final Logger logger = Logger.getLogger(QueryFactory.class);
|
74
|
|
75
|
protected ILuceneIndexToolProvider toolProvider;
|
76
|
|
77
|
Set<String> textFieldNames = new HashSet<String>();
|
78
|
|
79
|
Map<Class<? extends CdmBase>, IndexSearcher> indexSearcherMap = new HashMap<Class<? extends CdmBase>, IndexSearcher>();
|
80
|
|
81
|
private final Class<? extends CdmBase> cdmBaseType;
|
82
|
|
83
|
public Set<String> getTextFieldNames() {
|
84
|
return textFieldNames;
|
85
|
}
|
86
|
|
87
|
public String[] getTextFieldNamesAsArray() {
|
88
|
return textFieldNames.toArray(new String[textFieldNames.size()]);
|
89
|
}
|
90
|
|
91
|
public QueryFactory(ILuceneIndexToolProvider toolProvider, Class<? extends CdmBase> cdmBaseType){
|
92
|
this.cdmBaseType = cdmBaseType;
|
93
|
this.toolProvider = toolProvider;
|
94
|
}
|
95
|
|
96
|
/**
|
97
|
* Creates a new Term query. Depending on whether <code>isTextField</code> is set true or not the
|
98
|
* supplied <code>queryString</code> will be parsed by using the according analyzer or not.
|
99
|
* Setting <code>isTextField</code> to <code>false</code> is useful for searching for uuids etc.
|
100
|
*
|
101
|
* @param fieldName
|
102
|
* @param queryString
|
103
|
* @param isTextField whether this field is a field containing free text in contrast to e.g. ID fields.
|
104
|
* If <code>isTextField</code> is set <code>true</code> the <code>queryString</code> will be parsed by
|
105
|
* using the according analyzer.
|
106
|
* @return the resulting <code>TermQuery</code> or <code>null</code> in case of an <code>ParseException</code>
|
107
|
*
|
108
|
* TODO consider throwing the ParseException !!!!
|
109
|
*/
|
110
|
public Query newTermQuery(String fieldName, String queryString, boolean isTextField) {
|
111
|
|
112
|
String luceneQueryString = fieldName + ":(" + queryString + ")";
|
113
|
if (isTextField) {
|
114
|
queryString = queryString.trim();
|
115
|
boolean isComplexPhraseQuery = queryString.matches("^\\\".*\\s+.*[\\*].*\\\"$");
|
116
|
textFieldNames.add(fieldName);
|
117
|
// in order to support the full query syntax we must use the parser
|
118
|
// here
|
119
|
try {
|
120
|
return toolProvider.getQueryParserFor(cdmBaseType, isComplexPhraseQuery).parse(luceneQueryString);
|
121
|
} catch (ParseException e) {
|
122
|
logger.error(e);
|
123
|
}
|
124
|
return null;
|
125
|
} else {
|
126
|
return new TermQuery(new Term(fieldName, queryString));
|
127
|
}
|
128
|
}
|
129
|
|
130
|
/**
|
131
|
* only to be used for text fields, see {@link #newTermQuery(String, String, boolean)}
|
132
|
* @param fieldName
|
133
|
* @param queryString
|
134
|
* @return a {@link TermQuery} or a {@link WildcardQuery}
|
135
|
*/
|
136
|
public Query newTermQuery(String fieldName, String queryString){
|
137
|
return newTermQuery(fieldName, queryString, true);
|
138
|
}
|
139
|
|
140
|
/**
|
141
|
* DefinedTerms are stored in the Lucene index by the
|
142
|
* {@link DefinedTermBaseClassBridge} in a consistent way. One field per
|
143
|
* language and also in one additional field for all languages. This method
|
144
|
* is a convenient means to retrieve a Lucene query string for such the
|
145
|
* fields.
|
146
|
*
|
147
|
* @param name
|
148
|
* name of the term field as in the Lucene index. The field must
|
149
|
* have been written to Lucene document by
|
150
|
* {@link DefinedTermBaseClassBridge}
|
151
|
*
|
152
|
* @param languages
|
153
|
* the languages to search for exclusively. Can be
|
154
|
* <code>null</code> to search in all languages
|
155
|
* @return
|
156
|
*/
|
157
|
public Query newDefinedTermQuery(String name, String queryString, List<Language> languages) {
|
158
|
|
159
|
Builder localizedTermQueryBuilder = new Builder();
|
160
|
localizedTermQueryBuilder.add(newTermQuery(name + ".label", queryString), Occur.SHOULD);
|
161
|
if(languages == null || languages.size() == 0){
|
162
|
localizedTermQueryBuilder.add(newTermQuery(name + ".representation.text.ALL", queryString), Occur.SHOULD);
|
163
|
localizedTermQueryBuilder.add(newTermQuery(name + ".representation.label.ALL", queryString), Occur.SHOULD);
|
164
|
localizedTermQueryBuilder.add(newTermQuery(name + ".representation.abbreviatedLabel.ALL", queryString), Occur.SHOULD);
|
165
|
|
166
|
} else {
|
167
|
for(Language lang : languages){
|
168
|
localizedTermQueryBuilder.add(newTermQuery(name + ".representation.text." + lang.getUuid().toString(), queryString), Occur.SHOULD);
|
169
|
localizedTermQueryBuilder.add(newTermQuery(name + ".representation.label." + lang.getUuid().toString(), queryString), Occur.SHOULD);
|
170
|
localizedTermQueryBuilder.add(newTermQuery(name + ".representation.abbreviatedLabel." + lang.getUuid().toString(), queryString), Occur.SHOULD);
|
171
|
}
|
172
|
}
|
173
|
return localizedTermQueryBuilder.build();
|
174
|
}
|
175
|
|
176
|
/**
|
177
|
* MultilanguageString maps are stored in the Lucene index by the
|
178
|
* {@link MultilanguageTextFieldBridge } in a consistent way. One field per
|
179
|
* language and also in one additional field for all languages. This method
|
180
|
* is a convenient means to retrieve a Lucene query string for such the
|
181
|
* fields.
|
182
|
*
|
183
|
* @param name
|
184
|
* name of the term field as in the Lucene index. The field must
|
185
|
* have been written to Lucene document by
|
186
|
* {@link DefinedTermBaseClassBridge}
|
187
|
* @param languages
|
188
|
* the languages to search for exclusively. Can be
|
189
|
* <code>null</code> to search in all languages
|
190
|
* @return
|
191
|
*/
|
192
|
public Query newMultilanguageTextQuery(String name, String queryString, List<Language> languages) {
|
193
|
|
194
|
Builder localizedTermQueryBuilder = new Builder();
|
195
|
localizedTermQueryBuilder.add(newTermQuery(name + ".label", queryString), Occur.SHOULD);
|
196
|
if(languages == null || languages.size() == 0){
|
197
|
localizedTermQueryBuilder.add(newTermQuery(name + ".ALL", queryString), Occur.SHOULD);
|
198
|
} else {
|
199
|
for(Language lang : languages){
|
200
|
localizedTermQueryBuilder.add(newTermQuery(name + "." + lang.getUuid().toString(), queryString), Occur.SHOULD);
|
201
|
}
|
202
|
}
|
203
|
return localizedTermQueryBuilder.build();
|
204
|
}
|
205
|
|
206
|
/**
|
207
|
* @param idFieldName
|
208
|
* @param entitiy
|
209
|
* @return
|
210
|
*/
|
211
|
public Query newEntityIdQuery(String idFieldName, CdmBase entitiy){
|
212
|
return newTermQuery(idFieldName, String.valueOf(entitiy.getId()), false);
|
213
|
}
|
214
|
|
215
|
/**
|
216
|
* @param idFieldName
|
217
|
* @param entitiy
|
218
|
* @return
|
219
|
*/
|
220
|
public Query newEntityIdsQuery(String idFieldName, Collection<? extends CdmBase> entities){
|
221
|
Builder idInQueryBuilder = new Builder();
|
222
|
if(entities != null && entities.size() > 0 ){
|
223
|
for(CdmBase entity : entities){
|
224
|
idInQueryBuilder.add(newEntityIdQuery(idFieldName, entity), Occur.SHOULD);
|
225
|
}
|
226
|
}
|
227
|
return idInQueryBuilder.build();
|
228
|
}
|
229
|
|
230
|
/**
|
231
|
* @param idFieldName
|
232
|
* @return
|
233
|
*/
|
234
|
public Query newIsNotNullQuery(String idFieldName){
|
235
|
return new TermQuery(new Term(NotNullAwareIdBridge.notNullField(idFieldName), NotNullAwareIdBridge.NOT_NULL_VALUE));
|
236
|
}
|
237
|
|
238
|
/**
|
239
|
* @param uuidFieldName
|
240
|
* @param entity
|
241
|
* @return
|
242
|
*/
|
243
|
public Query newEntityUuidQuery(String uuidFieldName, IdentifiableEntity entity) {
|
244
|
return newTermQuery(uuidFieldName, entity.getUuid().toString(), false);
|
245
|
}
|
246
|
|
247
|
/**
|
248
|
* creates a query for searching for documents in which the field specified by <code>uuidFieldName</code> matches at least one of the uuid
|
249
|
* of the <code>entities</code>, the sql equivalent of this is <code>WHERE uuidFieldName IN (uuid_1, uuid_2, ...) </code>.
|
250
|
* @param uuidFieldName
|
251
|
* @param entities
|
252
|
* @return
|
253
|
*/
|
254
|
public Query newEntityUuidsQuery(String uuidFieldName, List<? extends IdentifiableEntity> entities){
|
255
|
|
256
|
Builder uuidInQueryBuilder = new Builder();
|
257
|
if(entities != null && entities.size() > 0 ){
|
258
|
for(IdentifiableEntity entity : entities){
|
259
|
uuidInQueryBuilder.add(newEntityUuidQuery(uuidFieldName, entity), Occur.SHOULD);
|
260
|
}
|
261
|
}
|
262
|
return uuidInQueryBuilder.build();
|
263
|
}
|
264
|
|
265
|
|
266
|
/**
|
267
|
* creates a query for searching for documents in which the field specified by <code>uuidFieldName</code> matches at least one of the
|
268
|
* supplied <code>uuids</code>
|
269
|
* the sql equivalent of this is <code>WHERE uuidFieldName IN (uuid_1, uuid_2, ...) </code>.
|
270
|
* @param uuidFieldName
|
271
|
* @param entities
|
272
|
* @return
|
273
|
*/
|
274
|
public Query newUuidQuery(String uuidFieldName, List<UUID> uuids){
|
275
|
|
276
|
Builder uuidInQueryBuilder = new Builder();
|
277
|
if(uuids != null && uuids.size() > 0 ){
|
278
|
for(UUID uuid : uuids){
|
279
|
uuidInQueryBuilder.add(newTermQuery(uuidFieldName, uuids.toString(), false), Occur.SHOULD);
|
280
|
}
|
281
|
}
|
282
|
return uuidInQueryBuilder.build();
|
283
|
}
|
284
|
|
285
|
|
286
|
/**
|
287
|
* Returns a Lucene Query which rely on double numeric range query
|
288
|
* on Latitude / Longitude
|
289
|
*
|
290
|
*(+/- copied from {@link SpatialQueryBuilderFromPoint#buildSpatialQueryByRange(Point, double, String)})
|
291
|
*
|
292
|
* @param center center of the search discus
|
293
|
* @param radius distance max to center in km
|
294
|
* @param fieldName name of the Lucene Field implementing Coordinates
|
295
|
* @return Lucene Query to be used in a search
|
296
|
* @see Query
|
297
|
* @see org.hibernate.search.spatial.Coordinates
|
298
|
*/
|
299
|
public static Query buildSpatialQueryByRange(Rectangle boundingBox, String fieldName) {
|
300
|
|
301
|
String latitudeFieldName = fieldName + "_HSSI_Latitude";
|
302
|
String longitudeFieldName = fieldName + "_HSSI_Longitude";
|
303
|
|
304
|
Query latQuery= NumericRangeQuery.newDoubleRange(
|
305
|
latitudeFieldName, boundingBox.getLowerLeft().getLatitude(),
|
306
|
boundingBox.getUpperRight().getLatitude(), true, true
|
307
|
);
|
308
|
|
309
|
Builder longQueryBuilder = new Builder();
|
310
|
if ( boundingBox.getLowerLeft().getLongitude() <= boundingBox.getUpperRight().getLongitude() ) {
|
311
|
longQueryBuilder.add(NumericRangeQuery.newDoubleRange( longitudeFieldName, boundingBox.getLowerLeft().getLongitude(),
|
312
|
boundingBox.getUpperRight().getLongitude(), true, true ), Occur.MUST);
|
313
|
}
|
314
|
else {
|
315
|
longQueryBuilder.add( NumericRangeQuery.newDoubleRange( longitudeFieldName, boundingBox.getLowerLeft().getLongitude(),
|
316
|
180.0, true, true ), BooleanClause.Occur.SHOULD );
|
317
|
longQueryBuilder.add( NumericRangeQuery.newDoubleRange( longitudeFieldName, -180.0,
|
318
|
boundingBox.getUpperRight().getLongitude(), true, true ), BooleanClause.Occur.SHOULD );
|
319
|
}
|
320
|
|
321
|
Builder boxQueryBuilder = new Builder();
|
322
|
boxQueryBuilder.add( latQuery, BooleanClause.Occur.MUST );
|
323
|
boxQueryBuilder.add( longQueryBuilder.build(), BooleanClause.Occur.MUST );
|
324
|
|
325
|
return new FilteredQuery(
|
326
|
new MatchAllDocsQuery(),
|
327
|
new QueryWrapperFilter( boxQueryBuilder.build() )
|
328
|
);
|
329
|
}
|
330
|
|
331
|
/**
|
332
|
* Warning! JoinQuery do currently not work with numeric fields, see https://issues.apache.org/jira/browse/LUCENE-4824
|
333
|
* @param fromType
|
334
|
* @param fromField
|
335
|
* @param fromFieldIsMultivalued TODO
|
336
|
* @param fromQuery
|
337
|
* @param toField
|
338
|
* @param toType
|
339
|
* Optional parameter. Only used for debugging only, can be left null otherwise.
|
340
|
* @param scoreMode TODO
|
341
|
* @return
|
342
|
* @throws IOException
|
343
|
*/
|
344
|
public Query newJoinQuery(Class<? extends CdmBase> fromType, String fromField, boolean fromFieldIsMultivalued,
|
345
|
Query fromQuery, String toField, Class<? extends CdmBase> toType, ScoreMode scoreMode) throws IOException {
|
346
|
boolean multipleValuesPerDocument = false;
|
347
|
Query joinQuery = JoinUtil.createJoinQuery(
|
348
|
// need to use the sort field of the id field since
|
349
|
// ScoreMode.Max forces the fromField to be a docValue
|
350
|
// field of type [SORTED, SORTED_SET]
|
351
|
fromField + "__sort",
|
352
|
multipleValuesPerDocument, toField,
|
353
|
fromQuery, indexSearcherFor(fromType), scoreMode);
|
354
|
if(logger.isDebugEnabled()) {
|
355
|
logger.debug("joinQuery: " + joinQuery);
|
356
|
if(toType != null) {
|
357
|
TopDocs result = indexSearcherFor(toType).search(joinQuery, 10);
|
358
|
ScoreDoc[] docs = result.scoreDocs;
|
359
|
logger.debug("joinQuery '" + fromType.getSimpleName() + ". " + fromField + "=" + toField + " where " + fromType.getSimpleName() + " matches "+ fromQuery + "' has " + result.totalHits + " results:");
|
360
|
for(ScoreDoc doc : docs) {
|
361
|
logger.debug(" toType doc: " + doc);
|
362
|
IndexReader indexReader = toolProvider.getIndexReaderFor(toType);
|
363
|
logger.debug(" : " + indexReader.document(doc.doc));
|
364
|
}
|
365
|
}
|
366
|
}
|
367
|
return joinQuery;
|
368
|
}
|
369
|
|
370
|
/**
|
371
|
* Creates a class restriction query and wraps the class restriction
|
372
|
* query and the given <code>query</code> into a BooleanQuery where both must match.
|
373
|
* <p>
|
374
|
*
|
375
|
* @param cdmTypeRestriction
|
376
|
* @param query
|
377
|
* @return
|
378
|
*/
|
379
|
public static BooleanQuery.Builder addTypeRestriction(Query query, Class<? extends CdmBase> cdmTypeRestriction) {
|
380
|
|
381
|
BooleanQuery fullQuery;
|
382
|
Builder filteredQueryBuilder = new Builder();
|
383
|
Builder classFilterBuilder = new Builder();
|
384
|
|
385
|
Term t = new Term(ProjectionConstants.OBJECT_CLASS, cdmTypeRestriction.getName());
|
386
|
TermQuery termQuery = new TermQuery(t);
|
387
|
|
388
|
classFilterBuilder.add(termQuery, Occur.SHOULD);
|
389
|
BooleanQuery classFilter = classFilterBuilder.build();
|
390
|
classFilter.setBoost(0);
|
391
|
|
392
|
filteredQueryBuilder.add(query, Occur.MUST);
|
393
|
filteredQueryBuilder.add(classFilter, Occur.MUST); // TODO using Occur.FILTER might be improve performance but causes wrong results
|
394
|
|
395
|
return filteredQueryBuilder;
|
396
|
}
|
397
|
|
398
|
/**
|
399
|
* @param clazz
|
400
|
* @return
|
401
|
*/
|
402
|
private IndexSearcher indexSearcherFor(Class<? extends CdmBase> clazz) {
|
403
|
|
404
|
if(indexSearcherMap.get(clazz) == null){
|
405
|
IndexReader indexReader = toolProvider.getIndexReaderFor(clazz);
|
406
|
IndexSearcher searcher = new IndexSearcher(indexReader);
|
407
|
indexSearcherMap.put(clazz, searcher);
|
408
|
}
|
409
|
IndexSearcher indexSearcher = indexSearcherMap.get(clazz);
|
410
|
return indexSearcher;
|
411
|
}
|
412
|
|
413
|
}
|