forked from FoundationDB/fdb-record-layer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LuceneIndexExpressions.java
462 lines (423 loc) · 20.4 KB
/
LuceneIndexExpressions.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
/*
* LuceneIndexExpressions.java
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2021 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.apple.foundationdb.record.lucene;
import com.apple.foundationdb.record.RecordCoreException;
import com.apple.foundationdb.record.metadata.expressions.FieldKeyExpression;
import com.apple.foundationdb.record.metadata.expressions.GroupingKeyExpression;
import com.apple.foundationdb.record.metadata.expressions.KeyExpression;
import com.apple.foundationdb.record.metadata.expressions.LiteralKeyExpression;
import com.apple.foundationdb.record.metadata.expressions.NestingKeyExpression;
import com.apple.foundationdb.record.metadata.expressions.RecordTypeKeyExpression;
import com.apple.foundationdb.record.metadata.expressions.ThenKeyExpression;
import com.google.protobuf.Descriptors;
import org.apache.lucene.queryparser.flexible.standard.config.PointsConfig;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* The root expression of a {@code LUCENE} index specifies how select fields of a record are mapped to fields of a Lucene document.
*
* <p>
* The expression tree is made up of the following.<br>
* <b>Structure</b><ul>
* <li>{@link ThenKeyExpression concat} includes multiple subexpressions in the index.
* Since these are flattened, order does not really matter.</li>
* <li>{@link NestingKeyExpression nest} traverses a nested subrecord.
* By default, the name of the parent field is prepended to the names of descendent fields.</li>
* </ul>
*
* <p>
* <b>Fields</b><ul>
* <li>{@link FieldKeyExpression field} is a record field whose value is added to the index.
* By default, a field is indexed as a scalar value. That is, even a string with whitespace is a single token.
* </li>
* <li>{@link LuceneFunctionNames#LUCENE_TEXT function(lucene_text)} annotates a document field as text so that it is tokenized in the Lucene index.</li>
* <li>{@link LuceneFunctionNames#LUCENE_STORED function(lucene_stored)} annotates a document field as additionally stored in the document so that its value is returned in searches.</li>
* </ul>
*
* <p>
* <b>Names</b><br>
* By default, the name of each field in the hierarchy of nested subrecords is included in the name of flattened fields.
* {@link LuceneFunctionNames#LUCENE_FIELD_NAME function(lucene_field_name)} overrides this.<ul>
* <li>{@code value(null)} skips adding any name prefix, introducing the possibility of flattened name collisions.</li>
* <li>{@code field(key)} allows another field to give the name. This is useful for map-like nested subrecords with well-known keys.</li>
* </ul>
*
* <p>
* The expression tree can be walked in several different ways, either with an actual record to produce actual fields, or with
* record meta-data to determine what possible fields there are. Specifically,<ul>
* <li>map a record into a document</li>
* <li>get a list of document field names</li>
* <li>validate the index expression at definition time</li>
* <li>compute correlated matching expressions for the query planner</li>
* </ul>
*/
public class LuceneIndexExpressions {
private LuceneIndexExpressions() {
}
/**
* Possible types for document fields.
*/
public enum DocumentFieldType { STRING, TEXT, INT, LONG, DOUBLE, BOOLEAN }
/**
* Validate this key expression by interpreting it against the given meta-data.
* @param root the {@code LUCENE} index root expresison
* @param recordType Protobuf meta-data for record type
*/
public static void validate(@Nonnull KeyExpression root, @Nonnull Descriptors.Descriptor recordType) {
getFields(root, new MetaDataSource(recordType), (source, fieldName, value, type, stored, sorted, overriddeKeyRanges, groupingKeyIndex, keyIndex, fieldConfigsIgnored) -> {
}, null);
}
/**
* Information about how a document field is derived from a record field.
*/
// TODO: Make this a JDK 14 record.
public static class DocumentFieldDerivation {
@Nonnull
private final String documentField;
@Nonnull
private final List<String> recordFieldPath;
@Nonnull
private final DocumentFieldType type;
private final boolean stored;
private final boolean sorted;
public DocumentFieldDerivation(@Nonnull String documentField, @Nonnull List<String> recordFieldPath,
@Nonnull DocumentFieldType type, boolean stored, boolean sorted) {
this.documentField = documentField;
this.recordFieldPath = recordFieldPath;
this.type = type;
this.stored = stored;
this.sorted = sorted;
}
@Nonnull
public String getDocumentField() {
return documentField;
}
@Nonnull
public List<String> getRecordFieldPath() {
return recordFieldPath;
}
@Nonnull
public DocumentFieldType getType() {
return type;
}
public boolean isStored() {
return stored;
}
public boolean isSorted() {
return sorted;
}
/**
* Get the Point configuration that is used by the Lucene Parser to interpret the type of data
* stored for this field.
*
* @return the PointsConfig for this field.
*/
public PointsConfig getPointsConfig() {
switch (type) {
case INT:
return new PointsConfig(NumberFormat.getInstance(), Integer.class);
case LONG:
return new PointsConfig(NumberFormat.getInstance(), Long.class);
case DOUBLE:
return new PointsConfig(NumberFormat.getInstance(), Double.class);
case STRING:
case TEXT:
case BOOLEAN:
default:
//we skip fields that are non-numeric because they don't parse differently in lucene anyway
return null;
}
}
}
/**
* Get the derivations of known document fields.
* @param root the {@code LUCENE} index root expression
* @param recordType Protobuf meta-data for record type
* @return a map of document field names to {@link DocumentFieldDerivation}
*/
public static Map<String, DocumentFieldDerivation> getDocumentFieldDerivations(@Nonnull KeyExpression root, @Nonnull Descriptors.Descriptor recordType) {
final Map<String, DocumentFieldDerivation> fields = new HashMap<>();
getFields(root,
new MetaDataSource(recordType),
(source, fieldName, value, type, stored, sorted, overriddenKeyRanges, groupingKeyIndex, keyIndex, fieldConfigsIgnored) -> {
List<String> path = new ArrayList<>();
for (MetaDataSource metaDataSource = source; metaDataSource != null; metaDataSource = metaDataSource.getParent()) {
if (metaDataSource.getField() != null) {
path.add(0, metaDataSource.getField());
}
}
path.add((String)value);
DocumentFieldDerivation derivation = new DocumentFieldDerivation(fieldName, path, type, stored, sorted);
fields.put(fieldName, derivation);
}, null);
return fields;
}
/**
* An actual record / record meta-data.
* @param <T> the actual type of this source
*/
public interface RecordSource<T extends RecordSource<T>> {
@Nonnull
Descriptors.Descriptor getDescriptor();
@Nonnull
Iterable<T> getChildren(@Nonnull FieldKeyExpression parentExpression);
@Nonnull
Iterable<Object> getValues(@Nonnull FieldKeyExpression fieldExpression);
}
/**
* An actual document / document meta-data.
* @param <T> the actual type of the source
*/
public interface DocumentDestination<T extends RecordSource<T>> {
@SuppressWarnings("java:S107")
void addField(@Nonnull T source, @Nonnull String fieldName, @Nullable Object value, @Nonnull DocumentFieldType type,
boolean stored, boolean sorted, @Nonnull List<Integer> overriddenKeyRanges, int groupingKeyIndex, int keyIndex, @Nonnull Map<String, Object> fieldConfigs);
}
/**
* Interpret the index key expression, either concretely for an actual record, or symbolically using meta-data.
* @param <T> specific kind of {@link RecordSource}
* @param root the {@code LUCENE} index root expresison
* @param source the record / record meta-data
* @param destination the document / document meta-data
* @param fieldNamePrefix prefix for generated field names
*/
@Nonnull
public static <T extends RecordSource<T>> void getFields(@Nonnull KeyExpression root, @Nonnull T source,
@Nonnull DocumentDestination<T> destination, @Nullable String fieldNamePrefix) {
KeyExpression expression;
if (root instanceof GroupingKeyExpression) {
expression = ((GroupingKeyExpression)root).getGroupedSubKey();
} else {
expression = root;
}
getFieldsRecursively(expression, source, destination, fieldNamePrefix, 0,
root instanceof GroupingKeyExpression ? ((GroupingKeyExpression) root).getGroupingCount() : 0, new ArrayList<>());
}
@SuppressWarnings("squid:S3776")
public static <T extends RecordSource<T>> void getFieldsRecursively(@Nonnull KeyExpression expression,
@Nonnull T source, @Nonnull DocumentDestination<T> destination,
@Nullable String fieldNamePrefix, int keyIndex, int groupingCount,
@Nonnull List<Integer> overriddenKeyRanges) {
// Record type evaluation of primary key based on this expression for the partial record is not needed,
// because this partial record to build has the correct record type.
if (expression instanceof RecordTypeKeyExpression) {
return;
}
if (expression instanceof ThenKeyExpression) {
int count = 0;
for (KeyExpression child : ((ThenKeyExpression)expression).getChildren()) {
getFieldsRecursively(child, source, destination, fieldNamePrefix, keyIndex + count, groupingCount, overriddenKeyRanges);
count += child.getColumnSize();
}
return;
}
String fieldNameSuffix = null;
boolean suffixOverride = false;
if (expression instanceof LuceneFunctionKeyExpression.LuceneFieldName) {
LuceneFunctionKeyExpression.LuceneFieldName fieldNameExpression = (LuceneFunctionKeyExpression.LuceneFieldName)expression;
KeyExpression nameExpression = fieldNameExpression.getNameExpression();
if (nameExpression instanceof LiteralKeyExpression) {
fieldNameSuffix = (String)((LiteralKeyExpression<?>)nameExpression).getValue();
} else if (nameExpression instanceof FieldKeyExpression) {
Iterator<Object> names = source.getValues((FieldKeyExpression)nameExpression).iterator();
if (names.hasNext()) {
fieldNameSuffix = (String)names.next();
if (names.hasNext()) {
throw new RecordCoreException("Lucene field name override should evaluate to single value");
}
}
} else {
throw new RecordCoreException("Lucene field name override should be a literal or a field");
}
suffixOverride = true;
expression = fieldNameExpression.getNamedExpression();
}
if (expression instanceof NestingKeyExpression) {
NestingKeyExpression nestingExpression = (NestingKeyExpression)expression;
FieldKeyExpression parentExpression = nestingExpression.getParent();
KeyExpression child = nestingExpression.getChild();
if (!suffixOverride) {
fieldNameSuffix = parentExpression.getFieldName();
} else {
addOverriddenKeyRange(overriddenKeyRanges, fieldNamePrefix, fieldNameSuffix);
}
String fieldName = appendFieldName(fieldNamePrefix, fieldNameSuffix);
for (T subsource : source.getChildren(parentExpression)) {
getFieldsRecursively(child, subsource, destination, fieldName, keyIndex, groupingCount, overriddenKeyRanges);
}
if (suffixOverride) {
// Remove the last 2 numbers added above
removedLastOverriddenKeyRange(overriddenKeyRanges);
}
return;
}
boolean fieldSorted = false;
boolean fieldStored = false;
boolean fieldText = false;
Map<String, Object> configs = Collections.emptyMap();
while (true) {
if (expression instanceof LuceneFunctionKeyExpression.LuceneSorted) {
LuceneFunctionKeyExpression.LuceneSorted sortedExpression = (LuceneFunctionKeyExpression.LuceneSorted)expression;
fieldSorted = true;
expression = sortedExpression.getSortedExpression();
} else if (expression instanceof LuceneFunctionKeyExpression.LuceneStored) {
LuceneFunctionKeyExpression.LuceneStored storedExpression = (LuceneFunctionKeyExpression.LuceneStored)expression;
fieldStored = true;
expression = storedExpression.getStoredExpression();
} else if (expression instanceof LuceneFunctionKeyExpression.LuceneText) {
LuceneFunctionKeyExpression.LuceneText textExpression = (LuceneFunctionKeyExpression.LuceneText)expression;
fieldText = true;
expression = textExpression.getFieldExpression();
configs = textExpression.getFieldConfigs();
} else {
// TODO: More text options.
break;
}
}
if (expression instanceof FieldKeyExpression) {
FieldKeyExpression fieldExpression = (FieldKeyExpression)expression;
if (!suffixOverride) {
fieldNameSuffix = fieldExpression.getFieldName();
} else {
addOverriddenKeyRange(overriddenKeyRanges, fieldNamePrefix, fieldNameSuffix);
}
String fieldName = appendFieldName(fieldNamePrefix, fieldNameSuffix);
if (fieldName == null) {
fieldName = "_";
}
Descriptors.Descriptor recordDescriptor = source.getDescriptor();
Descriptors.FieldDescriptor fieldDescriptor = recordDescriptor.findFieldByName(fieldExpression.getFieldName());
if (fieldDescriptor == null) {
return;
}
DocumentFieldType fieldType;
if (fieldText) {
switch (fieldDescriptor.getJavaType()) {
case STRING:
fieldType = DocumentFieldType.TEXT;
break;
default:
throw new RecordCoreException("Unknown Lucene text field type");
}
} else {
switch (fieldDescriptor.getJavaType()) {
case STRING:
fieldType = DocumentFieldType.STRING;
break;
case INT:
fieldType = DocumentFieldType.INT;
break;
case LONG:
fieldType = DocumentFieldType.LONG;
break;
case DOUBLE:
fieldType = DocumentFieldType.DOUBLE;
break;
case BOOLEAN:
fieldType = DocumentFieldType.BOOLEAN;
break;
default:
throw new RecordCoreException("Unknown Lucene field type");
}
}
for (Object value : source.getValues(fieldExpression)) {
destination.addField(source, fieldName, value, fieldType, fieldStored, fieldSorted,
overriddenKeyRanges, keyIndex < groupingCount ? keyIndex : -1, keyIndex, configs);
}
if (suffixOverride) {
// Remove the last 2 numbers added above
removedLastOverriddenKeyRange(overriddenKeyRanges);
}
return;
}
throw new RecordCoreException("Unknown Lucene field key expression");
}
private static void addOverriddenKeyRange(@Nonnull List<Integer> overriddenKeyRanges, @Nullable String fieldNamePrefix, @Nullable String fieldNameSuffix) {
if (fieldNamePrefix == null) {
overriddenKeyRanges.add(0);
overriddenKeyRanges.add((fieldNameSuffix == null || fieldNameSuffix.isEmpty()) ? 0 : fieldNameSuffix.length());
} else {
overriddenKeyRanges.add(fieldNamePrefix.length() + 1);
overriddenKeyRanges.add((fieldNameSuffix == null || fieldNameSuffix.isEmpty()) ? fieldNamePrefix.length() + 1 : fieldNamePrefix.length() + fieldNameSuffix.length() + 1);
}
}
private static void removedLastOverriddenKeyRange(@Nonnull List<Integer> overriddenKeyRanges) {
if (overriddenKeyRanges.size() < 2) {
throw new RecordCoreException("Invalid call to remove last overridden key range, since the list has not a full range to remove");
}
overriddenKeyRanges.remove(overriddenKeyRanges.size() - 1);
overriddenKeyRanges.remove(overriddenKeyRanges.size() - 1);
}
@Nullable
private static String appendFieldName(@Nullable String fieldNamePrefix, @Nullable String fieldNameSuffix) {
if (fieldNamePrefix == null) {
return fieldNameSuffix;
} else if (fieldNameSuffix == null) {
return fieldNamePrefix;
} else {
return fieldNamePrefix + "_" + fieldNameSuffix;
}
}
static class MetaDataSource implements RecordSource<MetaDataSource> {
@Nullable
private final MetaDataSource parent;
@Nullable
private final String field;
@Nonnull
private final Descriptors.Descriptor descriptor;
MetaDataSource(@Nonnull Descriptors.Descriptor descriptor) {
this(null, null, descriptor);
}
MetaDataSource(@Nullable MetaDataSource parent, @Nullable String field, @Nonnull Descriptors.Descriptor descriptor) {
this.parent = parent;
this.field = field;
this.descriptor = descriptor;
}
@Nullable
public MetaDataSource getParent() {
return parent;
}
@Nullable
public String getField() {
return field;
}
@Override
public Descriptors.Descriptor getDescriptor() {
return descriptor;
}
@Override
public Iterable<MetaDataSource> getChildren(@Nonnull FieldKeyExpression parentExpression) {
final String parentField = parentExpression.getFieldName();
final Descriptors.FieldDescriptor fieldDescriptor = descriptor.findFieldByName(parentField);
return Collections.singletonList(new MetaDataSource(this, parentField, fieldDescriptor.getMessageType()));
}
@Override
public Iterable<Object> getValues(@Nonnull FieldKeyExpression fieldExpression) {
return Collections.singletonList(fieldExpression.getFieldName());
}
}
}