diff --git a/build.gradle b/build.gradle index fb8f96925..d454d1a06 100644 --- a/build.gradle +++ b/build.gradle @@ -5,7 +5,7 @@ plugins { id 'idea' id 'maven-publish' id 'signing' - id "com.diffplug.spotless" version "6.22.0" + id "com.diffplug.spotless" version "6.25.0" id 'java-library' id 'jacoco' // Build docs locally by running "site" command diff --git a/src/main/java/com/yelp/nrtsearch/server/analysis/AnalyzerCreator.java b/src/main/java/com/yelp/nrtsearch/server/analysis/AnalyzerCreator.java index 9e6c969c0..683b358d8 100644 --- a/src/main/java/com/yelp/nrtsearch/server/analysis/AnalyzerCreator.java +++ b/src/main/java/com/yelp/nrtsearch/server/analysis/AnalyzerCreator.java @@ -147,8 +147,7 @@ public static void initialize(NrtsearchConfig configuration, Iterable pl SynonymV2GraphFilterFactory.NAME, SynonymV2GraphFilterFactory.class, builtInTokenFilters); for (Plugin plugin : plugins) { - if (plugin instanceof AnalysisPlugin) { - AnalysisPlugin analysisPlugin = (AnalysisPlugin) plugin; + if (plugin instanceof AnalysisPlugin analysisPlugin) { instance.registerAnalyzers(analysisPlugin.getAnalyzers()); instance.registerTokenFilters(analysisPlugin.getTokenFilters(), builtInTokenFilters); instance.registerCharFilters(analysisPlugin.getCharFilters(), builtInCharFilters); diff --git a/src/main/java/com/yelp/nrtsearch/server/analysis/MappingV2CharFilterFactory.java b/src/main/java/com/yelp/nrtsearch/server/analysis/MappingV2CharFilterFactory.java index 424a151b2..83f5f7c4a 100644 --- a/src/main/java/com/yelp/nrtsearch/server/analysis/MappingV2CharFilterFactory.java +++ b/src/main/java/com/yelp/nrtsearch/server/analysis/MappingV2CharFilterFactory.java @@ -61,7 +61,7 @@ public class MappingV2CharFilterFactory extends CharFilterFactory { /** * Initialize this factory via a set of key-value pairs. * - * @param args + * @param args filter arguments */ public MappingV2CharFilterFactory(Map args) { super(args); diff --git a/src/main/java/com/yelp/nrtsearch/server/analysis/NrtsearchSynonymParser.java b/src/main/java/com/yelp/nrtsearch/server/analysis/NrtsearchSynonymParser.java index 085c3ac5e..c046c3012 100644 --- a/src/main/java/com/yelp/nrtsearch/server/analysis/NrtsearchSynonymParser.java +++ b/src/main/java/com/yelp/nrtsearch/server/analysis/NrtsearchSynonymParser.java @@ -90,14 +90,14 @@ public void addInternal(String[] synonyms) throws IOException { } private static String[] split(String s, String separator) { - ArrayList list = new ArrayList(2); + ArrayList list = new ArrayList<>(2); StringBuilder sb = new StringBuilder(); int pos = 0; int end = s.length(); while (pos < end) { if (s.startsWith(separator, pos)) { - if (sb.length() > 0) { + if (!sb.isEmpty()) { list.add(sb.toString()); sb = new StringBuilder(); } @@ -118,15 +118,15 @@ private static String[] split(String s, String separator) { } } - if (sb.length() > 0) { + if (!sb.isEmpty()) { list.add(sb.toString()); } - return list.toArray(new String[list.size()]); + return list.toArray(new String[0]); } private String unescape(String s) { - if (s.indexOf("\\") < 0) { + if (!s.contains("\\")) { return s; } else { StringBuilder sb = new StringBuilder(); diff --git a/src/main/java/com/yelp/nrtsearch/server/codec/ServerCodec.java b/src/main/java/com/yelp/nrtsearch/server/codec/ServerCodec.java index a7b930d9d..cab2877a0 100644 --- a/src/main/java/com/yelp/nrtsearch/server/codec/ServerCodec.java +++ b/src/main/java/com/yelp/nrtsearch/server/codec/ServerCodec.java @@ -42,7 +42,7 @@ public PostingsFormat getPostingsFormatForField(String field) { IndexState state = stateManager.getCurrent(); try { FieldDef fd = state.getFieldOrThrow(field); - if (fd instanceof IndexableFieldDef indexableFieldDef) { + if (fd instanceof IndexableFieldDef indexableFieldDef) { PostingsFormat postingsFormat = indexableFieldDef.getPostingsFormat(); if (postingsFormat != null) { return postingsFormat; @@ -65,7 +65,7 @@ public DocValuesFormat getDocValuesFormatForField(String field) { IndexState state = stateManager.getCurrent(); try { FieldDef fd = state.getFieldOrThrow(field); - if (fd instanceof IndexableFieldDef indexableFieldDef) { + if (fd instanceof IndexableFieldDef indexableFieldDef) { DocValuesFormat docValuesFormat = indexableFieldDef.getDocValuesFormat(); if (docValuesFormat != null) { return docValuesFormat; @@ -86,7 +86,7 @@ public KnnVectorsFormat getKnnVectorsFormatForField(String field) { IndexState state = stateManager.getCurrent(); try { FieldDef fd = state.getFieldOrThrow(field); - if (fd instanceof VectorFieldDef vectorFieldDef) { + if (fd instanceof VectorFieldDef vectorFieldDef) { KnnVectorsFormat vectorsFormat = vectorFieldDef.getVectorsFormat(); if (vectorsFormat != null) { return vectorsFormat; diff --git a/src/main/java/com/yelp/nrtsearch/server/config/NrtsearchConfig.java b/src/main/java/com/yelp/nrtsearch/server/config/NrtsearchConfig.java index 4de7c6e0f..51f9ee0b7 100644 --- a/src/main/java/com/yelp/nrtsearch/server/config/NrtsearchConfig.java +++ b/src/main/java/com/yelp/nrtsearch/server/config/NrtsearchConfig.java @@ -418,7 +418,7 @@ public long getMaxConnectionAgeGraceForReplication() { private static List getPluginSearchPath(Object o) { List paths = new ArrayList<>(); - if (o instanceof List list) { + if (o instanceof List list) { for (Object item : list) { paths.add(item.toString()); } diff --git a/src/main/java/com/yelp/nrtsearch/server/config/NumberReaderFunc.java b/src/main/java/com/yelp/nrtsearch/server/config/NumberReaderFunc.java index a8ddde4da..06dc0dc65 100644 --- a/src/main/java/com/yelp/nrtsearch/server/config/NumberReaderFunc.java +++ b/src/main/java/com/yelp/nrtsearch/server/config/NumberReaderFunc.java @@ -40,8 +40,7 @@ public T apply(Object o) { if (o instanceof String) { return stringConverter.apply((String) o); } - if (o instanceof Number) { - Number num = (Number) o; + if (o instanceof Number num) { if (clazz.isInstance(num)) { return clazz.cast(num); } diff --git a/src/main/java/com/yelp/nrtsearch/server/config/QueryCacheConfig.java b/src/main/java/com/yelp/nrtsearch/server/config/QueryCacheConfig.java index f4917f927..2c977e907 100644 --- a/src/main/java/com/yelp/nrtsearch/server/config/QueryCacheConfig.java +++ b/src/main/java/com/yelp/nrtsearch/server/config/QueryCacheConfig.java @@ -73,15 +73,19 @@ static long sizeStrToBytes(String sizeStr) { long multiplier = 1; if (baseStr.length() > 2) { String suffix = baseStr.substring(baseStr.length() - 2).toLowerCase(); - if ("kb".equals(suffix)) { - baseStr = baseStr.substring(0, baseStr.length() - 2); - multiplier = 1024; - } else if ("mb".equals(suffix)) { - baseStr = baseStr.substring(0, baseStr.length() - 2); - multiplier = 1024 * 1024; - } else if ("gb".equals(suffix)) { - baseStr = baseStr.substring(0, baseStr.length() - 2); - multiplier = 1024 * 1024 * 1024; + switch (suffix) { + case "kb" -> { + baseStr = baseStr.substring(0, baseStr.length() - 2); + multiplier = 1024; + } + case "mb" -> { + baseStr = baseStr.substring(0, baseStr.length() - 2); + multiplier = 1024 * 1024; + } + case "gb" -> { + baseStr = baseStr.substring(0, baseStr.length() - 2); + multiplier = 1024 * 1024 * 1024; + } } } if (baseStr.isEmpty()) { diff --git a/src/main/java/com/yelp/nrtsearch/server/config/ScriptCacheConfig.java b/src/main/java/com/yelp/nrtsearch/server/config/ScriptCacheConfig.java index 3b853d73f..1300b70a9 100644 --- a/src/main/java/com/yelp/nrtsearch/server/config/ScriptCacheConfig.java +++ b/src/main/java/com/yelp/nrtsearch/server/config/ScriptCacheConfig.java @@ -55,11 +55,8 @@ public static ScriptCacheConfig fromConfig(YamlConfigReader configReader) { * null */ public static TimeUnit getTimeUnitFromString(String timeUnitStr) { - TimeUnit timeUnit = - TimeUnit.valueOf( - Objects.requireNonNull( - timeUnitStr, "script cache expiration time unit cannot be null")); - return timeUnit; + return TimeUnit.valueOf( + Objects.requireNonNull(timeUnitStr, "script cache expiration time unit cannot be null")); } /** diff --git a/src/main/java/com/yelp/nrtsearch/server/config/YamlConfigReader.java b/src/main/java/com/yelp/nrtsearch/server/config/YamlConfigReader.java index 85091a421..f39b3beb5 100644 --- a/src/main/java/com/yelp/nrtsearch/server/config/YamlConfigReader.java +++ b/src/main/java/com/yelp/nrtsearch/server/config/YamlConfigReader.java @@ -65,14 +65,14 @@ public class YamlConfigReader { private static final Logger logger = LoggerFactory.getLogger(YamlConfigReader.class.getName()); - private static Function STR_READER = + private static final Function STR_READER = (node) -> { if (!(node instanceof Collection) && !(node instanceof Map)) { return node.toString(); } return null; }; - private static Function BOOL_READER = + private static final Function BOOL_READER = (node) -> { if (node instanceof Boolean) { return (Boolean) node; @@ -83,16 +83,16 @@ public class YamlConfigReader { } return null; }; - private static Function INT_READER = + private static final Function INT_READER = new NumberReaderFunc<>(Integer.class, Number::intValue, Integer::parseInt); - private static Function LONG_READER = + private static final Function LONG_READER = new NumberReaderFunc<>(Long.class, Number::longValue, Long::parseLong); - private static Function FLOAT_READER = + private static final Function FLOAT_READER = new NumberReaderFunc<>(Float.class, Number::floatValue, Float::parseFloat); - private static Function DOUBLE_READER = + private static final Function DOUBLE_READER = new NumberReaderFunc<>(Double.class, Number::doubleValue, Double::parseDouble); - private static String SPLIT_REGEX = "[.]"; + private static final String SPLIT_REGEX = "[.]"; private final Map configRoot; @@ -496,7 +496,7 @@ public List getKeys(String path) throws ConfigKeyNotFoundException { throw new ConfigReadException("Not instance of Map, path: " + path); } List keys = new ArrayList<>(); - for (Object mapKey : ((Map) node).keySet()) { + for (Object mapKey : ((Map) node).keySet()) { if (!(mapKey instanceof String)) { throw new ConfigReadException("Map contain non String key: " + mapKey + ", path: " + path); } diff --git a/src/main/java/com/yelp/nrtsearch/server/doc/SegmentDocLookup.java b/src/main/java/com/yelp/nrtsearch/server/doc/SegmentDocLookup.java index 4088243ad..38ff99996 100644 --- a/src/main/java/com/yelp/nrtsearch/server/doc/SegmentDocLookup.java +++ b/src/main/java/com/yelp/nrtsearch/server/doc/SegmentDocLookup.java @@ -81,7 +81,7 @@ public boolean containsKey(Object key) { String fieldName = key.toString(); try { FieldDef field = fieldDefLookup.apply(fieldName); - return field instanceof IndexableFieldDef && ((IndexableFieldDef) field).hasDocValues(); + return field instanceof IndexableFieldDef && ((IndexableFieldDef) field).hasDocValues(); } catch (Exception ignored) { return false; } @@ -112,10 +112,9 @@ public LoadedDocValues get(Object key) { if (fieldDef == null) { throw new IllegalArgumentException("Field does not exist: " + fieldName); } - if (!(fieldDef instanceof IndexableFieldDef)) { + if (!(fieldDef instanceof IndexableFieldDef indexableFieldDef)) { throw new IllegalArgumentException("Field cannot have doc values: " + fieldName); } - IndexableFieldDef indexableFieldDef = (IndexableFieldDef) fieldDef; try { docValues = indexableFieldDef.getDocValues(context); } catch (IOException e) { diff --git a/src/main/java/com/yelp/nrtsearch/server/facet/DrillSidewaysImpl.java b/src/main/java/com/yelp/nrtsearch/server/facet/DrillSidewaysImpl.java index 85db9516c..2a8746f79 100644 --- a/src/main/java/com/yelp/nrtsearch/server/facet/DrillSidewaysImpl.java +++ b/src/main/java/com/yelp/nrtsearch/server/facet/DrillSidewaysImpl.java @@ -212,7 +212,7 @@ private static com.yelp.nrtsearch.server.grpc.FacetResult getScriptFacetResult( } private static com.yelp.nrtsearch.server.grpc.FacetResult getDocValuesFacetResult( - Facet facet, FacetsCollector drillDowns, IndexableFieldDef fieldDef) throws IOException { + Facet facet, FacetsCollector drillDowns, IndexableFieldDef fieldDef) throws IOException { Map countsMap = new HashMap<>(); int totalDocs = 0; // get doc values for all match docs, and aggregate counts @@ -270,7 +270,7 @@ public static com.yelp.nrtsearch.server.grpc.FacetResult buildFacetResultFromCou builder.setValue(totalDocs); builder.setChildCount(countsMap.size()); - if (countsMap.size() > 0 && facet.getTopN() > 0) { + if (!countsMap.isEmpty() && facet.getTopN() > 0) { // add all map entries into a priority queue, keeping only the top N PriorityQueue> priorityQueue = new PriorityQueue<>( @@ -390,8 +390,7 @@ private static com.yelp.nrtsearch.server.grpc.FacetResult getFieldFacetResult( c = drillDowns; } DoubleRangeFacetCounts doubleRangeFacetCounts; - if (fieldDef instanceof VirtualFieldDef) { - VirtualFieldDef virtualFieldDef = (VirtualFieldDef) fieldDef; + if (fieldDef instanceof VirtualFieldDef virtualFieldDef) { doubleRangeFacetCounts = new DoubleRangeFacetCounts( virtualFieldDef.getName(), virtualFieldDef.getValuesSource(), c, ranges); @@ -407,8 +406,7 @@ private static com.yelp.nrtsearch.server.grpc.FacetResult getFieldFacetResult( facet.getPathsList().toArray(new String[facet.getPathsCount()])); } else { throw new IllegalArgumentException( - String.format( - "numericRanges must be provided only on field type numeric e.g. int, double, flat")); + "numericRanges must be provided only on field type numeric e.g. int, double, flat"); } } else if (fieldDef.getFacetValueType() == IndexableFieldDef.FacetValueType.SORTED_SET_DOC_VALUES) { @@ -486,8 +484,7 @@ private static com.yelp.nrtsearch.server.grpc.FacetResult getFieldFacetResult( // counts for this indexFieldName: String indexFieldName = indexState.getFacetsConfig().getDimConfig(fieldDef.getName()).indexFieldName; - Map facetsMap = indexFieldNameToFacets; - luceneFacets = facetsMap.get(indexFieldName); + luceneFacets = indexFieldNameToFacets.get(indexFieldName); if (luceneFacets == null) { if (useCachedOrds) { luceneFacets = @@ -504,7 +501,7 @@ private static com.yelp.nrtsearch.server.grpc.FacetResult getFieldFacetResult( indexState.getFacetsConfig(), drillDowns); } - facetsMap.put(indexFieldName, luceneFacets); + indexFieldNameToFacets.put(indexFieldName, luceneFacets); } } if (facet.getTopN() != 0) { @@ -517,22 +514,16 @@ private static com.yelp.nrtsearch.server.grpc.FacetResult getFieldFacetResult( } facetResult = new FacetResult( - fieldDef.getName(), - path, - -1, - results.toArray(new LabelAndValue[results.size()]), - -1); + fieldDef.getName(), path, -1, results.toArray(new LabelAndValue[0]), -1); } else { - throw new IllegalArgumentException( - String.format("each facet request must have either topN or labels")); + throw new IllegalArgumentException("each facet request must have either topN or labels"); } } else { // if no facet type is enabled on the field, try using the field doc values - if (!(fieldDef instanceof IndexableFieldDef)) { + if (!(fieldDef instanceof IndexableFieldDef indexableFieldDef)) { throw new IllegalArgumentException( "Doc values facet requires an indexable field : " + fieldName); } - IndexableFieldDef indexableFieldDef = (IndexableFieldDef) fieldDef; if (!indexableFieldDef.hasDocValues()) { throw new IllegalArgumentException( "Doc values facet requires doc values enabled : " + fieldName); diff --git a/src/main/java/com/yelp/nrtsearch/server/facet/FacetTopDocs.java b/src/main/java/com/yelp/nrtsearch/server/facet/FacetTopDocs.java index 8d0fb61fa..1c74121e2 100644 --- a/src/main/java/com/yelp/nrtsearch/server/facet/FacetTopDocs.java +++ b/src/main/java/com/yelp/nrtsearch/server/facet/FacetTopDocs.java @@ -28,7 +28,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.ReaderUtil; import org.apache.lucene.search.IndexSearcher; @@ -64,7 +63,7 @@ public static Iterable facetTopDocsSample( Diagnostics.Builder diagnostics) throws IOException { List sampleFacets = - facets.stream().filter(facet -> facet.getSampleTopDocs() > 0).collect(Collectors.toList()); + facets.stream().filter(facet -> facet.getSampleTopDocs() > 0).toList(); if (sampleFacets.isEmpty()) { return Collections.emptyList(); } @@ -83,11 +82,10 @@ private static FacetResult facetFromTopDocs( TopDocs topDocs, Facet facet, IndexState indexState, IndexSearcher searcher) throws IOException { FieldDef fieldDef = indexState.getFieldOrThrow(facet.getDim()); - if (!(fieldDef instanceof IndexableFieldDef)) { + if (!(fieldDef instanceof IndexableFieldDef indexableFieldDef)) { throw new IllegalArgumentException( "Sampling facet field must be indexable: " + facet.getDim()); } - IndexableFieldDef indexableFieldDef = (IndexableFieldDef) fieldDef; if (!indexableFieldDef.hasDocValues()) { throw new IllegalArgumentException( "Sampling facet field must have doc values enabled: " + facet.getDim()); diff --git a/src/main/java/com/yelp/nrtsearch/server/field/ContextSuggestFieldDef.java b/src/main/java/com/yelp/nrtsearch/server/field/ContextSuggestFieldDef.java index 1aec3ca40..e51e0f414 100644 --- a/src/main/java/com/yelp/nrtsearch/server/field/ContextSuggestFieldDef.java +++ b/src/main/java/com/yelp/nrtsearch/server/field/ContextSuggestFieldDef.java @@ -79,8 +79,7 @@ public void parseDocumentField( */ private void parseFieldValueToDocumentField(Document document, String fieldValue) { ContextSuggestFieldData csfData = GSON.fromJson(fieldValue, ContextSuggestFieldData.class); - CharSequence[] contexts = - csfData.getContexts().toArray(new CharSequence[csfData.getContexts().size()]); + CharSequence[] contexts = csfData.getContexts().toArray(new CharSequence[0]); ContextSuggestField csf = new ContextSuggestField(getName(), csfData.getValue(), csfData.getWeight(), contexts); document.add(csf); diff --git a/src/main/java/com/yelp/nrtsearch/server/field/DateTimeFieldDef.java b/src/main/java/com/yelp/nrtsearch/server/field/DateTimeFieldDef.java index 4787757a1..246d96563 100644 --- a/src/main/java/com/yelp/nrtsearch/server/field/DateTimeFieldDef.java +++ b/src/main/java/com/yelp/nrtsearch/server/field/DateTimeFieldDef.java @@ -57,9 +57,7 @@ private static DateTimeFormatter createDateTimeFormatter(String dateTimeFormat) if (dateTimeFormat.equals(EPOCH_MILLIS)) { return null; } else if (dateTimeFormat.equals(STRICT_DATE_OPTIONAL_TIME)) { - /** - * This is a replication of {@link DateTimeFormatter#ISO_LOCAL_DATE_TIME} with time optional. - */ + // This is a replication of {@link DateTimeFormatter#ISO_LOCAL_DATE_TIME} with time optional. return new DateTimeFormatterBuilder() .parseCaseInsensitive() .append(DateTimeFormatter.ISO_LOCAL_DATE) @@ -271,8 +269,7 @@ private long getTimeFromEpochMillisString(String epochMillisString) { "%s could not parse %s as date_time with format %s", getName(), epochMillisString, dateTimeFormat); try { - long epochMillis = Long.parseLong(epochMillisString); - return epochMillis; + return Long.parseLong(epochMillisString); } catch (NumberFormatException e) { throw new IllegalArgumentException(format, e); } diff --git a/src/main/java/com/yelp/nrtsearch/server/field/FieldDefCreator.java b/src/main/java/com/yelp/nrtsearch/server/field/FieldDefCreator.java index a53bbd160..44dbe8e72 100644 --- a/src/main/java/com/yelp/nrtsearch/server/field/FieldDefCreator.java +++ b/src/main/java/com/yelp/nrtsearch/server/field/FieldDefCreator.java @@ -122,8 +122,7 @@ private String getCustomFieldType(Map additionalProperties) { public static void initialize(NrtsearchConfig configuration, Iterable plugins) { instance = new FieldDefCreator(configuration); for (Plugin plugin : plugins) { - if (plugin instanceof FieldTypePlugin) { - FieldTypePlugin fieldTypePlugin = (FieldTypePlugin) plugin; + if (plugin instanceof FieldTypePlugin fieldTypePlugin) { instance.register(fieldTypePlugin.getFieldTypes()); } } diff --git a/src/main/java/com/yelp/nrtsearch/server/field/NumberFieldDef.java b/src/main/java/com/yelp/nrtsearch/server/field/NumberFieldDef.java index 4b7bbe5a6..16c7a1c92 100644 --- a/src/main/java/com/yelp/nrtsearch/server/field/NumberFieldDef.java +++ b/src/main/java/com/yelp/nrtsearch/server/field/NumberFieldDef.java @@ -177,7 +177,7 @@ protected FacetValueType parseFacetValueType(Field requestField) { /** * Convert the string to number * - * @param numberString + * @param numberString number string * @return number value of the string */ protected Number parseNumberString(String numberString) { diff --git a/src/main/java/com/yelp/nrtsearch/server/field/ObjectFieldDef.java b/src/main/java/com/yelp/nrtsearch/server/field/ObjectFieldDef.java index 2019ca5ca..c572cf118 100644 --- a/src/main/java/com/yelp/nrtsearch/server/field/ObjectFieldDef.java +++ b/src/main/java/com/yelp/nrtsearch/server/field/ObjectFieldDef.java @@ -71,9 +71,7 @@ public void parseFieldWithChildren( parseFieldWithChildren(documentsContext.getRootDocument(), fieldValues, facetHierarchyPaths); } else { List> fieldValueMaps = new ArrayList<>(); - fieldValues.stream() - .map(e -> gson.fromJson(e, Map.class)) - .forEach(e -> fieldValueMaps.add(e)); + fieldValues.stream().map(e -> gson.fromJson(e, Map.class)).forEach(fieldValueMaps::add); List childDocuments = fieldValueMaps.stream() @@ -94,17 +92,16 @@ private Document createChildDocument( Map fieldValue, List> facetHierarchyPaths) { Document document = new Document(); parseFieldWithChildrenObject(document, List.of(fieldValue), facetHierarchyPaths); - ((IndexableFieldDef) (IndexState.getMetaField(IndexState.NESTED_PATH))) + ((IndexableFieldDef) (IndexState.getMetaField(IndexState.NESTED_PATH))) .parseDocumentField(document, List.of(this.getName()), List.of()); return document; } @Override - @SuppressWarnings("unchecked") public void parseFieldWithChildren( Document document, List fieldValues, List> facetHierarchyPaths) { List> fieldValueMaps = new ArrayList<>(); - fieldValues.stream().map(e -> gson.fromJson(e, Map.class)).forEach(e -> fieldValueMaps.add(e)); + fieldValues.stream().map(e -> gson.fromJson(e, Map.class)).forEach(fieldValueMaps::add); if (isStored()) { for (String fieldValue : fieldValues) { document.add(new StoredField(this.getName(), jsonToStruct(fieldValue).toByteArray())); diff --git a/src/main/java/com/yelp/nrtsearch/server/field/VectorFieldDef.java b/src/main/java/com/yelp/nrtsearch/server/field/VectorFieldDef.java index aebc40cbb..54152e5a6 100644 --- a/src/main/java/com/yelp/nrtsearch/server/field/VectorFieldDef.java +++ b/src/main/java/com/yelp/nrtsearch/server/field/VectorFieldDef.java @@ -148,8 +148,9 @@ private static KnnVectorsFormat createVectorsFormat( KnnVectorsFormat vectorsFormat = switch (vectorSearchType) { case HNSW -> getHnswVectorsFormat(m, efConstruction, mergeWorkers, executorService); - case HNSW_SCALAR_QUANTIZED -> getHnswScalarQuantizedVectorsFormat( - m, efConstruction, mergeWorkers, executorService, vectorIndexingOptions); + case HNSW_SCALAR_QUANTIZED -> + getHnswScalarQuantizedVectorsFormat( + m, efConstruction, mergeWorkers, executorService, vectorIndexingOptions); }; return new KnnVectorsFormat(vectorsFormat.getName()) { @@ -196,8 +197,7 @@ private static KnnVectorsFormat getHnswScalarQuantizedVectorsFormat( : DEFAULT_QUANTIZED_BITS; boolean compress = vectorIndexingOptions.hasQuantizedCompress() - ? vectorIndexingOptions.getQuantizedCompress() - : false; + && vectorIndexingOptions.getQuantizedCompress(); return new Lucene99HnswScalarQuantizedVectorsFormat( m, efConstruction, mergeWorkers, bits, compress, confidenceInterval, executorService); @@ -214,8 +214,8 @@ static VectorFieldDef createField(String name, Field field) { return switch (field.getVectorElementType()) { case VECTOR_ELEMENT_FLOAT -> new FloatVectorFieldDef(name, field); case VECTOR_ELEMENT_BYTE -> new ByteVectorFieldDef(name, field); - default -> throw new IllegalArgumentException( - "Invalid field type: " + field.getVectorElementType()); + default -> + throw new IllegalArgumentException("Invalid field type: " + field.getVectorElementType()); }; } diff --git a/src/main/java/com/yelp/nrtsearch/server/field/properties/TermQueryable.java b/src/main/java/com/yelp/nrtsearch/server/field/properties/TermQueryable.java index 5924b11f5..ddaca23ba 100644 --- a/src/main/java/com/yelp/nrtsearch/server/field/properties/TermQueryable.java +++ b/src/main/java/com/yelp/nrtsearch/server/field/properties/TermQueryable.java @@ -36,30 +36,16 @@ public interface TermQueryable { * @throws UnsupportedOperationException if field does not support term type */ default Query getTermQuery(TermQuery termQuery) { - Query query; - switch (termQuery.getTermTypesCase()) { - case BOOLEANVALUE: - query = getTermQueryFromBooleanValue(termQuery.getBooleanValue()); - break; - case DOUBLEVALUE: - query = getTermQueryFromDoubleValue(termQuery.getDoubleValue()); - break; - case FLOATVALUE: - query = getTermQueryFromFloatValue(termQuery.getFloatValue()); - break; - case INTVALUE: - query = getTermQueryFromIntValue(termQuery.getIntValue()); - break; - case LONGVALUE: - query = getTermQueryFromLongValue(termQuery.getLongValue()); - break; - case TEXTVALUE: - query = getTermQueryFromTextValue(termQuery.getTextValue()); - break; - default: - query = null; - break; - } + Query query = + switch (termQuery.getTermTypesCase()) { + case BOOLEANVALUE -> getTermQueryFromBooleanValue(termQuery.getBooleanValue()); + case DOUBLEVALUE -> getTermQueryFromDoubleValue(termQuery.getDoubleValue()); + case FLOATVALUE -> getTermQueryFromFloatValue(termQuery.getFloatValue()); + case INTVALUE -> getTermQueryFromIntValue(termQuery.getIntValue()); + case LONGVALUE -> getTermQueryFromLongValue(termQuery.getLongValue()); + case TEXTVALUE -> getTermQueryFromTextValue(termQuery.getTextValue()); + default -> null; + }; if (query == null) { throw new UnsupportedOperationException( @@ -171,27 +157,20 @@ default Query getTermQueryFromTextValue(String textValue) { * @throws UnsupportedOperationException if field does not support term type */ default Query getTermInSetQuery(TermInSetQuery termInSetQuery) { - Query query; - switch (termInSetQuery.getTermTypesCase()) { - case DOUBLETERMS: - query = getTermInSetQueryFromDoubleValues(termInSetQuery.getDoubleTerms().getTermsList()); - break; - case FLOATTERMS: - query = getTermInSetQueryFromFloatValues(termInSetQuery.getFloatTerms().getTermsList()); - break; - case INTTERMS: - query = getTermInSetQueryFromIntValues(termInSetQuery.getIntTerms().getTermsList()); - break; - case LONGTERMS: - query = getTermInSetQueryFromLongValues(termInSetQuery.getLongTerms().getTermsList()); - break; - case TEXTTERMS: - query = getTermInSetQueryFromTextValues(termInSetQuery.getTextTerms().getTermsList()); - break; - default: - query = null; - break; - } + Query query = + switch (termInSetQuery.getTermTypesCase()) { + case DOUBLETERMS -> + getTermInSetQueryFromDoubleValues(termInSetQuery.getDoubleTerms().getTermsList()); + case FLOATTERMS -> + getTermInSetQueryFromFloatValues(termInSetQuery.getFloatTerms().getTermsList()); + case INTTERMS -> + getTermInSetQueryFromIntValues(termInSetQuery.getIntTerms().getTermsList()); + case LONGTERMS -> + getTermInSetQueryFromLongValues(termInSetQuery.getLongTerms().getTermsList()); + case TEXTTERMS -> + getTermInSetQueryFromTextValues(termInSetQuery.getTextTerms().getTermsList()); + default -> null; + }; if (query == null) { throw new UnsupportedOperationException( String.format( diff --git a/src/main/java/com/yelp/nrtsearch/server/geo/GeoPoint.java b/src/main/java/com/yelp/nrtsearch/server/geo/GeoPoint.java index c6a3dcfb3..50b0233bb 100644 --- a/src/main/java/com/yelp/nrtsearch/server/geo/GeoPoint.java +++ b/src/main/java/com/yelp/nrtsearch/server/geo/GeoPoint.java @@ -61,13 +61,7 @@ public boolean equals(Object o) { @Override public String toString() { - return new StringBuilder("GeoPoint(") - .append("latitude=") - .append(latitude) - .append(", longitude=") - .append(longitude) - .append(")") - .toString(); + return "GeoPoint(" + "latitude=" + latitude + ", longitude=" + longitude + ")"; } @Override diff --git a/src/main/java/com/yelp/nrtsearch/server/geo/GeoUtils.java b/src/main/java/com/yelp/nrtsearch/server/geo/GeoUtils.java index f693a7648..cc2679d03 100644 --- a/src/main/java/com/yelp/nrtsearch/server/geo/GeoUtils.java +++ b/src/main/java/com/yelp/nrtsearch/server/geo/GeoUtils.java @@ -35,20 +35,17 @@ public static double getDistance(String rawDistance) { } try { - double distanceNumber = Double.valueOf(distanceList[0]); + double distanceNumber = Double.parseDouble(distanceList[0]); if (distanceList.length == 1) { return distanceNumber; } String distanceUnit = distanceList[1]; - if (distanceUnit.equals("m")) { - return distanceNumber; - } else if (distanceUnit.equals("km")) { - return distanceNumber * KM_TO_M; - } else if (distanceUnit.equals("mi")) { - return distanceNumber * MI_TO_M; - } else { - throw new IllegalArgumentException("Invalid distance " + rawDistance); - } + return switch (distanceUnit) { + case "m" -> distanceNumber; + case "km" -> distanceNumber * KM_TO_M; + case "mi" -> distanceNumber * MI_TO_M; + default -> throw new IllegalArgumentException("Invalid distance " + rawDistance); + }; } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid distance " + rawDistance); } diff --git a/src/main/java/com/yelp/nrtsearch/server/grpc/NrtsearchClient.java b/src/main/java/com/yelp/nrtsearch/server/grpc/NrtsearchClient.java index c9583d03c..c204b01f4 100644 --- a/src/main/java/com/yelp/nrtsearch/server/grpc/NrtsearchClient.java +++ b/src/main/java/com/yelp/nrtsearch/server/grpc/NrtsearchClient.java @@ -130,7 +130,7 @@ public void liveSettingsV2(LiveSettingsV2Request liveSettingsV2Request) { try { logger.info("Server returned : " + JsonFormat.printer().print(response.getLiveSettings())); } catch (Exception e) { - logger.info("Error printing response message: " + response, e); + logger.info("Error printing response message: {}", response, e); } } @@ -257,7 +257,7 @@ public void onCompleted() { } if (!exception.isEmpty()) { - throw new RuntimeException(exception.get(0)); + throw new RuntimeException(exception.getFirst()); } } diff --git a/src/main/java/com/yelp/nrtsearch/server/grpc/ReplicationServerClient.java b/src/main/java/com/yelp/nrtsearch/server/grpc/ReplicationServerClient.java index 594e88388..9882600f0 100644 --- a/src/main/java/com/yelp/nrtsearch/server/grpc/ReplicationServerClient.java +++ b/src/main/java/com/yelp/nrtsearch/server/grpc/ReplicationServerClient.java @@ -308,7 +308,6 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; ReplicationServerClient that = (ReplicationServerClient) o; return port == that.port - && Objects.equals(logger, that.logger) && Objects.equals(host, that.host) && Objects.equals(discoveryFile, that.discoveryFile) && Objects.equals(channel, that.channel) diff --git a/src/main/java/com/yelp/nrtsearch/server/handler/AddDocumentHandler.java b/src/main/java/com/yelp/nrtsearch/server/handler/AddDocumentHandler.java index 39032b631..3c3502184 100644 --- a/src/main/java/com/yelp/nrtsearch/server/handler/AddDocumentHandler.java +++ b/src/main/java/com/yelp/nrtsearch/server/handler/AddDocumentHandler.java @@ -61,12 +61,12 @@ public AddDocumentHandler(GlobalState globalState) { public StreamObserver handle( StreamObserver responseObserver) { return new StreamObserver<>() { - Multimap> futures = HashMultimap.create(); + final Multimap> futures = HashMultimap.create(); // Map of {indexName: addDocumentRequestQueue} - Map> addDocumentRequestQueueMap = + final Map> addDocumentRequestQueueMap = new ConcurrentHashMap<>(); // Map of {indexName: count} - Map countMap = new ConcurrentHashMap<>(); + final Map countMap = new ConcurrentHashMap<>(); private int getAddDocumentsMaxBufferLen(String indexName) { try { @@ -289,7 +289,7 @@ public static DocumentsContext getDocumentsContext( parseOneField(entry.getKey(), entry.getValue(), documentsContext, indexState); } - ((IndexableFieldDef) (IndexState.getMetaField(IndexState.NESTED_PATH))) + ((IndexableFieldDef) (IndexState.getMetaField(IndexState.NESTED_PATH))) .parseDocumentField( documentsContext.getRootDocument(), List.of(IndexState.ROOT), List.of()); @@ -308,8 +308,8 @@ private static void extractFieldNames(DocumentsContext documentsContext) { /** Extract all field names in the document and stores it into a hidden field */ private static void extractFieldNamesForDocument(Document document) { - IndexableFieldDef fieldNamesFieldDef = - (IndexableFieldDef) IndexState.getMetaField(IndexState.FIELD_NAMES); + IndexableFieldDef fieldNamesFieldDef = + (IndexableFieldDef) IndexState.getMetaField(IndexState.FIELD_NAMES); List fieldNames = document.getFields().stream() @@ -339,7 +339,9 @@ private static void parseMultiValueField( ProtocolStringList fieldValues = value.getValueList(); List facetHierarchyPaths = value.getFaceHierarchyPathsList(); List> facetHierarchyPathValues = - facetHierarchyPaths.stream().map(fp -> fp.getValueList()).collect(Collectors.toList()); + facetHierarchyPaths.stream() + .map(FacetHierarchyPath::getValueList) + .collect(Collectors.toList()); if (!facetHierarchyPathValues.isEmpty()) { if (facetHierarchyPathValues.size() != fieldValues.size()) { throw new AddDocumentHandlerException( @@ -350,11 +352,10 @@ private static void parseMultiValueField( field.getName(), fieldValues.size(), facetHierarchyPathValues.size())); } } - if (!(field instanceof IndexableFieldDef)) { + if (!(field instanceof IndexableFieldDef indexableFieldDef)) { throw new AddDocumentHandlerException( String.format("Field: %s is not indexable", field.getName())); } - IndexableFieldDef indexableFieldDef = (IndexableFieldDef) field; indexableFieldDef.parseFieldWithChildren( documentsContext, fieldValues, facetHierarchyPathValues); } @@ -476,9 +477,7 @@ private void updateNestedDocuments( List documents = new ArrayList<>(); for (Map.Entry> e : documentsContext.getChildDocuments().entrySet()) { documents.addAll( - e.getValue().stream() - .map(v -> handleFacets(indexState, shardState, v)) - .collect(Collectors.toList())); + e.getValue().stream().map(v -> handleFacets(indexState, shardState, v)).toList()); } Document rootDoc = handleFacets(indexState, shardState, documentsContext.getRootDocument()); @@ -505,9 +504,7 @@ private void addNestedDocuments( List documents = new ArrayList<>(); for (Map.Entry> e : documentsContext.getChildDocuments().entrySet()) { documents.addAll( - e.getValue().stream() - .map(v -> handleFacets(indexState, shardState, v)) - .collect(Collectors.toList())); + e.getValue().stream().map(v -> handleFacets(indexState, shardState, v)).toList()); } Document rootDoc = handleFacets(indexState, shardState, documentsContext.getRootDocument()); documents.add(rootDoc); diff --git a/src/main/java/com/yelp/nrtsearch/server/handler/CopyFilesHandler.java b/src/main/java/com/yelp/nrtsearch/server/handler/CopyFilesHandler.java index 58daa0573..582d288f1 100644 --- a/src/main/java/com/yelp/nrtsearch/server/handler/CopyFilesHandler.java +++ b/src/main/java/com/yelp/nrtsearch/server/handler/CopyFilesHandler.java @@ -89,7 +89,7 @@ private void handle( String indexName = copyFilesRequest.getIndexName(); ShardState shardState = indexState.getShard(0); - if (shardState.isReplica() == false) { + if (!shardState.isReplica()) { throw new IllegalArgumentException( "index \"" + indexName + "\" is not a replica or was not started yet"); } diff --git a/src/main/java/com/yelp/nrtsearch/server/handler/DeleteByQueryHandler.java b/src/main/java/com/yelp/nrtsearch/server/handler/DeleteByQueryHandler.java index 980fdac5c..ecf0b61bc 100644 --- a/src/main/java/com/yelp/nrtsearch/server/handler/DeleteByQueryHandler.java +++ b/src/main/java/com/yelp/nrtsearch/server/handler/DeleteByQueryHandler.java @@ -23,7 +23,6 @@ import com.yelp.nrtsearch.server.state.GlobalState; import java.io.IOException; import java.util.List; -import java.util.stream.Collectors; import org.apache.lucene.search.Query; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -53,7 +52,7 @@ private AddDocumentResponse handle( List queryList = deleteByQueryRequest.getQueryList().stream() .map(query -> queryNodeMapper.getQuery(query, indexState)) - .collect(Collectors.toList()); + .toList(); try { shardState.writer.deleteDocuments(queryList.toArray(new Query[] {})); } catch (IOException e) { diff --git a/src/main/java/com/yelp/nrtsearch/server/handler/DeleteDocumentsHandler.java b/src/main/java/com/yelp/nrtsearch/server/handler/DeleteDocumentsHandler.java index 687365f50..30a204713 100644 --- a/src/main/java/com/yelp/nrtsearch/server/handler/DeleteDocumentsHandler.java +++ b/src/main/java/com/yelp/nrtsearch/server/handler/DeleteDocumentsHandler.java @@ -64,7 +64,7 @@ private AddDocumentResponse handleInternal( } } try { - shardState.writer.deleteDocuments(terms.stream().toArray(Term[]::new)); + shardState.writer.deleteDocuments(terms.toArray(Term[]::new)); } catch (IOException e) { logger.warn( "ThreadId: {}, writer.deleteDocuments failed", diff --git a/src/main/java/com/yelp/nrtsearch/server/handler/NewNRTPointHandler.java b/src/main/java/com/yelp/nrtsearch/server/handler/NewNRTPointHandler.java index 5c8da8c78..0222f6c13 100644 --- a/src/main/java/com/yelp/nrtsearch/server/handler/NewNRTPointHandler.java +++ b/src/main/java/com/yelp/nrtsearch/server/handler/NewNRTPointHandler.java @@ -49,7 +49,7 @@ public TransferStatus handle(NewNRTPoint request) throws Exception { private TransferStatus handle(IndexState indexState, NewNRTPoint newNRTPointRequest) { ShardState shardState = indexState.getShard(0); - if (shardState.isReplica() == false) { + if (!shardState.isReplica()) { throw new IllegalArgumentException( "index \"" + newNRTPointRequest.getIndexName() diff --git a/src/main/java/com/yelp/nrtsearch/server/handler/RecvCopyStateHandler.java b/src/main/java/com/yelp/nrtsearch/server/handler/RecvCopyStateHandler.java index f9058ac97..ba6c00ba9 100644 --- a/src/main/java/com/yelp/nrtsearch/server/handler/RecvCopyStateHandler.java +++ b/src/main/java/com/yelp/nrtsearch/server/handler/RecvCopyStateHandler.java @@ -56,7 +56,7 @@ public CopyState handle(CopyStateRequest request) throws Exception { private CopyState handle(IndexState indexState, CopyStateRequest copyStateRequest) { ShardState shardState = indexState.getShard(0); - if (shardState.isPrimary() == false) { + if (!shardState.isPrimary()) { throw new IllegalArgumentException( "index \"" + indexState.getName() + "\" was not started or is not a primary"); } diff --git a/src/main/java/com/yelp/nrtsearch/server/handler/SearchHandler.java b/src/main/java/com/yelp/nrtsearch/server/handler/SearchHandler.java index 108171a18..9022beaa1 100644 --- a/src/main/java/com/yelp/nrtsearch/server/handler/SearchHandler.java +++ b/src/main/java/com/yelp/nrtsearch/server/handler/SearchHandler.java @@ -22,7 +22,6 @@ import com.yelp.nrtsearch.server.doc.LoadedDocValues; import com.yelp.nrtsearch.server.facet.DrillSidewaysImpl; import com.yelp.nrtsearch.server.facet.FacetTopDocs; -import com.yelp.nrtsearch.server.field.BooleanFieldDef; import com.yelp.nrtsearch.server.field.DateTimeFieldDef; import com.yelp.nrtsearch.server.field.FieldDef; import com.yelp.nrtsearch.server.field.IndexableFieldDef; @@ -751,11 +750,11 @@ private static SearcherTaxonomyManager.SearcherAndTaxonomy openSnapshotReader( public static class FillFieldsTask implements Callable>> { - private IndexSearcher s; - private List hitIdToleaves; - private List hitBuilders; - private List fields; - private SearchContext searchContext; + private final IndexSearcher s; + private final List hitIdToleaves; + private final List hitBuilders; + private final List fields; + private final SearchContext searchContext; public FillFieldsTask( IndexSearcher indexSearcher, @@ -810,60 +809,61 @@ private CompositeFieldValue getFieldForHit( // We detect invalid field above: assert fd != null; - if (fd instanceof VirtualFieldDef) { - VirtualFieldDef virtualFieldDef = (VirtualFieldDef) fd; - - int docID = hit.getLuceneDocId() - leaf.docBase; - - assert !Double.isNaN(hit.getScore()) || !virtualFieldDef.getValuesSource().needsScores(); - DoubleValues scoreValue = - new DoubleValues() { - @Override - public double doubleValue() throws IOException { - return hit.getScore(); - } - - @Override - public boolean advanceExact(int doc) throws IOException { - return !Double.isNaN(hit.getScore()); - } - }; - DoubleValues doubleValues = virtualFieldDef.getValuesSource().getValues(leaf, scoreValue); - doubleValues.advanceExact(docID); - compositeFieldValue.addFieldValue( - FieldValue.newBuilder().setDoubleValue(doubleValues.doubleValue())); - } else if (fd instanceof RuntimeFieldDef) { - RuntimeFieldDef runtimeFieldDef = (RuntimeFieldDef) fd; - RuntimeScript.SegmentFactory segmentFactory = runtimeFieldDef.getSegmentFactory(); - RuntimeScript values = segmentFactory.newInstance(leaf); - int docID = hit.getLuceneDocId() - leaf.docBase; - // Check if the value is available for the current document - if (values != null) { - values.setDocId(docID); - Object obj = values.execute(); - ObjectToCompositeFieldTransformer.enrichCompositeField(obj, compositeFieldValue); + switch (fd) { + case VirtualFieldDef virtualFieldDef -> { + int docID = hit.getLuceneDocId() - leaf.docBase; + + assert !Double.isNaN(hit.getScore()) || !virtualFieldDef.getValuesSource().needsScores(); + DoubleValues scoreValue = + new DoubleValues() { + @Override + public double doubleValue() throws IOException { + return hit.getScore(); + } + + @Override + public boolean advanceExact(int doc) throws IOException { + return !Double.isNaN(hit.getScore()); + } + }; + DoubleValues doubleValues = virtualFieldDef.getValuesSource().getValues(leaf, scoreValue); + doubleValues.advanceExact(docID); + compositeFieldValue.addFieldValue( + FieldValue.newBuilder().setDoubleValue(doubleValues.doubleValue())); } - - } else if (fd instanceof IndexableFieldDef && ((IndexableFieldDef) fd).hasDocValues()) { - int docID = hit.getLuceneDocId() - leaf.docBase; - // it may be possible to cache this if there are multiple hits in the same segment - LoadedDocValues docValues = ((IndexableFieldDef) fd).getDocValues(leaf); - docValues.setDocId(docID); - for (int i = 0; i < docValues.size(); ++i) { - compositeFieldValue.addFieldValue(docValues.toFieldValue(i)); + case RuntimeFieldDef runtimeFieldDef -> { + RuntimeScript.SegmentFactory segmentFactory = runtimeFieldDef.getSegmentFactory(); + RuntimeScript values = segmentFactory.newInstance(leaf); + int docID = hit.getLuceneDocId() - leaf.docBase; + // Check if the value is available for the current document + if (values != null) { + values.setDocId(docID); + Object obj = values.execute(); + ObjectToCompositeFieldTransformer.enrichCompositeField(obj, compositeFieldValue); + } + } + case IndexableFieldDef fieldDef when fieldDef.hasDocValues() -> { + int docID = hit.getLuceneDocId() - leaf.docBase; + // it may be possible to cache this if there are multiple hits in the same segment + LoadedDocValues docValues = fieldDef.getDocValues(leaf); + docValues.setDocId(docID); + for (int i = 0; i < docValues.size(); ++i) { + compositeFieldValue.addFieldValue(docValues.toFieldValue(i)); + } } - } - // retrieve stored fields - else if (fd instanceof IndexableFieldDef indexableFieldDef && indexableFieldDef.isStored()) { - IndexableField[] values = s.doc(hit.getLuceneDocId()).getFields(field); - for (IndexableField fieldValue : values) { - compositeFieldValue.addFieldValue( - indexableFieldDef.getStoredFieldValue(fieldValue.storedValue())); + // retrieve stored fields + case IndexableFieldDef indexableFieldDef when indexableFieldDef.isStored() -> { + IndexableField[] values = s.doc(hit.getLuceneDocId()).getFields(field); + for (IndexableField fieldValue : values) { + compositeFieldValue.addFieldValue( + indexableFieldDef.getStoredFieldValue(fieldValue.storedValue())); + } } - } else { - // TODO: throw exception here after confirming that legitimate requests do not enter this - logger.error("Unable to fill hit for field: {}", field); + default -> + // TODO: throw exception here after confirming that legitimate requests do not enter + // this + logger.error("Unable to fill hit for field: {}", field); } return compositeFieldValue.build(); @@ -952,31 +952,26 @@ private static void fetchSlice( LeafReaderContext sliceSegment) throws IOException { for (Map.Entry fieldDefEntry : context.getRetrieveFields().entrySet()) { - if (fieldDefEntry.getValue() instanceof VirtualFieldDef) { - fetchFromValueSource( - sliceHits, - sliceSegment, - fieldDefEntry.getKey(), - (VirtualFieldDef) fieldDefEntry.getValue()); - } else if (fieldDefEntry.getValue() instanceof RuntimeFieldDef) { - fetchRuntimeFromSegmentFactory( - sliceHits, - sliceSegment, - fieldDefEntry.getKey(), - (RuntimeFieldDef) fieldDefEntry.getValue()); - } else if (fieldDefEntry.getValue() instanceof IndexableFieldDef) { - IndexableFieldDef indexableFieldDef = (IndexableFieldDef) fieldDefEntry.getValue(); - if (indexableFieldDef.hasDocValues()) { - fetchFromDocVales(sliceHits, sliceSegment, fieldDefEntry.getKey(), indexableFieldDef); - } else if (indexableFieldDef.isStored()) { - fetchFromStored(context, sliceHits, fieldDefEntry.getKey(), indexableFieldDef); - } else { - throw new IllegalStateException( - "No valid method to retrieve indexable field: " + fieldDefEntry.getKey()); + switch (fieldDefEntry.getValue()) { + case VirtualFieldDef virtualFieldDef -> + fetchFromValueSource( + sliceHits, sliceSegment, fieldDefEntry.getKey(), virtualFieldDef); + case RuntimeFieldDef runtimeFieldDef -> + fetchRuntimeFromSegmentFactory( + sliceHits, sliceSegment, fieldDefEntry.getKey(), runtimeFieldDef); + case IndexableFieldDef indexableFieldDef -> { + if (indexableFieldDef.hasDocValues()) { + fetchFromDocVales(sliceHits, sliceSegment, fieldDefEntry.getKey(), indexableFieldDef); + } else if (indexableFieldDef.isStored()) { + fetchFromStored(context, sliceHits, fieldDefEntry.getKey(), indexableFieldDef); + } else { + throw new IllegalStateException( + "No valid method to retrieve indexable field: " + fieldDefEntry.getKey()); + } } - } else { - throw new IllegalStateException( - "No valid method to retrieve field: " + fieldDefEntry.getKey()); + case null, default -> + throw new IllegalStateException( + "No valid method to retrieve field: " + fieldDefEntry.getKey()); } } @@ -1053,7 +1048,7 @@ private static void fetchFromDocVales( List sliceHits, LeafReaderContext sliceSegment, String name, - IndexableFieldDef indexableFieldDef) + IndexableFieldDef indexableFieldDef) throws IOException { LoadedDocValues docValues = indexableFieldDef.getDocValues(sliceSegment); for (SearchResponse.Hit.Builder hit : sliceHits) { @@ -1074,7 +1069,7 @@ private static void fetchFromStored( FieldFetchContext context, List sliceHits, String name, - IndexableFieldDef indexableFieldDef) + IndexableFieldDef indexableFieldDef) throws IOException { for (SearchResponse.Hit.Builder hit : sliceHits) { SearchResponse.Hit.CompositeFieldValue.Builder compositeFieldValue = @@ -1112,24 +1107,6 @@ public void setScore(double score) { } } - private static FieldValue convertType(FieldDef fd, Object o) { - var fieldValue = FieldValue.newBuilder(); - if (fd instanceof BooleanFieldDef) { - if ((Integer) o == 1) { - fieldValue.setBooleanValue(Boolean.TRUE); - } else { - assert (Integer) o == 0; - fieldValue.setBooleanValue(Boolean.FALSE); - } - } else if (fd instanceof DateTimeFieldDef) { - fieldValue.setTextValue(msecToDateString(((DateTimeFieldDef) fd), ((Number) o).longValue())); - } else { - throw new IllegalArgumentException("Unable to convert object: " + o); - } - - return fieldValue.build(); - } - private static String msecToDateString(DateTimeFieldDef fd, long value) { // nocommit use CTL to reuse these? return fd.formatEpochMillis(value); diff --git a/src/main/java/com/yelp/nrtsearch/server/handler/StatsHandler.java b/src/main/java/com/yelp/nrtsearch/server/handler/StatsHandler.java index 69f10a3f2..0c9b8f6f1 100644 --- a/src/main/java/com/yelp/nrtsearch/server/handler/StatsHandler.java +++ b/src/main/java/com/yelp/nrtsearch/server/handler/StatsHandler.java @@ -73,9 +73,9 @@ public static StatsResponse process(IndexState indexState) throws IOException { } String[] fNames = shardState.indexDir.listAll(); long dirSize = 0; - for (int i = 0; i < fNames.length; i++) { + for (String fName : fNames) { try { - dirSize += shardState.indexDir.fileLength(fNames[i]); + dirSize += shardState.indexDir.fileLength(fName); } catch (IOException ignored) { // files may be deleted from merging, don't fail the request } @@ -118,8 +118,7 @@ public boolean doPrune(double ageSec, IndexSearcher indexSearcher) { searcher.setSegments(s.searcher.toString()); IndexReader indexReader = s.searcher.getIndexReader(); searcher.setNumDocs(indexReader.numDocs()); - if (indexReader instanceof StandardDirectoryReader) { - StandardDirectoryReader standardDirectoryReader = (StandardDirectoryReader) indexReader; + if (indexReader instanceof StandardDirectoryReader standardDirectoryReader) { searcher.setNumSegments(standardDirectoryReader.getSegmentInfos().asList().size()); } } diff --git a/src/main/java/com/yelp/nrtsearch/server/handler/WriteNRTPointHandler.java b/src/main/java/com/yelp/nrtsearch/server/handler/WriteNRTPointHandler.java index 8c52a2404..18ee38f3c 100644 --- a/src/main/java/com/yelp/nrtsearch/server/handler/WriteNRTPointHandler.java +++ b/src/main/java/com/yelp/nrtsearch/server/handler/WriteNRTPointHandler.java @@ -53,7 +53,7 @@ public SearcherVersion handle(IndexName indexNameRequest) throws Exception { private SearcherVersion handle(IndexState indexState, String indexId) { final ShardState shardState = indexState.getShard(0); - if (shardState.isPrimary() == false) { + if (!shardState.isPrimary()) { throw new IllegalArgumentException( "index \"" + indexState.getName() + "\" is either not started or is not a primary index"); } diff --git a/src/main/java/com/yelp/nrtsearch/server/highlights/HighlightUtils.java b/src/main/java/com/yelp/nrtsearch/server/highlights/HighlightUtils.java index 9c11bfc27..2b70194df 100644 --- a/src/main/java/com/yelp/nrtsearch/server/highlights/HighlightUtils.java +++ b/src/main/java/com/yelp/nrtsearch/server/highlights/HighlightUtils.java @@ -36,7 +36,7 @@ public class HighlightUtils { private static final int DEFAULT_FRAGMENT_SIZE = 100; // In number of characters private static final int DEFAULT_MAX_NUM_FRAGMENTS = 5; - private static String DEFAULT_HIGHLIGHTER_NAME = NRTFastVectorHighlighter.HIGHLIGHTER_NAME; + private static final String DEFAULT_HIGHLIGHTER_NAME = NRTFastVectorHighlighter.HIGHLIGHTER_NAME; private static final String DEFAULT_FRAGMENTER = "span"; private static final boolean DEFAULT_SCORE_ORDERED = true; private static final boolean DEFAULT_FIELD_MATCH = false; @@ -203,7 +203,7 @@ private static HighlightSettings createGlobalFieldSettings( .withCustomHighlighterParams( settings.hasCustomHighlighterParams() ? StructValueTransformer.transformStruct(settings.getCustomHighlighterParams()) - : Collections.EMPTY_MAP); + : Map.of()); Query query = settings.hasHighlightQuery() @@ -215,21 +215,19 @@ private static HighlightSettings createGlobalFieldSettings( } private static String resolveHighlighterName(Settings settings) { - switch (settings.getHighlighterType()) { - case DEFAULT: - /* default -> default-highlighter is only applicable in global settings. - * In field override, we should return the one in global settings instead. - */ - return DEFAULT_HIGHLIGHTER_NAME; - case PLAIN: - throw new UnsupportedOperationException("plain-highlighter is not supported yet."); - case FAST_VECTOR: - return NRTFastVectorHighlighter.HIGHLIGHTER_NAME; - case CUSTOM: - return settings.getCustomHighlighterName(); - default: - throw new IllegalArgumentException( - String.format("Unknown highlighter_type: %s", settings.getHighlighterType())); - } + return switch (settings.getHighlighterType()) { + case DEFAULT -> + /* default -> default-highlighter is only applicable in global settings. + * In field override, we should return the one in global settings instead. + */ + DEFAULT_HIGHLIGHTER_NAME; + case PLAIN -> + throw new UnsupportedOperationException("plain-highlighter is not supported yet."); + case FAST_VECTOR -> NRTFastVectorHighlighter.HIGHLIGHTER_NAME; + case CUSTOM -> settings.getCustomHighlighterName(); + default -> + throw new IllegalArgumentException( + String.format("Unknown highlighter_type: %s", settings.getHighlighterType())); + }; } } diff --git a/src/main/java/com/yelp/nrtsearch/server/highlights/HighlighterService.java b/src/main/java/com/yelp/nrtsearch/server/highlights/HighlighterService.java index 021086abb..2c7a51c34 100644 --- a/src/main/java/com/yelp/nrtsearch/server/highlights/HighlighterService.java +++ b/src/main/java/com/yelp/nrtsearch/server/highlights/HighlighterService.java @@ -62,8 +62,7 @@ public static void initialize(NrtsearchConfig configuration, Iterable pl instance = new HighlighterService(configuration); initializeBuiltinHighlighters(); for (Plugin plugin : plugins) { - if (plugin instanceof HighlighterPlugin) { - HighlighterPlugin highlighterPlugin = (HighlighterPlugin) plugin; + if (plugin instanceof HighlighterPlugin highlighterPlugin) { instance.register(highlighterPlugin.getHighlighters()); } } diff --git a/src/main/java/com/yelp/nrtsearch/server/index/BucketedTieredMergePolicy.java b/src/main/java/com/yelp/nrtsearch/server/index/BucketedTieredMergePolicy.java index 53de63436..365585a73 100644 --- a/src/main/java/com/yelp/nrtsearch/server/index/BucketedTieredMergePolicy.java +++ b/src/main/java/com/yelp/nrtsearch/server/index/BucketedTieredMergePolicy.java @@ -220,7 +220,7 @@ MergePolicy.MergeSpecification findForSegmentInfos( } } } - if (aggregateMerges.merges.size() > 0) { + if (!aggregateMerges.merges.isEmpty()) { return aggregateMerges; } else { return null; diff --git a/src/main/java/com/yelp/nrtsearch/server/index/DirectoryFactory.java b/src/main/java/com/yelp/nrtsearch/server/index/DirectoryFactory.java index 3a858fdf5..f786f5131 100644 --- a/src/main/java/com/yelp/nrtsearch/server/index/DirectoryFactory.java +++ b/src/main/java/com/yelp/nrtsearch/server/index/DirectoryFactory.java @@ -55,80 +55,87 @@ public DirectoryFactory() {} * NIOFSDirectory}. */ public static DirectoryFactory get(final String dirImpl, NrtsearchConfig config) { - if (dirImpl.equals("FSDirectory")) { - return new DirectoryFactory() { - @Override - public Directory open(Path path, IndexPreloadConfig preloadConfig) throws IOException { - Directory directory = FSDirectory.open(path); - if (directory instanceof MMapDirectory mMapDirectory) { + switch (dirImpl) { + case "FSDirectory" -> { + return new DirectoryFactory() { + @Override + public Directory open(Path path, IndexPreloadConfig preloadConfig) throws IOException { + Directory directory = FSDirectory.open(path); + if (directory instanceof MMapDirectory mMapDirectory) { + mMapDirectory.setPreload(preloadConfig.preloadPredicate()); + setMMapGrouping(mMapDirectory, config.getMMapGrouping()); + } + return directory; + } + }; + } + case "MMapDirectory" -> { + return new DirectoryFactory() { + @Override + public Directory open(Path path, IndexPreloadConfig preloadConfig) throws IOException { + MMapDirectory mMapDirectory = new MMapDirectory(path); mMapDirectory.setPreload(preloadConfig.preloadPredicate()); setMMapGrouping(mMapDirectory, config.getMMapGrouping()); + return mMapDirectory; + } + }; + } + case "NIOFSDirectory" -> { + return new DirectoryFactory() { + @Override + public Directory open(Path path, IndexPreloadConfig preloadConfig) throws IOException { + return new NIOFSDirectory(path); } - return directory; + }; + } + default -> { + final Class dirClass; + try { + dirClass = Class.forName(dirImpl).asSubclass(Directory.class); + } catch (ClassNotFoundException cnfe) { + throw new IllegalArgumentException( + "could not locate Directory sub-class \"" + dirImpl + "\"; verify CLASSPATH"); } - }; - } else if (dirImpl.equals("MMapDirectory")) { - return new DirectoryFactory() { - @Override - public Directory open(Path path, IndexPreloadConfig preloadConfig) throws IOException { - MMapDirectory mMapDirectory = new MMapDirectory(path); - mMapDirectory.setPreload(preloadConfig.preloadPredicate()); - setMMapGrouping(mMapDirectory, config.getMMapGrouping()); - return mMapDirectory; + Constructor ctor = null; + try { + ctor = dirClass.getConstructor(Path.class); + } catch (NoSuchMethodException ignored) { } - }; - } else if (dirImpl.equals("NIOFSDirectory")) { - return new DirectoryFactory() { - @Override - public Directory open(Path path, IndexPreloadConfig preloadConfig) throws IOException { - return new NIOFSDirectory(path); + try { + ctor = dirClass.getConstructor(Path.class, IndexPreloadConfig.class); + } catch (NoSuchMethodException ignored) { + } + if (ctor == null) { + throw new IllegalArgumentException( + "class \"" + + dirImpl + + "\" does not have a constructor taking a single Path argument, or a Path and a boolean"); } - }; - } else { - final Class dirClass; - try { - dirClass = Class.forName(dirImpl).asSubclass(Directory.class); - } catch (ClassNotFoundException cnfe) { - throw new IllegalArgumentException( - "could not locate Directory sub-class \"" + dirImpl + "\"; verify CLASSPATH"); - } - Constructor ctor = null; - try { - ctor = dirClass.getConstructor(Path.class); - } catch (NoSuchMethodException ignored) { - } - try { - ctor = dirClass.getConstructor(Path.class, IndexPreloadConfig.class); - } catch (NoSuchMethodException ignored) { - } - if (ctor == null) { - throw new IllegalArgumentException( - "class \"" - + dirImpl - + "\" does not have a constructor taking a single Path argument, or a Path and a boolean"); - } - final Constructor finalCtor = ctor; - return new DirectoryFactory() { - @Override - public Directory open(Path path, IndexPreloadConfig preloadConfig) throws IOException { - try { - if (finalCtor.getParameterCount() == 1) { - return finalCtor.newInstance(path); - } else { - return finalCtor.newInstance(path, preloadConfig); + final Constructor finalCtor = ctor; + return new DirectoryFactory() { + @Override + public Directory open(Path path, IndexPreloadConfig preloadConfig) throws IOException { + try { + if (finalCtor.getParameterCount() == 1) { + return finalCtor.newInstance(path); + } else { + return finalCtor.newInstance(path, preloadConfig); + } + } catch (InstantiationException + | InvocationTargetException + | IllegalAccessException ie) { + throw new RuntimeException( + "failed to instantiate directory class \"" + + dirImpl + + "\" on path=\"" + + path + + "\"", + ie); } - } catch (InstantiationException | InvocationTargetException | IllegalAccessException ie) { - throw new RuntimeException( - "failed to instantiate directory class \"" - + dirImpl - + "\" on path=\"" - + path - + "\"", - ie); } - } - }; + }; + } } } diff --git a/src/main/java/com/yelp/nrtsearch/server/index/FieldAndFacetState.java b/src/main/java/com/yelp/nrtsearch/server/index/FieldAndFacetState.java index 360ddafe4..96c16c137 100644 --- a/src/main/java/com/yelp/nrtsearch/server/index/FieldAndFacetState.java +++ b/src/main/java/com/yelp/nrtsearch/server/index/FieldAndFacetState.java @@ -216,9 +216,8 @@ public Builder addField(FieldDef fieldDef, Field field) { private void setFacetsConfigForField(FieldDef fieldDef, Field field) { // facets not supported for child fields - if (field != null && fieldDef instanceof IndexableFieldDef) { + if (field != null && fieldDef instanceof IndexableFieldDef indexableFieldDef) { String fieldName = fieldDef.getName(); - IndexableFieldDef indexableFieldDef = (IndexableFieldDef) fieldDef; IndexableFieldDef.FacetValueType facetType = indexableFieldDef.getFacetValueType(); if (facetType != IndexableFieldDef.FacetValueType.NO_FACETS && facetType != IndexableFieldDef.FacetValueType.NUMERIC_RANGE) { diff --git a/src/main/java/com/yelp/nrtsearch/server/index/IndexSimilarity.java b/src/main/java/com/yelp/nrtsearch/server/index/IndexSimilarity.java index d107799b8..2bf01020c 100644 --- a/src/main/java/com/yelp/nrtsearch/server/index/IndexSimilarity.java +++ b/src/main/java/com/yelp/nrtsearch/server/index/IndexSimilarity.java @@ -52,7 +52,7 @@ public static Similarity getFromState(String name, IndexState indexState) { try { FieldDef fd = indexState.getFieldOrThrow(name); if (fd instanceof IndexableFieldDef) { - return ((IndexableFieldDef) fd).getSimilarity(); + return ((IndexableFieldDef) fd).getSimilarity(); } } catch (IllegalArgumentException ignored) { // ReplicaNode tries to do a Term query for a field called 'marker' diff --git a/src/main/java/com/yelp/nrtsearch/server/index/IndexState.java b/src/main/java/com/yelp/nrtsearch/server/index/IndexState.java index ba1663b30..a92e5acf0 100644 --- a/src/main/java/com/yelp/nrtsearch/server/index/IndexState.java +++ b/src/main/java/com/yelp/nrtsearch/server/index/IndexState.java @@ -131,12 +131,6 @@ public Analyzer getWrappedAnalyzer(String name) { } throw new IllegalArgumentException("field \"" + name + "\" does not support analysis"); } - - @Override - protected TokenStreamComponents wrapComponents( - String fieldName, TokenStreamComponents components) { - return components; - } }; /** Per-field wrapper that provides the similarity for searcher */ @@ -313,7 +307,7 @@ public void verifyStarted() { * @throws IllegalArgumentException if the non-root path is invalid */ public String resolveQueryNestedPath(String path) { - if (path == null || path.length() == 0 || path.equals(IndexState.ROOT)) { + if (path == null || path.isEmpty() || path.equals(IndexState.ROOT)) { return IndexState.ROOT; } FieldDef fieldDef = getFieldOrThrow(path); diff --git a/src/main/java/com/yelp/nrtsearch/server/index/ShardState.java b/src/main/java/com/yelp/nrtsearch/server/index/ShardState.java index 492f417dd..82539aa6c 100644 --- a/src/main/java/com/yelp/nrtsearch/server/index/ShardState.java +++ b/src/main/java/com/yelp/nrtsearch/server/index/ShardState.java @@ -583,7 +583,7 @@ public synchronized void start(NrtDataManager nrtDataManager) throws IOException // nocommit don't allow RAMDir // nocommit remove NRTCachingDir too? - if ((origIndexDir instanceof MMapDirectory) == false) { + if (!(origIndexDir instanceof MMapDirectory)) { double maxMergeSizeMB = indexState.getNrtCachingDirectoryMaxMergeSizeMB(); double maxSizeMB = indexState.getNrtCachingDirectoryMaxSizeMB(); if (maxMergeSizeMB > 0 && maxSizeMB > 0) { @@ -609,12 +609,7 @@ public synchronized void start(NrtDataManager nrtDataManager) throws IOException openMode = IndexWriterConfig.OpenMode.APPEND; } - Path taxoDirFile; - if (rootDir == null) { - taxoDirFile = null; - } else { - taxoDirFile = rootDir.resolve(TAXONOMY_DATA_DIR_NAME); - } + Path taxoDirFile = rootDir.resolve(TAXONOMY_DATA_DIR_NAME); taxoDir = indexState .getDirectoryFactory() @@ -718,7 +713,7 @@ public synchronized void startPrimary(NrtDataManager nrtDataManager, long primar .open( indexDirFile, indexState.getGlobalState().getConfiguration().getPreloadConfig()); - if ((origIndexDir instanceof MMapDirectory) == false) { + if (!(origIndexDir instanceof MMapDirectory)) { double maxMergeSizeMB = indexState.getNrtCachingDirectoryMaxMergeSizeMB(); double maxSizeMB = indexState.getNrtCachingDirectoryMaxSizeMB(); if (maxMergeSizeMB > 0 && maxSizeMB > 0) { @@ -952,7 +947,7 @@ public synchronized void startReplica( indexState.getDirectoryFactory().open(indexDirFile, configuration.getPreloadConfig()); // nocommit don't allow RAMDir // nocommit remove NRTCachingDir too? - if ((origIndexDir instanceof MMapDirectory) == false) { + if (!(origIndexDir instanceof MMapDirectory)) { double maxMergeSizeMB = indexState.getNrtCachingDirectoryMaxMergeSizeMB(); double maxSizeMB = indexState.getNrtCachingDirectoryMaxSizeMB(); if (maxMergeSizeMB > 0 && maxSizeMB > 0) { diff --git a/src/main/java/com/yelp/nrtsearch/server/innerhit/InnerHitContext.java b/src/main/java/com/yelp/nrtsearch/server/innerhit/InnerHitContext.java index 87fb02789..d2706aa8e 100644 --- a/src/main/java/com/yelp/nrtsearch/server/innerhit/InnerHitContext.java +++ b/src/main/java/com/yelp/nrtsearch/server/innerhit/InnerHitContext.java @@ -27,7 +27,7 @@ import com.yelp.nrtsearch.server.search.SearchContext; import com.yelp.nrtsearch.server.search.sort.SortContext; import java.io.IOException; -import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.Objects; import org.apache.lucene.facet.taxonomy.SearcherTaxonomyManager; @@ -61,7 +61,7 @@ public class InnerHitContext implements FieldFetchContext { private final Map retrieveFields; private final SortContext sortContext; - private final CollectorManager + private final CollectorManager, ? extends TopDocs> topDocsCollectorManager; private final FetchTasks fetchTasks; private SearchContext searchContext = null; @@ -86,8 +86,7 @@ private InnerHitContext(InnerHitContextBuilder builder, boolean needValidation) this.queryFields = builder.queryFields; this.retrieveFields = builder.retrieveFields; this.explain = builder.explain; - this.fetchTasks = - new FetchTasks(Collections.EMPTY_LIST, builder.highlightFetchTask, null, null); + this.fetchTasks = new FetchTasks(List.of(), builder.highlightFetchTask, null, null); if (builder.querySort == null) { // relevance collector @@ -235,7 +234,7 @@ public SortContext getSortContext() { } /** Get the topDocsCollectorManager to collect the search results. */ - public CollectorManager + public CollectorManager, ? extends TopDocs> getTopDocsCollectorManager() { return topDocsCollectorManager; } diff --git a/src/main/java/com/yelp/nrtsearch/server/innerhit/InnerHitFetchTask.java b/src/main/java/com/yelp/nrtsearch/server/innerhit/InnerHitFetchTask.java index 1f2834707..782a1e8bd 100644 --- a/src/main/java/com/yelp/nrtsearch/server/innerhit/InnerHitFetchTask.java +++ b/src/main/java/com/yelp/nrtsearch/server/innerhit/InnerHitFetchTask.java @@ -107,7 +107,8 @@ public void processHit( parentChildrenBlockJoinQuery.createWeight(searcher, ScoreMode.COMPLETE_NO_SCORES, 1f); // All child documents are guaranteed to be stored in the same leaf as the parent document. // Therefore, a single collector without reduce is sufficient to collect all. - TopDocsCollector topDocsCollector = innerHitContext.getTopDocsCollectorManager().newCollector(); + TopDocsCollector topDocsCollector = + innerHitContext.getTopDocsCollectorManager().newCollector(); intersectWeights(filterWeight, innerHitWeight, topDocsCollector, hitLeaf); TopDocs topDocs = topDocsCollector.topDocs(); @@ -156,7 +157,7 @@ public void processHit( private void intersectWeights( Weight filterWeight, Weight innerHitWeight, - TopDocsCollector topDocsCollector, + TopDocsCollector topDocsCollector, LeafReaderContext hitLeaf) throws IOException { ScorerSupplier filterScorerSupplier = filterWeight.scorerSupplier(hitLeaf); diff --git a/src/main/java/com/yelp/nrtsearch/server/monitoring/IndexMetrics.java b/src/main/java/com/yelp/nrtsearch/server/monitoring/IndexMetrics.java index 709b8a55b..b149c587f 100644 --- a/src/main/java/com/yelp/nrtsearch/server/monitoring/IndexMetrics.java +++ b/src/main/java/com/yelp/nrtsearch/server/monitoring/IndexMetrics.java @@ -92,17 +92,15 @@ public static void updateReaderStats(String index, IndexReader reader) { numDeletedDocs.labelValues(index).set(reader.numDeletedDocs()); numSegments.labelValues(index).set(reader.leaves().size()); - if (reader.leaves().size() > 0) { + if (!reader.leaves().isEmpty()) { ArrayList sortedLeaves = new ArrayList<>(reader.leaves()); // sort by segment size sortedLeaves.sort(Comparator.comparingInt(l -> l.reader().maxDoc())); - segmentDocs.labelValues(index, "min").set(sortedLeaves.get(0).reader().maxDoc()); + segmentDocs.labelValues(index, "min").set(sortedLeaves.getFirst().reader().maxDoc()); segmentDocs.labelValues(index, "0.5").set(getSegmentDocsQuantile(0.5, sortedLeaves)); segmentDocs.labelValues(index, "0.95").set(getSegmentDocsQuantile(0.95, sortedLeaves)); segmentDocs.labelValues(index, "0.99").set(getSegmentDocsQuantile(0.99, sortedLeaves)); - segmentDocs - .labelValues(index, "max") - .set(sortedLeaves.get(sortedLeaves.size() - 1).reader().maxDoc()); + segmentDocs.labelValues(index, "max").set(sortedLeaves.getLast().reader().maxDoc()); try { // This type assumption is the same made by the nrt PrimaryNode class diff --git a/src/main/java/com/yelp/nrtsearch/server/monitoring/NrtsearchMonitoringServerInterceptor.java b/src/main/java/com/yelp/nrtsearch/server/monitoring/NrtsearchMonitoringServerInterceptor.java index 61587614a..cbdca4009 100644 --- a/src/main/java/com/yelp/nrtsearch/server/monitoring/NrtsearchMonitoringServerInterceptor.java +++ b/src/main/java/com/yelp/nrtsearch/server/monitoring/NrtsearchMonitoringServerInterceptor.java @@ -49,7 +49,7 @@ public ServerCall.Listener interceptCall( com.yelp.nrtsearch.server.monitoring.GrpcMethod grpcMethod = com.yelp.nrtsearch.server.monitoring.GrpcMethod.of(method); ServerCall monitoringCall = - new MonitoringServerCall(call, clock, grpcMethod, metrics, configuration); + new MonitoringServerCall<>(call, clock, grpcMethod, metrics, configuration); return new MonitoringServerCallListener<>( next.startCall(monitoringCall, requestHeaders), metrics, diff --git a/src/main/java/com/yelp/nrtsearch/server/monitoring/ServerMetrics.java b/src/main/java/com/yelp/nrtsearch/server/monitoring/ServerMetrics.java index 1a9d606af..642fa44b0 100644 --- a/src/main/java/com/yelp/nrtsearch/server/monitoring/ServerMetrics.java +++ b/src/main/java/com/yelp/nrtsearch/server/monitoring/ServerMetrics.java @@ -110,7 +110,7 @@ public void recordStreamMessageReceived() { * does nothing. */ public void recordLatency(double latencySec) { - if (!this.serverHandledLatencySeconds.isPresent()) { + if (this.serverHandledLatencySeconds.isEmpty()) { return; } addLabels(this.serverHandledLatencySeconds.get()).observe(latencySec); diff --git a/src/main/java/com/yelp/nrtsearch/server/nrt/NRTPrimaryNode.java b/src/main/java/com/yelp/nrtsearch/server/nrt/NRTPrimaryNode.java index 659560a2e..d39c7ef00 100644 --- a/src/main/java/com/yelp/nrtsearch/server/nrt/NRTPrimaryNode.java +++ b/src/main/java/com/yelp/nrtsearch/server/nrt/NRTPrimaryNode.java @@ -372,7 +372,7 @@ protected void preCopyMergedSegmentFiles( // TODO: maybe ... place some sort of time limit on how long we are willing to wait for slow // replica(s) to finish copying? - while (preCopy.finished() == false) { + while (!preCopy.finished()) { try { Thread.sleep(10); } catch (InterruptedException ie) { diff --git a/src/main/java/com/yelp/nrtsearch/server/nrt/NRTReplicaNode.java b/src/main/java/com/yelp/nrtsearch/server/nrt/NRTReplicaNode.java index fb8c61708..88b6f299f 100644 --- a/src/main/java/com/yelp/nrtsearch/server/nrt/NRTReplicaNode.java +++ b/src/main/java/com/yelp/nrtsearch/server/nrt/NRTReplicaNode.java @@ -194,13 +194,7 @@ private static CopyState readCopyState(com.yelp.nrtsearch.server.grpc.CopyState long version = copyState.getVersion(); Map files = readFilesMetaData(copyState.getFilesMetadata()); - int count = copyState.getCompletedMergeFilesCount(); - assert count == copyState.getCompletedMergeFilesCount(); - - Set completedMergeFiles = new HashSet<>(); - for (String completedMergeFile : copyState.getCompletedMergeFilesList()) { - completedMergeFiles.add(completedMergeFile); - } + Set completedMergeFiles = new HashSet<>(copyState.getCompletedMergeFilesList()); long primaryGen = copyState.getPrimaryGen(); return new CopyState(files, version, gen, infosBytes, completedMergeFiles, primaryGen, null); diff --git a/src/main/java/com/yelp/nrtsearch/server/nrt/NrtCopyThread.java b/src/main/java/com/yelp/nrtsearch/server/nrt/NrtCopyThread.java index 2aee28c35..325871def 100644 --- a/src/main/java/com/yelp/nrtsearch/server/nrt/NrtCopyThread.java +++ b/src/main/java/com/yelp/nrtsearch/server/nrt/NrtCopyThread.java @@ -91,13 +91,11 @@ public void run() { this.setName("jobs o" + topJob.ord); - assert topJob != null; - boolean result; try { result = topJob.visit(); } catch (Throwable t) { - if ((t instanceof AlreadyClosedException) == false) { + if (!(t instanceof AlreadyClosedException)) { logWarning("exception during job.visit job=" + topJob + "; now cancel", t); } else { @@ -116,7 +114,7 @@ public void run() { continue; } - if (result == false) { + if (!result) { // Job isn't done yet; put it back: synchronized (this) { addJob(topJob); @@ -161,7 +159,7 @@ public void run() { } public synchronized void launch(CopyJob job) { - if (finish == false) { + if (!finish) { addJob(job); notify(); } else { diff --git a/src/main/java/com/yelp/nrtsearch/server/nrt/SimpleCopyJob.java b/src/main/java/com/yelp/nrtsearch/server/nrt/SimpleCopyJob.java index c634ce32c..3aa8feb99 100644 --- a/src/main/java/com/yelp/nrtsearch/server/nrt/SimpleCopyJob.java +++ b/src/main/java/com/yelp/nrtsearch/server/nrt/SimpleCopyJob.java @@ -105,7 +105,7 @@ public void start() throws IOException { @Override public void runBlocking() throws Exception { - while (visit() == false) + while (!visit()) ; if (getFailed()) { throw new RuntimeException("copy failed: " + cancelReason, exc); @@ -220,7 +220,7 @@ public synchronized boolean visit() throws IOException { return true; } if (current == null) { - if (iter.hasNext() == false) { + if (!iter.hasNext()) { return true; } Map.Entry next = iter.next(); diff --git a/src/main/java/com/yelp/nrtsearch/server/plugins/PluginMetadata.java b/src/main/java/com/yelp/nrtsearch/server/plugins/PluginMetadata.java index 525ad9f4e..7752e6840 100644 --- a/src/main/java/com/yelp/nrtsearch/server/plugins/PluginMetadata.java +++ b/src/main/java/com/yelp/nrtsearch/server/plugins/PluginMetadata.java @@ -71,10 +71,9 @@ static PluginMetadata fromInstallDir(File pluginDir) { static PluginMetadata fromInputStream(InputStream fileStream) { Yaml yaml = new Yaml(); Object configObject = yaml.load(fileStream); - if (!(configObject instanceof Map)) { + if (!(configObject instanceof Map configMap)) { throw new IllegalArgumentException("Plugin metadata must be a yaml hash"); } - Map configMap = (Map) configObject; String name = getConfigString(configMap, NAME); String version = getConfigString(configMap, VERSION); String description = getConfigString(configMap, DESCRIPTION); @@ -98,7 +97,7 @@ static File getMetadataFile(File pluginDir) throws FileNotFoundException { throw new FileNotFoundException("No metadata file for plugin"); } - private static String getConfigString(Map configMap, String key) { + private static String getConfigString(Map configMap, String key) { if (!configMap.containsKey(key) || configMap.get(key) == null) { throw new IllegalArgumentException("Plugin config missing key: " + key); } @@ -134,12 +133,19 @@ public String getDescription() { @Override public String toString() { - final StringBuilder sb = new StringBuilder("PluginMetadata{"); - sb.append("name='").append(name).append("'"); - sb.append(", classname='").append(classname).append("'"); - sb.append(", version='").append(version).append("'"); - sb.append(", description='").append(description).append("'"); - sb.append('}'); - return sb.toString(); + return "PluginMetadata{" + + "name='" + + name + + "'" + + ", classname='" + + classname + + "'" + + ", version='" + + version + + "'" + + ", description='" + + description + + "'" + + '}'; } } diff --git a/src/main/java/com/yelp/nrtsearch/server/plugins/PluginsService.java b/src/main/java/com/yelp/nrtsearch/server/plugins/PluginsService.java index af4b2d294..2baf0e4ee 100644 --- a/src/main/java/com/yelp/nrtsearch/server/plugins/PluginsService.java +++ b/src/main/java/com/yelp/nrtsearch/server/plugins/PluginsService.java @@ -116,7 +116,7 @@ List getPluginSearchPath() { */ PluginDescriptor loadPlugin( String pluginName, List searchPath, PluginDownloader pluginDownloader) { - Path defaultSearchPath = searchPath.get(0).toPath(); + Path defaultSearchPath = searchPath.getFirst().toPath(); pluginName = pluginDownloader.downloadPluginIfNeeded(pluginName, defaultSearchPath); File pluginInstallDir = findPluginInstallDir(pluginName, searchPath); diff --git a/src/main/java/com/yelp/nrtsearch/server/query/BlendedTermQuery.java b/src/main/java/com/yelp/nrtsearch/server/query/BlendedTermQuery.java index 95c825d87..2e0b74262 100644 --- a/src/main/java/com/yelp/nrtsearch/server/query/BlendedTermQuery.java +++ b/src/main/java/com/yelp/nrtsearch/server/query/BlendedTermQuery.java @@ -255,14 +255,14 @@ public String toString(String field) { public void visit(QueryVisitor visitor) { Set fields = Arrays.stream(terms).map(Term::field).collect(Collectors.toSet()); for (String field : fields) { - if (visitor.acceptField(field) == false) { + if (!visitor.acceptField(field)) { return; } } visitor.getSubVisitor(BooleanClause.Occur.SHOULD, this).consumeTerms(this, terms); } - private class TermAndBoost implements Comparable { + private static class TermAndBoost implements Comparable { protected final Term term; protected float boost; @@ -285,11 +285,10 @@ public boolean equals(Object o) { if (this == o) { return true; } - if (o instanceof TermAndBoost == false) { + if (!(o instanceof TermAndBoost that)) { return false; } - TermAndBoost that = (TermAndBoost) o; return term.equals(that.term) && (Float.compare(boost, that.boost) == 0); } @@ -326,7 +325,7 @@ public boolean equals(Object o) { if (this == o) { return true; } - if (sameClassAs(o) == false) { + if (!sameClassAs(o)) { return false; } diff --git a/src/main/java/com/yelp/nrtsearch/server/query/MatchCrossFieldsQuery.java b/src/main/java/com/yelp/nrtsearch/server/query/MatchCrossFieldsQuery.java index befd1b685..7ec0a7307 100644 --- a/src/main/java/com/yelp/nrtsearch/server/query/MatchCrossFieldsQuery.java +++ b/src/main/java/com/yelp/nrtsearch/server/query/MatchCrossFieldsQuery.java @@ -68,12 +68,13 @@ public static Query build( try { // use first field for name in extracted terms QueryUtils.TermsAndPositions termsAndPositions = - QueryUtils.getTermsAndPositions(fields.get(0), queryText, analyzer); + QueryUtils.getTermsAndPositions(fields.getFirst(), queryText, analyzer); Query query; if (fields.size() == 1) { - query = buildSingleFieldQuery(termsAndPositions, fields.get(0), occur, minimumShouldMatch); + query = + buildSingleFieldQuery(termsAndPositions, fields.getFirst(), occur, minimumShouldMatch); // Add field boost if specified - Float boost = fieldBoostMap.get(fields.get(0)); + Float boost = fieldBoostMap.get(fields.getFirst()); if (query != null && boost != null) { query = new BoostQuery(query, boost); } @@ -116,13 +117,13 @@ private static Query buildSingleFieldQuery( } if (termsAndPositions.getTermArrays().size() == 1 - && termsAndPositions.getTermArrays().get(0).length == 1) { + && termsAndPositions.getTermArrays().getFirst().length == 1) { // single token - return new TermQuery(termsAndPositions.getTermArrays().get(0)[0]); + return new TermQuery(termsAndPositions.getTermArrays().getFirst()[0]); } else if (termsAndPositions.getPositions().size() == 1) { // synonyms for single position SynonymQuery.Builder builder = new SynonymQuery.Builder(field); - for (Term term : termsAndPositions.getTermArrays().get(0)) { + for (Term term : termsAndPositions.getTermArrays().getFirst()) { builder.addTerm(term); } return builder.build(); @@ -174,7 +175,10 @@ private static Query buildMultiFieldQuery( if (termsAndPositions.getTermArrays().size() == 1) { // single position return blendTerms( - termsAndPositions.getTermArrays().get(0), fields, fieldBoostMap, tieBreakerMultiplier); + termsAndPositions.getTermArrays().getFirst(), + fields, + fieldBoostMap, + tieBreakerMultiplier); } else { // multiple positions BooleanQuery.Builder builder = new Builder(); diff --git a/src/main/java/com/yelp/nrtsearch/server/query/MatchPhrasePrefixQuery.java b/src/main/java/com/yelp/nrtsearch/server/query/MatchPhrasePrefixQuery.java index cc9134487..608459300 100644 --- a/src/main/java/com/yelp/nrtsearch/server/query/MatchPhrasePrefixQuery.java +++ b/src/main/java/com/yelp/nrtsearch/server/query/MatchPhrasePrefixQuery.java @@ -80,10 +80,9 @@ public static Query build( com.yelp.nrtsearch.server.grpc.MatchPhrasePrefixQuery matchPhrasePrefixQueryGrpc, IndexState indexState) { FieldDef fieldDef = indexState.getFieldOrThrow(matchPhrasePrefixQueryGrpc.getField()); - if (!(fieldDef instanceof IndexableFieldDef)) { + if (!(fieldDef instanceof IndexableFieldDef indexableFieldDef)) { throw new IllegalArgumentException("MatchPhrasePrefixQuery requires an indexable field"); } - IndexableFieldDef indexableFieldDef = (IndexableFieldDef) fieldDef; if (!indexableFieldDef.isSearchable()) { throw new IllegalArgumentException( "Field " + matchPhrasePrefixQueryGrpc.getField() + " is not searchable"); @@ -117,7 +116,7 @@ public static Query build( * @throws IOException */ public static Query createQueryFromTokenStream( - TokenStream stream, IndexableFieldDef fieldDef, int slop, int maxExpansions) + TokenStream stream, IndexableFieldDef fieldDef, int slop, int maxExpansions) throws IOException { int resolvedMaxExpansions = maxExpansions > 0 ? maxExpansions : DEFAULT_MAX_EXPANSION; String field = fieldDef.getName(); @@ -273,7 +272,7 @@ private void getPrefixTerms(Set terms, final Term prefix, final IndexReade @Override public final String toString(String f) { StringBuilder buffer = new StringBuilder(); - if (field.equals(f) == false) { + if (!field.equals(f)) { buffer.append(field); buffer.append(":"); } @@ -321,7 +320,7 @@ public final String toString(String f) { /** Returns true if o is equal to this. */ @Override public boolean equals(Object o) { - if (sameClassAs(o) == false) { + if (!sameClassAs(o)) { return false; } MatchPhrasePrefixQuery other = (MatchPhrasePrefixQuery) o; diff --git a/src/main/java/com/yelp/nrtsearch/server/query/QueryNodeMapper.java b/src/main/java/com/yelp/nrtsearch/server/query/QueryNodeMapper.java index 20879e5c1..f99506bed 100644 --- a/src/main/java/com/yelp/nrtsearch/server/query/QueryNodeMapper.java +++ b/src/main/java/com/yelp/nrtsearch/server/query/QueryNodeMapper.java @@ -143,81 +143,58 @@ public Query getNestedPathQuery(IndexState indexState, String path) { private Query getQueryNode( com.yelp.nrtsearch.server.grpc.Query query, IndexState state, DocLookup docLookup) { - switch (query.getQueryNodeCase()) { - case BOOLEANQUERY: - return getBooleanQuery(query.getBooleanQuery(), state, docLookup); - case PHRASEQUERY: - return getPhraseQuery(query.getPhraseQuery()); - case FUNCTIONSCOREQUERY: - return getFunctionScoreQuery(query.getFunctionScoreQuery(), state, docLookup); - case TERMQUERY: - return getTermQuery(query.getTermQuery(), state); - case TERMINSETQUERY: - return getTermInSetQuery(query.getTermInSetQuery(), state); - case DISJUNCTIONMAXQUERY: - return getDisjunctionMaxQuery(query.getDisjunctionMaxQuery(), state, docLookup); - case MATCHQUERY: - return getMatchQuery(query.getMatchQuery(), state); - case MATCHPHRASEQUERY: - return getMatchPhraseQuery(query.getMatchPhraseQuery(), state); - case MULTIMATCHQUERY: - return getMultiMatchQuery(query.getMultiMatchQuery(), state); - case RANGEQUERY: - return getRangeQuery(query.getRangeQuery(), state); - case GEOBOUNDINGBOXQUERY: - return getGeoBoundingBoxQuery(query.getGeoBoundingBoxQuery(), state); - case GEOPOINTQUERY: - return getGeoPointQuery(query.getGeoPointQuery(), state); - case NESTEDQUERY: - return getNestedQuery(query.getNestedQuery(), state, docLookup); - case EXISTSQUERY: - return getExistsQuery(query.getExistsQuery(), state); - case GEORADIUSQUERY: - return getGeoRadiusQuery(query.getGeoRadiusQuery(), state); - case FUNCTIONFILTERQUERY: - return getFunctionFilterQuery(query.getFunctionFilterQuery(), state); - case COMPLETIONQUERY: - return getCompletionQuery(query.getCompletionQuery(), state); - case MULTIFUNCTIONSCOREQUERY: - return MultiFunctionScoreQuery.build(query.getMultiFunctionScoreQuery(), state); - case MATCHPHRASEPREFIXQUERY: - return MatchPhrasePrefixQuery.build(query.getMatchPhrasePrefixQuery(), state); - case PREFIXQUERY: - return getPrefixQuery(query.getPrefixQuery(), state); - case CONSTANTSCOREQUERY: - return getConstantScoreQuery(query.getConstantScoreQuery(), state, docLookup); - case SPANQUERY: - return getSpanQuery(query.getSpanQuery(), state); - case GEOPOLYGONQUERY: - return getGeoPolygonQuery(query.getGeoPolygonQuery(), state); - case MATCHALLQUERY, QUERYNODE_NOT_SET: - return new MatchAllDocsQuery(); - default: - throw new UnsupportedOperationException( - "Unsupported query type received: " + query.getQueryNodeCase()); - } + return switch (query.getQueryNodeCase()) { + case BOOLEANQUERY -> getBooleanQuery(query.getBooleanQuery(), state, docLookup); + case PHRASEQUERY -> getPhraseQuery(query.getPhraseQuery()); + case FUNCTIONSCOREQUERY -> + getFunctionScoreQuery(query.getFunctionScoreQuery(), state, docLookup); + case TERMQUERY -> getTermQuery(query.getTermQuery(), state); + case TERMINSETQUERY -> getTermInSetQuery(query.getTermInSetQuery(), state); + case DISJUNCTIONMAXQUERY -> + getDisjunctionMaxQuery(query.getDisjunctionMaxQuery(), state, docLookup); + case MATCHQUERY -> getMatchQuery(query.getMatchQuery(), state); + case MATCHPHRASEQUERY -> getMatchPhraseQuery(query.getMatchPhraseQuery(), state); + case MULTIMATCHQUERY -> getMultiMatchQuery(query.getMultiMatchQuery(), state); + case RANGEQUERY -> getRangeQuery(query.getRangeQuery(), state); + case GEOBOUNDINGBOXQUERY -> getGeoBoundingBoxQuery(query.getGeoBoundingBoxQuery(), state); + case GEOPOINTQUERY -> getGeoPointQuery(query.getGeoPointQuery(), state); + case NESTEDQUERY -> getNestedQuery(query.getNestedQuery(), state, docLookup); + case EXISTSQUERY -> getExistsQuery(query.getExistsQuery(), state); + case GEORADIUSQUERY -> getGeoRadiusQuery(query.getGeoRadiusQuery(), state); + case FUNCTIONFILTERQUERY -> getFunctionFilterQuery(query.getFunctionFilterQuery(), state); + case COMPLETIONQUERY -> getCompletionQuery(query.getCompletionQuery(), state); + case MULTIFUNCTIONSCOREQUERY -> + MultiFunctionScoreQuery.build(query.getMultiFunctionScoreQuery(), state); + case MATCHPHRASEPREFIXQUERY -> + MatchPhrasePrefixQuery.build(query.getMatchPhrasePrefixQuery(), state); + case PREFIXQUERY -> getPrefixQuery(query.getPrefixQuery(), state); + case CONSTANTSCOREQUERY -> + getConstantScoreQuery(query.getConstantScoreQuery(), state, docLookup); + case SPANQUERY -> getSpanQuery(query.getSpanQuery(), state); + case GEOPOLYGONQUERY -> getGeoPolygonQuery(query.getGeoPolygonQuery(), state); + case MATCHALLQUERY, QUERYNODE_NOT_SET -> new MatchAllDocsQuery(); + default -> + throw new UnsupportedOperationException( + "Unsupported query type received: " + query.getQueryNodeCase()); + }; } private Query getCompletionQuery( com.yelp.nrtsearch.server.grpc.CompletionQuery completionQueryDef, IndexState state) { - CompletionQuery completionQuery; - switch (completionQueryDef.getQueryType()) { - case PREFIX_QUERY: - completionQuery = - new PrefixCompletionQuery( - state.searchAnalyzer, - new Term(completionQueryDef.getField(), completionQueryDef.getText())); - break; - case FUZZY_QUERY: - completionQuery = - new FuzzyCompletionQuery( - state.searchAnalyzer, - new Term(completionQueryDef.getField(), completionQueryDef.getText())); - break; - default: - throw new UnsupportedOperationException( - "Unsupported suggest query type received: " + completionQueryDef.getQueryType()); - } + CompletionQuery completionQuery = + switch (completionQueryDef.getQueryType()) { + case PREFIX_QUERY -> + new PrefixCompletionQuery( + state.searchAnalyzer, + new Term(completionQueryDef.getField(), completionQueryDef.getText())); + case FUZZY_QUERY -> + new FuzzyCompletionQuery( + state.searchAnalyzer, + new Term(completionQueryDef.getField(), completionQueryDef.getText())); + default -> + throw new UnsupportedOperationException( + "Unsupported suggest query type received: " + completionQueryDef.getQueryType()); + }; MyContextQuery contextQuery = new MyContextQuery(completionQuery); contextQuery.addContexts(completionQueryDef.getContextsList()); return contextQuery; @@ -239,21 +216,16 @@ private Query getNestedQuery( } private ScoreMode getScoreMode(com.yelp.nrtsearch.server.grpc.NestedQuery nestedQuery) { - switch (nestedQuery.getScoreMode()) { - case NONE: - return ScoreMode.None; - case AVG: - return ScoreMode.Avg; - case MAX: - return ScoreMode.Max; - case MIN: - return ScoreMode.Min; - case SUM: - return ScoreMode.Total; - default: - throw new UnsupportedOperationException( - "Unsupported score mode received: " + nestedQuery.getScoreMode()); - } + return switch (nestedQuery.getScoreMode()) { + case NONE -> ScoreMode.None; + case AVG -> ScoreMode.Avg; + case MAX -> ScoreMode.Max; + case MIN -> ScoreMode.Min; + case SUM -> ScoreMode.Total; + default -> + throw new UnsupportedOperationException( + "Unsupported score mode received: " + nestedQuery.getScoreMode()); + }; } private BooleanQuery getBooleanQuery( @@ -333,7 +305,8 @@ private Query getTermQuery(com.yelp.nrtsearch.server.grpc.TermQuery termQuery, I } private void validateTermQueryIsSearchable(FieldDef fieldDef) { - if (fieldDef instanceof IndexableFieldDef && !((IndexableFieldDef) fieldDef).isSearchable()) { + if (fieldDef instanceof IndexableFieldDef + && !((IndexableFieldDef) fieldDef).isSearchable()) { throw new IllegalStateException( "Field " + fieldDef.getName() @@ -427,9 +400,10 @@ private Query getMatchPhraseQuery(MatchPhraseQuery matchPhraseQuery, IndexState case ALL_ZERO_TERMS -> { return new MatchAllDocsQuery(); } - default -> throw new IllegalArgumentException( - zeroTermsQuery - + " not valid. ZeroTermsQuery should be NONE_ZERO_TERMS or ALL_ZERO_TERMS"); + default -> + throw new IllegalArgumentException( + zeroTermsQuery + + " not valid. ZeroTermsQuery should be NONE_ZERO_TERMS or ALL_ZERO_TERMS"); } } return phraseQuery; @@ -454,41 +428,40 @@ private Query getMultiMatchQuery(MultiMatchQuery multiMatchQuery, IndexState sta fields.stream() .map( field -> { - Query query; - switch (multiMatchQuery.getType()) { - case BEST_FIELDS: - MatchQuery matchQuery = - MatchQuery.newBuilder() - .setField(field) - .setQuery(multiMatchQuery.getQuery()) - .setOperator(multiMatchQuery.getOperator()) - .setMinimumNumberShouldMatch( - multiMatchQuery.getMinimumNumberShouldMatch()) - .setAnalyzer( - multiMatchQuery - .getAnalyzer()) // TODO: making the analyzer once and using it - // for - // all match queries would be more efficient - .setFuzzyParams(multiMatchQuery.getFuzzyParams()) - .build(); - query = getMatchQuery(matchQuery, state); - break; - case PHRASE_PREFIX: - query = - MatchPhrasePrefixQuery.build( - com.yelp.nrtsearch.server.grpc.MatchPhrasePrefixQuery.newBuilder() + Query query = + switch (multiMatchQuery.getType()) { + case BEST_FIELDS -> { + MatchQuery matchQuery = + MatchQuery.newBuilder() .setField(field) .setQuery(multiMatchQuery.getQuery()) - .setAnalyzer(multiMatchQuery.getAnalyzer()) - .setSlop(multiMatchQuery.getSlop()) - .setMaxExpansions(multiMatchQuery.getMaxExpansions()) - .build(), - state); - break; - default: - throw new IllegalArgumentException( - "Unknown multi match type: " + multiMatchQuery.getType()); - } + .setOperator(multiMatchQuery.getOperator()) + .setMinimumNumberShouldMatch( + multiMatchQuery.getMinimumNumberShouldMatch()) + .setAnalyzer( + multiMatchQuery + .getAnalyzer()) // TODO: making the analyzer once and + // using it + // for + // all match queries would be more efficient + .setFuzzyParams(multiMatchQuery.getFuzzyParams()) + .build(); + yield getMatchQuery(matchQuery, state); + } + case PHRASE_PREFIX -> + MatchPhrasePrefixQuery.build( + com.yelp.nrtsearch.server.grpc.MatchPhrasePrefixQuery.newBuilder() + .setField(field) + .setQuery(multiMatchQuery.getQuery()) + .setAnalyzer(multiMatchQuery.getAnalyzer()) + .setSlop(multiMatchQuery.getSlop()) + .setMaxExpansions(multiMatchQuery.getMaxExpansions()) + .build(), + state); + default -> + throw new IllegalArgumentException( + "Unknown multi match type: " + multiMatchQuery.getType()); + }; Float boost = fieldBoosts.get(field); if (boost != null) { if (boost < 0) { @@ -511,10 +484,9 @@ private Query getMultiMatchCrossFieldsQuery( Analyzer analyzer = null; for (String field : fields) { FieldDef fieldDef = state.getFieldOrThrow(field); - if (!(fieldDef instanceof TextBaseFieldDef)) { + if (!(fieldDef instanceof TextBaseFieldDef textBaseFieldDef)) { throw new IllegalArgumentException("Field must be analyzable: " + field); } - TextBaseFieldDef textBaseFieldDef = (TextBaseFieldDef) fieldDef; if (!textBaseFieldDef.isSearchable()) { throw new IllegalArgumentException("Field must be searchable: " + field); } @@ -613,7 +585,7 @@ private static Query getPrefixQuery(PrefixQuery prefixQuery, IndexState state) { throw new IllegalArgumentException( "Field \"" + prefixQuery.getPrefix() + "\" is not indexable"); } - IndexOptions indexOptions = ((IndexableFieldDef) fieldDef).getFieldType().indexOptions(); + IndexOptions indexOptions = ((IndexableFieldDef) fieldDef).getFieldType().indexOptions(); if (indexOptions == IndexOptions.NONE) { throw new IllegalArgumentException( "Field \"" + prefixQuery.getField() + "\" is not indexed with terms"); @@ -687,7 +659,7 @@ private SpanQuery getSpanQuery( } } - private SpanMultiTermQueryWrapper getSpanMultiTermQueryWrapper( + private SpanMultiTermQueryWrapper getSpanMultiTermQueryWrapper( com.yelp.nrtsearch.server.grpc.SpanMultiTermQuery protoSpanMultiTermQuery, IndexState state) { com.yelp.nrtsearch.server.grpc.SpanMultiTermQuery.WrappedQueryCase wrappedQueryCase = diff --git a/src/main/java/com/yelp/nrtsearch/server/query/multifunction/DecayFilterFunction.java b/src/main/java/com/yelp/nrtsearch/server/query/multifunction/DecayFilterFunction.java index 44bbab780..faae8aad2 100644 --- a/src/main/java/com/yelp/nrtsearch/server/query/multifunction/DecayFilterFunction.java +++ b/src/main/java/com/yelp/nrtsearch/server/query/multifunction/DecayFilterFunction.java @@ -42,9 +42,10 @@ protected DecayFunction getDecayType(MultiFunctionScoreQuery.DecayType decayType case DECAY_TYPE_GUASSIAN -> new GuassianDecayFunction(); case DECAY_TYPE_EXPONENTIAL -> new ExponentialDecayFunction(); case DECAY_TYPE_LINEAR -> new LinearDecayFunction(); - default -> throw new IllegalArgumentException( - decayType - + " not supported. Only exponential, guassian and linear decay functions are supported"); + default -> + throw new IllegalArgumentException( + decayType + + " not supported. Only exponential, guassian and linear decay functions are supported"); }; } } diff --git a/src/main/java/com/yelp/nrtsearch/server/query/multifunction/GeoPointDecayFilterFunction.java b/src/main/java/com/yelp/nrtsearch/server/query/multifunction/GeoPointDecayFilterFunction.java index 87cfe7103..8282f9b1f 100644 --- a/src/main/java/com/yelp/nrtsearch/server/query/multifunction/GeoPointDecayFilterFunction.java +++ b/src/main/java/com/yelp/nrtsearch/server/query/multifunction/GeoPointDecayFilterFunction.java @@ -73,13 +73,12 @@ public GeoPointDecayFilterFunction( } public void validateLatLonField(FieldDef fieldDef) { - if (!(fieldDef instanceof LatLonFieldDef)) { + if (!(fieldDef instanceof LatLonFieldDef latLonFieldDef)) { throw new IllegalArgumentException( fieldName + " should be a LAT_LON to apply geoPoint decay function but it is: " + fieldDef.getType()); } - LatLonFieldDef latLonFieldDef = (LatLonFieldDef) fieldDef; // TODO: Add support for multi-value fields if (latLonFieldDef.isMultiValue()) { throw new IllegalArgumentException( @@ -155,15 +154,20 @@ public Explanation explainScore(int docId, Explanation innerQueryScore) { @Override public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(super.toString()).append(", decayFunction:"); - sb.append("fieldName: ").append(fieldName); - sb.append("decayType: ").append(decayType); - sb.append("origin: ").append(origin); - sb.append("scale: ").append(scale); - sb.append("offset: ").append(offset); - sb.append("decay: ").append(decay); - return sb.toString(); + return super.toString() + + ", decayFunction:" + + "fieldName: " + + fieldName + + "decayType: " + + decayType + + "origin: " + + origin + + "scale: " + + scale + + "offset: " + + offset + + "decay: " + + decay; } @Override diff --git a/src/main/java/com/yelp/nrtsearch/server/query/multifunction/MultiFunctionScoreQuery.java b/src/main/java/com/yelp/nrtsearch/server/query/multifunction/MultiFunctionScoreQuery.java index c256ab843..802e90bd4 100644 --- a/src/main/java/com/yelp/nrtsearch/server/query/multifunction/MultiFunctionScoreQuery.java +++ b/src/main/java/com/yelp/nrtsearch/server/query/multifunction/MultiFunctionScoreQuery.java @@ -60,10 +60,7 @@ private static boolean hasPassedMinScore( float currentScore, float minimalScore, boolean minimalExcluded) { if (currentScore > minimalScore) { return true; - } else if (!minimalExcluded && currentScore == minimalScore) { - return true; - } - return false; + } else return !minimalExcluded && currentScore == minimalScore; } /** @@ -225,13 +222,13 @@ public Explanation explain(LeafReaderContext context, int doc) throws IOExceptio } } final Explanation factorExplanation; - if (functionsExplanations.size() == 0) { + if (functionsExplanations.isEmpty()) { // it is a little weird to add a match although no function matches but that is the way // function_score behaves right now factorExplanation = Explanation.match(1.0f, "No function matched", Collections.emptyList()); } else if (singleFunction && functionsExplanations.size() == 1) { - factorExplanation = functionsExplanations.get(0); + factorExplanation = functionsExplanations.getFirst(); } else { MultiFunctionScorer scorer = (MultiFunctionScorer) scorer(context); int actualDoc = scorer.iterator().advance(doc); @@ -260,28 +257,27 @@ public Explanation explain(LeafReaderContext context, int doc) throws IOExceptio } private Explanation explainBoost(Explanation queryExpl, Explanation funcExpl) { - switch (boostMode) { - case BOOST_MODE_MULTIPLY: - return Explanation.match( - queryExpl.getValue().floatValue() * funcExpl.getValue().floatValue(), - "function score, product of:", - queryExpl, - funcExpl); - case BOOST_MODE_SUM: - return Explanation.match( - funcExpl.getValue().floatValue() + queryExpl.getValue().floatValue(), - "sum of", - queryExpl, - funcExpl); - case BOOST_MODE_REPLACE: - return Explanation.match( - funcExpl.getValue().floatValue(), - "Ignoring query score, function score of", - queryExpl, - funcExpl); - default: - throw new IllegalStateException("Unknown boost mode type: " + boostMode); - } + return switch (boostMode) { + case BOOST_MODE_MULTIPLY -> + Explanation.match( + queryExpl.getValue().floatValue() * funcExpl.getValue().floatValue(), + "function score, product of:", + queryExpl, + funcExpl); + case BOOST_MODE_SUM -> + Explanation.match( + funcExpl.getValue().floatValue() + queryExpl.getValue().floatValue(), + "sum of", + queryExpl, + funcExpl); + case BOOST_MODE_REPLACE -> + Explanation.match( + funcExpl.getValue().floatValue(), + "Ignoring query score, function score of", + queryExpl, + funcExpl); + default -> throw new IllegalStateException("Unknown boost mode type: " + boostMode); + }; } @Override @@ -364,7 +360,7 @@ public TwoPhaseIterator twoPhaseIterator() { @Override public boolean matches() throws IOException { - if (finalTwoPhase != null && finalTwoPhase.matches() == false) { + if (finalTwoPhase != null && !finalTwoPhase.matches()) { return false; } // we need to check the two-phase iterator first @@ -480,16 +476,12 @@ private double computeFunctionScore(int docId, float innerQueryScore) throws IOE } private float computeFinalScore(float innerQueryScore, double functionScore) { - switch (boostMode) { - case BOOST_MODE_MULTIPLY: - return (float) (innerQueryScore * functionScore); - case BOOST_MODE_SUM: - return (float) (innerQueryScore + functionScore); - case BOOST_MODE_REPLACE: - return (float) functionScore; - default: - throw new IllegalStateException("Unknown boost mode type: " + boostMode); - } + return switch (boostMode) { + case BOOST_MODE_MULTIPLY -> (float) (innerQueryScore * functionScore); + case BOOST_MODE_SUM -> (float) (innerQueryScore + functionScore); + case BOOST_MODE_REPLACE -> (float) functionScore; + default -> throw new IllegalStateException("Unknown boost mode type: " + boostMode); + }; } @Override @@ -503,18 +495,17 @@ public String toString(String field) { StringBuilder sb = new StringBuilder(); sb.append("multi function score (").append(innerQuery.toString(field)).append(", functions: ["); for (FilterFunction function : functions) { - sb.append("{" + (function == null ? "" : function.toString()) + "}"); + sb.append("{").append(function == null ? "" : function.toString()).append("}"); } sb.append("])"); - sb.append(", minScore: " + minScore).append(minExcluded ? " (excluded)" : " (included)"); + sb.append(", minScore: ").append(minScore).append(minExcluded ? " (excluded)" : " (included)"); return sb.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; - if (!(o instanceof MultiFunctionScoreQuery)) return false; - MultiFunctionScoreQuery that = (MultiFunctionScoreQuery) o; + if (!(o instanceof MultiFunctionScoreQuery that)) return false; return Float.compare(that.minScore, minScore) == 0 && minExcluded == that.minExcluded && Objects.equals(innerQuery, that.innerQuery) diff --git a/src/main/java/com/yelp/nrtsearch/server/rescore/RescorerCreator.java b/src/main/java/com/yelp/nrtsearch/server/rescore/RescorerCreator.java index 6048ab2a2..fb79b127e 100644 --- a/src/main/java/com/yelp/nrtsearch/server/rescore/RescorerCreator.java +++ b/src/main/java/com/yelp/nrtsearch/server/rescore/RescorerCreator.java @@ -76,8 +76,7 @@ private void register(String name, RescorerProvider public static void initialize(NrtsearchConfig configuration, Iterable plugins) { instance = new RescorerCreator(configuration); for (Plugin plugin : plugins) { - if (plugin instanceof RescorerPlugin) { - RescorerPlugin rescorePlugin = (RescorerPlugin) plugin; + if (plugin instanceof RescorerPlugin rescorePlugin) { instance.register(rescorePlugin.getRescorers()); } } diff --git a/src/main/java/com/yelp/nrtsearch/server/script/ScriptContext.java b/src/main/java/com/yelp/nrtsearch/server/script/ScriptContext.java index b9ef8c9e7..839f85505 100644 --- a/src/main/java/com/yelp/nrtsearch/server/script/ScriptContext.java +++ b/src/main/java/com/yelp/nrtsearch/server/script/ScriptContext.java @@ -19,7 +19,6 @@ import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; -import java.util.stream.Collectors; /** * Context that holds type information needed to compile a script. Provides classes conforming with @@ -146,7 +145,7 @@ private Method getMethod(Class clazz, String methodName) { List methods = Arrays.stream(clazz.getMethods()) .filter(method -> method.getName().equals(methodName)) - .collect(Collectors.toList()); + .toList(); if (methods.isEmpty()) { return null; } @@ -154,6 +153,6 @@ private Method getMethod(Class clazz, String methodName) { throw new IllegalArgumentException( "Expected at most 1 method named " + methodName + ", found " + methods.size()); } - return methods.get(0); + return methods.getFirst(); } } diff --git a/src/main/java/com/yelp/nrtsearch/server/script/ScriptService.java b/src/main/java/com/yelp/nrtsearch/server/script/ScriptService.java index c798b44b4..6431ce708 100644 --- a/src/main/java/com/yelp/nrtsearch/server/script/ScriptService.java +++ b/src/main/java/com/yelp/nrtsearch/server/script/ScriptService.java @@ -121,8 +121,7 @@ private void register(String name, ScriptEngine scriptEngine) { public static void initialize(NrtsearchConfig configuration, Iterable plugins) { instance = new ScriptService(configuration); for (Plugin plugin : plugins) { - if (plugin instanceof ScriptPlugin) { - ScriptPlugin scriptPlugin = (ScriptPlugin) plugin; + if (plugin instanceof ScriptPlugin scriptPlugin) { instance.register(scriptPlugin.getScriptEngines(builtInContexts)); } } @@ -150,8 +149,7 @@ public int hashCode() { @Override public boolean equals(Object o) { - if (o instanceof ScriptCacheKey) { - ScriptCacheKey cacheKey = (ScriptCacheKey) o; + if (o instanceof ScriptCacheKey cacheKey) { return context == cacheKey.context && Objects.equals(lang, cacheKey.lang) && Objects.equals(source, cacheKey.source); diff --git a/src/main/java/com/yelp/nrtsearch/server/script/js/JsScriptBindings.java b/src/main/java/com/yelp/nrtsearch/server/script/js/JsScriptBindings.java index c0752e7c3..420fcf2b4 100644 --- a/src/main/java/com/yelp/nrtsearch/server/script/js/JsScriptBindings.java +++ b/src/main/java/com/yelp/nrtsearch/server/script/js/JsScriptBindings.java @@ -79,8 +79,7 @@ public DoubleValuesSource getDoubleValuesSource(String name) { double valueAsDouble; if (paramObject instanceof Number) { valueAsDouble = ((Number) paramObject).doubleValue(); - } else if (paramObject instanceof Boolean) { - Boolean value = (Boolean) paramObject; + } else if (paramObject instanceof Boolean value) { valueAsDouble = value == Boolean.TRUE ? 1.0 : 0.0; } else { throw new IllegalArgumentException( @@ -127,8 +126,7 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (obj instanceof ParamDoubleValuesSource) { - ParamDoubleValuesSource paramDoubleValuesSource = (ParamDoubleValuesSource) obj; + if (obj instanceof ParamDoubleValuesSource paramDoubleValuesSource) { return Double.compare( paramDoubleValuesSource.paramDoubleValues.paramValue, paramDoubleValues.paramValue) == 0; diff --git a/src/main/java/com/yelp/nrtsearch/server/search/collectors/CollectorCreator.java b/src/main/java/com/yelp/nrtsearch/server/search/collectors/CollectorCreator.java index 2dee2d2b7..2df99b6d2 100644 --- a/src/main/java/com/yelp/nrtsearch/server/search/collectors/CollectorCreator.java +++ b/src/main/java/com/yelp/nrtsearch/server/search/collectors/CollectorCreator.java @@ -160,8 +160,7 @@ private void register( public static void initialize(NrtsearchConfig configuration, Iterable plugins) { instance = new CollectorCreator(configuration); for (Plugin plugin : plugins) { - if (plugin instanceof CollectorPlugin) { - CollectorPlugin collectorPlugin = (CollectorPlugin) plugin; + if (plugin instanceof CollectorPlugin collectorPlugin) { instance.register(collectorPlugin.getCollectors()); } } diff --git a/src/main/java/com/yelp/nrtsearch/server/search/collectors/MyTopSuggestDocsCollector.java b/src/main/java/com/yelp/nrtsearch/server/search/collectors/MyTopSuggestDocsCollector.java index 5d4b97312..ddf942f91 100644 --- a/src/main/java/com/yelp/nrtsearch/server/search/collectors/MyTopSuggestDocsCollector.java +++ b/src/main/java/com/yelp/nrtsearch/server/search/collectors/MyTopSuggestDocsCollector.java @@ -206,7 +206,7 @@ public TopSuggestDocs.SuggestScoreDoc insertWithOverflow( priorityQueue.add(suggestScoreDoc); // this doc may have displaced a previous one for this id return previousForId; - } else if (priorityQueue.size() > 0 && isLessThan(priorityQueue.peek(), suggestScoreDoc)) { + } else if (!priorityQueue.isEmpty() && isLessThan(priorityQueue.peek(), suggestScoreDoc)) { // remove the current lowest doc and replace with higher scoring new doc SuggestScoreDoc previous = priorityQueue.poll(); priorityQueue.add(suggestScoreDoc); diff --git a/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/DoubleTermsCollectorManager.java b/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/DoubleTermsCollectorManager.java index 16406f39f..f655c96d9 100644 --- a/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/DoubleTermsCollectorManager.java +++ b/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/DoubleTermsCollectorManager.java @@ -42,7 +42,7 @@ /** Collector manager that aggregates terms from Double doc values into buckets. */ public class DoubleTermsCollectorManager extends TermsCollectorManager { - private final IndexableFieldDef fieldDef; + private final IndexableFieldDef fieldDef; /** * Constructor. @@ -58,7 +58,7 @@ public DoubleTermsCollectorManager( String name, com.yelp.nrtsearch.server.grpc.TermsCollector grpcTermsCollector, CollectorCreatorContext context, - IndexableFieldDef indexableFieldDef, + IndexableFieldDef indexableFieldDef, Map>> nestedCollectorSuppliers, BucketOrder bucketOrder) { diff --git a/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/FilterCollectorManager.java b/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/FilterCollectorManager.java index 6d01ad946..c5fe707f0 100644 --- a/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/FilterCollectorManager.java +++ b/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/FilterCollectorManager.java @@ -140,7 +140,7 @@ public boolean accepts(int docId) throws IOException { * of building a scorer is high. */ private static class SetQueryFilter implements Filter { - final IndexableFieldDef filterField; + final IndexableFieldDef filterField; final Set filterSet = new HashSet<>(); /** @@ -159,7 +159,7 @@ private static class SetQueryFilter implements Filter { throw new IllegalArgumentException( "Filter field is not indexable: " + grpcTermInSetQuery.getField()); } - filterField = (IndexableFieldDef) fieldDef; + filterField = (IndexableFieldDef) fieldDef; if (!filterField.hasDocValues()) { throw new IllegalArgumentException( "Filter field must have doc values enabled: " + grpcTermInSetQuery.getField()); diff --git a/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/FloatTermsCollectorManager.java b/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/FloatTermsCollectorManager.java index b0b388c36..7a134526c 100644 --- a/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/FloatTermsCollectorManager.java +++ b/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/FloatTermsCollectorManager.java @@ -42,7 +42,7 @@ /** Collector manager that aggregates terms from Float doc values into buckets. */ public class FloatTermsCollectorManager extends TermsCollectorManager { - private final IndexableFieldDef fieldDef; + private final IndexableFieldDef fieldDef; /** * Constructor. @@ -58,7 +58,7 @@ public FloatTermsCollectorManager( String name, com.yelp.nrtsearch.server.grpc.TermsCollector grpcTermsCollector, CollectorCreatorContext context, - IndexableFieldDef indexableFieldDef, + IndexableFieldDef indexableFieldDef, Map>> nestedCollectorSuppliers, BucketOrder bucketOrder) { diff --git a/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/IntTermsCollectorManager.java b/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/IntTermsCollectorManager.java index 980be781e..4594d01dc 100644 --- a/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/IntTermsCollectorManager.java +++ b/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/IntTermsCollectorManager.java @@ -40,7 +40,7 @@ /** Collector manager that aggregates terms from Integer doc values into buckets. */ public class IntTermsCollectorManager extends TermsCollectorManager { - private final IndexableFieldDef fieldDef; + private final IndexableFieldDef fieldDef; /** * Constructor. @@ -56,7 +56,7 @@ public IntTermsCollectorManager( String name, com.yelp.nrtsearch.server.grpc.TermsCollector grpcTermsCollector, CollectorCreatorContext context, - IndexableFieldDef indexableFieldDef, + IndexableFieldDef indexableFieldDef, Map>> nestedCollectorSuppliers, BucketOrder bucketOrder) { diff --git a/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/LongTermsCollectorManager.java b/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/LongTermsCollectorManager.java index 414b63348..d8e15d9f1 100644 --- a/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/LongTermsCollectorManager.java +++ b/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/LongTermsCollectorManager.java @@ -40,7 +40,7 @@ /** Collector manager that aggregates terms from Long doc values into buckets. */ public class LongTermsCollectorManager extends TermsCollectorManager { - private final IndexableFieldDef fieldDef; + private final IndexableFieldDef fieldDef; /** * Constructor. @@ -56,7 +56,7 @@ public LongTermsCollectorManager( String name, com.yelp.nrtsearch.server.grpc.TermsCollector grpcTermsCollector, CollectorCreatorContext context, - IndexableFieldDef indexableFieldDef, + IndexableFieldDef indexableFieldDef, Map>> nestedCollectorSuppliers, BucketOrder bucketOrder) { diff --git a/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/MaxCollectorManager.java b/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/MaxCollectorManager.java index bc2e13374..ad1bf4031 100644 --- a/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/MaxCollectorManager.java +++ b/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/MaxCollectorManager.java @@ -53,15 +53,14 @@ public MaxCollectorManager( CollectorCreatorContext context) { this.name = name; - switch (grpcMaxCollector.getValueSourceCase()) { - case SCRIPT: - valueProvider = - new ScriptValueProvider( - grpcMaxCollector.getScript(), context.getIndexState().docLookup, UNSET_VALUE); - break; - default: - throw new IllegalArgumentException( - "Unknown value source: " + grpcMaxCollector.getValueSourceCase()); + if (grpcMaxCollector.getValueSourceCase() + == com.yelp.nrtsearch.server.grpc.MaxCollector.ValueSourceCase.SCRIPT) { + valueProvider = + new ScriptValueProvider( + grpcMaxCollector.getScript(), context.getIndexState().docLookup, UNSET_VALUE); + } else { + throw new IllegalArgumentException( + "Unknown value source: " + grpcMaxCollector.getValueSourceCase()); } } diff --git a/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/MinCollectorManager.java b/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/MinCollectorManager.java index 8bf9d5cc8..0bc3c22fa 100644 --- a/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/MinCollectorManager.java +++ b/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/MinCollectorManager.java @@ -17,6 +17,7 @@ import com.google.protobuf.DoubleValue; import com.yelp.nrtsearch.server.grpc.CollectorResult; +import com.yelp.nrtsearch.server.grpc.MinCollector; import com.yelp.nrtsearch.server.script.ScoreScript; import com.yelp.nrtsearch.server.search.collectors.AdditionalCollectorManager; import com.yelp.nrtsearch.server.search.collectors.CollectorCreatorContext; @@ -52,15 +53,14 @@ public MinCollectorManager( CollectorCreatorContext context) { this.name = name; - switch (grpcMinCollector.getValueSourceCase()) { - case SCRIPT: - valueProvider = - new ScriptValueProvider( - grpcMinCollector.getScript(), context.getIndexState().docLookup, UNSET_VALUE); - break; - default: - throw new IllegalArgumentException( - "Unknown value source: " + grpcMinCollector.getValueSourceCase()); + if (grpcMinCollector.getValueSourceCase() + == com.yelp.nrtsearch.server.grpc.MinCollector.ValueSourceCase.SCRIPT) { + valueProvider = + new ScriptValueProvider( + grpcMinCollector.getScript(), context.getIndexState().docLookup, UNSET_VALUE); + } else { + throw new IllegalArgumentException( + "Unknown value source: " + grpcMinCollector.getValueSourceCase()); } } diff --git a/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/OrdinalTermsCollectorManager.java b/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/OrdinalTermsCollectorManager.java index bcb6c0d98..900e6a66a 100644 --- a/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/OrdinalTermsCollectorManager.java +++ b/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/OrdinalTermsCollectorManager.java @@ -51,7 +51,7 @@ /** Collector manager that aggregates terms using global ordinals into buckets. */ public class OrdinalTermsCollectorManager extends TermsCollectorManager { - private final IndexableFieldDef fieldDef; + private final IndexableFieldDef fieldDef; private final GlobalOrdinalLookup globalOrdinalLookup; /** @@ -69,7 +69,7 @@ public OrdinalTermsCollectorManager( String name, com.yelp.nrtsearch.server.grpc.TermsCollector grpcTermsCollector, CollectorCreatorContext context, - IndexableFieldDef indexableFieldDef, + IndexableFieldDef indexableFieldDef, GlobalOrdinalable globalOrdinalable, Map>> nestedCollectorSuppliers, diff --git a/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/StringTermsCollectorManager.java b/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/StringTermsCollectorManager.java index a98f15795..5ee7c557d 100644 --- a/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/StringTermsCollectorManager.java +++ b/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/StringTermsCollectorManager.java @@ -40,7 +40,7 @@ /** Collector manager that aggregates terms from String doc values into buckets. */ public class StringTermsCollectorManager extends TermsCollectorManager { - private final IndexableFieldDef fieldDef; + private final IndexableFieldDef fieldDef; /** * Constructor. @@ -56,7 +56,7 @@ public StringTermsCollectorManager( String name, com.yelp.nrtsearch.server.grpc.TermsCollector grpcTermsCollector, CollectorCreatorContext context, - IndexableFieldDef indexableFieldDef, + IndexableFieldDef indexableFieldDef, Map>> nestedCollectorSuppliers, BucketOrder bucketOrder) { diff --git a/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/TermsCollectorManager.java b/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/TermsCollectorManager.java index fe6e841a5..8945e48ee 100644 --- a/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/TermsCollectorManager.java +++ b/src/main/java/com/yelp/nrtsearch/server/search/collectors/additional/TermsCollectorManager.java @@ -103,77 +103,87 @@ public static TermsCollectorManager buildManager( name, grpcTermsCollector, context, nestedCollectorSuppliers, bucketOrder); case FIELD: FieldDef field = context.getQueryFields().get(grpcTermsCollector.getField()); - if (field == null) { - throw new IllegalArgumentException("Unknown field: " + grpcTermsCollector.getField()); - } - if (field instanceof IndexableFieldDef) { - IndexableFieldDef indexableFieldDef = (IndexableFieldDef) field; - if (!indexableFieldDef.hasDocValues()) { - throw new IllegalArgumentException( - "Terms collection requires doc values for field: " + grpcTermsCollector.getField()); + switch (field) { + case null -> + throw new IllegalArgumentException("Unknown field: " + grpcTermsCollector.getField()); + case IndexableFieldDef indexableFieldDef -> { + if (!indexableFieldDef.hasDocValues()) { + throw new IllegalArgumentException( + "Terms collection requires doc values for field: " + + grpcTermsCollector.getField()); + } + // Pick implementation based on field type + switch (indexableFieldDef) { + case IntFieldDef intFieldDef -> { + return new IntTermsCollectorManager( + name, + grpcTermsCollector, + context, + indexableFieldDef, + nestedCollectorSuppliers, + bucketOrder); + } + case LongFieldDef longFieldDef -> { + return new LongTermsCollectorManager( + name, + grpcTermsCollector, + context, + indexableFieldDef, + nestedCollectorSuppliers, + bucketOrder); + } + case FloatFieldDef floatFieldDef -> { + return new FloatTermsCollectorManager( + name, + grpcTermsCollector, + context, + indexableFieldDef, + nestedCollectorSuppliers, + bucketOrder); + } + case DoubleFieldDef doubleFieldDef -> { + return new DoubleTermsCollectorManager( + name, + grpcTermsCollector, + context, + indexableFieldDef, + nestedCollectorSuppliers, + bucketOrder); + } + case TextBaseFieldDef textBaseFieldDef -> { + if (indexableFieldDef instanceof GlobalOrdinalable + && ((GlobalOrdinalable) indexableFieldDef).usesOrdinals()) { + return new OrdinalTermsCollectorManager( + name, + grpcTermsCollector, + context, + indexableFieldDef, + (GlobalOrdinalable) indexableFieldDef, + nestedCollectorSuppliers, + bucketOrder); + } else { + return new StringTermsCollectorManager( + name, + grpcTermsCollector, + context, + indexableFieldDef, + nestedCollectorSuppliers, + bucketOrder); + } + } + default -> {} + } } - // Pick implementation based on field type - if (indexableFieldDef instanceof IntFieldDef) { - return new IntTermsCollectorManager( - name, - grpcTermsCollector, - context, - indexableFieldDef, - nestedCollectorSuppliers, - bucketOrder); - } else if (indexableFieldDef instanceof LongFieldDef) { - return new LongTermsCollectorManager( - name, - grpcTermsCollector, - context, - indexableFieldDef, - nestedCollectorSuppliers, - bucketOrder); - } else if (indexableFieldDef instanceof FloatFieldDef) { - return new FloatTermsCollectorManager( + case VirtualFieldDef virtualFieldDef -> { + return new VirtualTermsCollectorManager( name, grpcTermsCollector, context, - indexableFieldDef, + virtualFieldDef, nestedCollectorSuppliers, bucketOrder); - } else if (indexableFieldDef instanceof DoubleFieldDef) { - return new DoubleTermsCollectorManager( - name, - grpcTermsCollector, - context, - indexableFieldDef, - nestedCollectorSuppliers, - bucketOrder); - } else if (indexableFieldDef instanceof TextBaseFieldDef) { - if (indexableFieldDef instanceof GlobalOrdinalable - && ((GlobalOrdinalable) indexableFieldDef).usesOrdinals()) { - return new OrdinalTermsCollectorManager( - name, - grpcTermsCollector, - context, - indexableFieldDef, - (GlobalOrdinalable) indexableFieldDef, - nestedCollectorSuppliers, - bucketOrder); - } else { - return new StringTermsCollectorManager( - name, - grpcTermsCollector, - context, - indexableFieldDef, - nestedCollectorSuppliers, - bucketOrder); - } } - } else if (field instanceof VirtualFieldDef) { - return new VirtualTermsCollectorManager( - name, - grpcTermsCollector, - context, - (VirtualFieldDef) field, - nestedCollectorSuppliers, - bucketOrder); + default -> {} } throw new IllegalArgumentException( "Terms collection does not support field: " @@ -320,7 +330,7 @@ void fillBucketResultByCount( Collection nestedCollectors) throws IOException { int size = getSize(); - if (counts.size() > 0 && size > 0) { + if (!counts.isEmpty() && size > 0) { Comparator entryComparator = Comparator.comparingInt(b -> b.count); QueueAddDecider queueAddDecider; if (bucketOrder.getOrderType() == OrderType.DESC) { @@ -423,7 +433,7 @@ void fillBucketResultByCount( Collection nestedCollectors) throws IOException { int size = getSize(); - if (counts.size() > 0 && size > 0) { + if (!counts.isEmpty() && size > 0) { Comparator entryComparator = Comparator.comparingInt(b -> b.count); QueueAddDecider queueAddDecider; if (bucketOrder.getOrderType() == OrderType.DESC) { @@ -526,7 +536,7 @@ void fillBucketResultByCount( Collection nestedCollectors) throws IOException { int size = getSize(); - if (counts.size() > 0 && size > 0) { + if (!counts.isEmpty() && size > 0) { Comparator entryComparator = Comparator.comparingInt(b -> b.count); QueueAddDecider queueAddDecider; if (bucketOrder.getOrderType() == OrderType.DESC) { @@ -629,7 +639,7 @@ void fillBucketResultByCount( Collection nestedCollectors) throws IOException { int size = getSize(); - if (counts.size() > 0 && size > 0) { + if (!counts.isEmpty() && size > 0) { Comparator entryComparator = Comparator.comparingInt(b -> b.count); QueueAddDecider queueAddDecider; if (bucketOrder.getOrderType() == OrderType.DESC) { @@ -732,7 +742,7 @@ void fillBucketResultByCount( Collection nestedCollectors) throws IOException { int size = getSize(); - if (counts.size() > 0 && size > 0) { + if (!counts.isEmpty() && size > 0) { Comparator entryComparator = Comparator.comparingInt(b -> b.count); QueueAddDecider queueAddDecider; if (bucketOrder.getOrderType() == OrderType.DESC) { @@ -833,7 +843,7 @@ void fillBucketResultByCount( Collection nestedCollectors) throws IOException { int size = getSize(); - if (counts.size() > 0 && size > 0) { + if (!counts.isEmpty() && size > 0) { Comparator entryComparator = Comparator.comparingInt(b -> b.count); QueueAddDecider queueAddDecider; if (bucketOrder.getOrderType() == OrderType.DESC) { @@ -927,7 +937,7 @@ private void fillBucketResultByNestedOrder( throw new IllegalStateException("Collector ordering requires nested collectors"); } int size = getSize(); - if (counts.size() > 0 && size > 0) { + if (!counts.isEmpty() && size > 0) { Comparator orderComparator = bucketOrder.getCollectorResultComparator(); if (bucketOrder.getOrderType() == OrderType.ASC) { orderComparator = orderComparator.reversed(); diff --git a/src/main/java/com/yelp/nrtsearch/server/similarity/SimilarityCreator.java b/src/main/java/com/yelp/nrtsearch/server/similarity/SimilarityCreator.java index 085c70cf9..b3a4d8c7d 100644 --- a/src/main/java/com/yelp/nrtsearch/server/similarity/SimilarityCreator.java +++ b/src/main/java/com/yelp/nrtsearch/server/similarity/SimilarityCreator.java @@ -84,8 +84,7 @@ private void register(String name, SimilarityProvider simi public static void initialize(NrtsearchConfig configuration, Iterable plugins) { instance = new SimilarityCreator(configuration); for (Plugin plugin : plugins) { - if (plugin instanceof SimilarityPlugin) { - SimilarityPlugin similarityPlugin = (SimilarityPlugin) plugin; + if (plugin instanceof SimilarityPlugin similarityPlugin) { instance.register(similarityPlugin.getSimilarities()); } } diff --git a/src/main/java/com/yelp/nrtsearch/server/state/BackendGlobalState.java b/src/main/java/com/yelp/nrtsearch/server/state/BackendGlobalState.java index 75c9875ec..17584e60d 100644 --- a/src/main/java/com/yelp/nrtsearch/server/state/BackendGlobalState.java +++ b/src/main/java/com/yelp/nrtsearch/server/state/BackendGlobalState.java @@ -129,16 +129,14 @@ public BackendGlobalState(NrtsearchConfig luceneServerConfiguration, RemoteBacke * for testing. */ protected StateBackend createStateBackend() { - switch (getConfiguration().getStateConfig().getBackendType()) { - case LOCAL: - return new LocalStateBackend(this); - case REMOTE: - return new RemoteStateBackend(this); - default: - throw new IllegalArgumentException( - "Unsupported state backend type: " - + getConfiguration().getStateConfig().getBackendType()); - } + return switch (getConfiguration().getStateConfig().getBackendType()) { + case LOCAL -> new LocalStateBackend(this); + case REMOTE -> new RemoteStateBackend(this); + default -> + throw new IllegalArgumentException( + "Unsupported state backend type: " + + getConfiguration().getStateConfig().getBackendType()); + }; } /** diff --git a/src/main/java/com/yelp/nrtsearch/server/state/GlobalState.java b/src/main/java/com/yelp/nrtsearch/server/state/GlobalState.java index ccc621bcb..c5f65c44e 100644 --- a/src/main/java/com/yelp/nrtsearch/server/state/GlobalState.java +++ b/src/main/java/com/yelp/nrtsearch/server/state/GlobalState.java @@ -88,7 +88,7 @@ protected GlobalState(NrtsearchConfig luceneServerConfiguration, RemoteBackend r this.replicaReplicationPortPingInterval = luceneServerConfiguration.getReplicaReplicationPortPingInterval(); this.threadPoolConfiguration = luceneServerConfiguration.getThreadPoolConfiguration(); - if (Files.exists(stateDir) == false) { + if (!Files.exists(stateDir)) { Files.createDirectories(stateDir); } this.indexExecutor = diff --git a/src/main/java/com/yelp/nrtsearch/server/utils/HostPort.java b/src/main/java/com/yelp/nrtsearch/server/utils/HostPort.java index 629dfc9f6..e4b35f1a6 100644 --- a/src/main/java/com/yelp/nrtsearch/server/utils/HostPort.java +++ b/src/main/java/com/yelp/nrtsearch/server/utils/HostPort.java @@ -49,10 +49,6 @@ public int getPort() { @Override public String toString() { - final StringBuilder sb = new StringBuilder("HostPort{"); - sb.append("hostname='").append(hostName).append('\''); - sb.append(", port=").append(port); - sb.append('}'); - return sb.toString(); + return "HostPort{" + "hostname='" + hostName + '\'' + ", port=" + port + '}'; } } diff --git a/src/main/java/com/yelp/nrtsearch/server/utils/StructValueTransformer.java b/src/main/java/com/yelp/nrtsearch/server/utils/StructValueTransformer.java index e8a7ef7c2..98138cb75 100644 --- a/src/main/java/com/yelp/nrtsearch/server/utils/StructValueTransformer.java +++ b/src/main/java/com/yelp/nrtsearch/server/utils/StructValueTransformer.java @@ -72,21 +72,15 @@ public Object apply(@Nullable Value input) { if (input == null) { return null; } - switch (input.getKindCase()) { - case NULL_VALUE: - return null; - case STRING_VALUE: - return input.getStringValue(); - case NUMBER_VALUE: - return input.getNumberValue(); - case BOOL_VALUE: - return input.getBoolValue(); - case LIST_VALUE: - return transformList(input.getListValue()); - case STRUCT_VALUE: - return transformStruct(input.getStructValue()); - default: - throw new IllegalArgumentException("Unknown Struct value type: " + input.getKindCase()); - } + return switch (input.getKindCase()) { + case NULL_VALUE -> null; + case STRING_VALUE -> input.getStringValue(); + case NUMBER_VALUE -> input.getNumberValue(); + case BOOL_VALUE -> input.getBoolValue(); + case LIST_VALUE -> transformList(input.getListValue()); + case STRUCT_VALUE -> transformStruct(input.getStructValue()); + default -> + throw new IllegalArgumentException("Unknown Struct value type: " + input.getKindCase()); + }; } } diff --git a/src/main/java/com/yelp/nrtsearch/server/vector/FloatVectorType.java b/src/main/java/com/yelp/nrtsearch/server/vector/FloatVectorType.java index 004b99dd9..eb9cde5da 100644 --- a/src/main/java/com/yelp/nrtsearch/server/vector/FloatVectorType.java +++ b/src/main/java/com/yelp/nrtsearch/server/vector/FloatVectorType.java @@ -20,7 +20,7 @@ public final class FloatVectorType extends AbstractList { - private float[] vectorData; + private final float[] vectorData; /** * Construct VectorType with given vector data diff --git a/src/main/java/com/yelp/nrtsearch/tools/nrt_utils/backup/BackupCommandUtils.java b/src/main/java/com/yelp/nrtsearch/tools/nrt_utils/backup/BackupCommandUtils.java index cc00a674b..e288697e5 100644 --- a/src/main/java/com/yelp/nrtsearch/tools/nrt_utils/backup/BackupCommandUtils.java +++ b/src/main/java/com/yelp/nrtsearch/tools/nrt_utils/backup/BackupCommandUtils.java @@ -119,17 +119,12 @@ public static long getTimeIntervalMs(String interval) { throw new IllegalArgumentException("Time interval must be > 0"); } - switch (endChar) { - case 's': - return TimeUnit.SECONDS.toMillis(numberVal); - case 'm': - return TimeUnit.MINUTES.toMillis(numberVal); - case 'h': - return TimeUnit.HOURS.toMillis(numberVal); - case 'd': - return TimeUnit.DAYS.toMillis(numberVal); - default: - throw new IllegalArgumentException("Unknown time unit: " + endChar); - } + return switch (endChar) { + case 's' -> TimeUnit.SECONDS.toMillis(numberVal); + case 'm' -> TimeUnit.MINUTES.toMillis(numberVal); + case 'h' -> TimeUnit.HOURS.toMillis(numberVal); + case 'd' -> TimeUnit.DAYS.toMillis(numberVal); + default -> throw new IllegalArgumentException("Unknown time unit: " + endChar); + }; } }