Java Code Examples for org.apache.lucene.search.SortField#Type

The following examples show how to use org.apache.lucene.search.SortField#Type . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SolrIndexConfigTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testSortingMPSolrIndexConfigCreation() throws Exception {
  final String expectedFieldName = "timestamp_i_dvo";
  final SortField.Type expectedFieldType = SortField.Type.INT;
  final boolean expectedFieldSortDescending = true;

  SolrConfig solrConfig = new SolrConfig(instanceDir, solrConfigFileNameSortingMergePolicyFactory);
  SolrIndexConfig solrIndexConfig = new SolrIndexConfig(solrConfig, null, null);
  assertNotNull(solrIndexConfig);
  IndexSchema indexSchema = IndexSchemaFactory.buildIndexSchema(schemaFileName, solrConfig);

  h.getCore().setLatestSchema(indexSchema);
  IndexWriterConfig iwc = solrIndexConfig.toIndexWriterConfig(h.getCore());

  final MergePolicy mergePolicy = iwc.getMergePolicy();
  assertNotNull("null mergePolicy", mergePolicy);
  assertTrue("mergePolicy ("+mergePolicy+") is not a SortingMergePolicy", mergePolicy instanceof SortingMergePolicy);
  final SortingMergePolicy sortingMergePolicy = (SortingMergePolicy) mergePolicy;
  final Sort expected = new Sort(new SortField(expectedFieldName, expectedFieldType, expectedFieldSortDescending));
  final Sort actual = sortingMergePolicy.getSort();
  assertEquals("SortingMergePolicy.getSort", expected, actual);
}
 
Example 2
Source File: ShardFieldSortedHitQueue.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
Comparator<ShardDoc> getCachedComparator(SortField sortField, IndexSearcher searcher) {
  SortField.Type type = sortField.getType();
  if (type == SortField.Type.SCORE) {
    return (o1, o2) -> {
      final float f1 = o1.score;
      final float f2 = o2.score;
      if (f1 < f2)
        return -1;
      if (f1 > f2)
        return 1;
      return 0;
    };
  } else if (type == SortField.Type.REWRITEABLE) {
    try {
      sortField = sortField.rewrite(searcher);
    } catch (IOException e) {
      throw new SolrException(SERVER_ERROR, "Exception rewriting sort field " + sortField, e);
    }
  }
  return comparatorFieldComparator(sortField);
}
 
Example 3
Source File: SortingMergePolicyFactory.java    From linden with Apache License 2.0 6 votes vote down vote up
@Override
public MergePolicy getInstance(Map<String, String> params) throws IOException {
  String field = params.get(SORT_FIELD);
  SortField.Type sortFieldType = SortField.Type.DOC;
  if (params.containsKey(SORT_FIELD_TYPE)) {
    sortFieldType = SortField.Type.valueOf(params.get(SORT_FIELD_TYPE).toUpperCase());
  }

  if (sortFieldType == SortField.Type.DOC) {
    throw new IOException(
        "Relying on internal lucene DocIDs is not guaranteed to work, this is only an implementation detail.");
  }

  boolean desc = true;
  if (params.containsKey(SORT_DESC)) {
    try {
      desc = Boolean.valueOf(params.get(SORT_DESC));
    } catch (Exception e) {
      desc = true;
    }
  }
  SortField sortField = new SortField(field, sortFieldType, desc);
  Sort sort = new Sort(sortField);
  return new SortingMergePolicyDecorator(new TieredMergePolicy(), sort);
}
 
Example 4
Source File: IndexNumericFieldData.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private NumericType(int requiredBits, boolean floatingPoint, SortField.Type type, Number minValue, Number maxValue) {
    this.requiredBits = requiredBits;
    this.floatingPoint = floatingPoint;
    this.type = type;
    this.minValue = minValue;
    this.maxValue = maxValue;
}
 
Example 5
Source File: FieldType.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Same as {@link #getSortField} but using {@link SortedNumericSortField}.
 */
protected static SortField getSortedNumericSortField(SchemaField field, SortField.Type sortType,
                                                     SortedNumericSelector.Type selector,
                                                     boolean reverse, Object missingLow, Object missingHigh) {
                                                 
  field.checkSortability();
  SortField sf = new SortedNumericSortField(field.getName(), sortType, reverse, selector);
  applySetMissingValue(field, sf, missingLow, missingHigh);
  
  return sf;
}
 
Example 6
Source File: ShardFieldSortedHitQueue.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
public ShardFieldSortedHitQueue(SortField[] fields, int size, IndexSearcher searcher) {
  super(size);
  final int n = fields.length;
  comparators = new Comparator[n];
  this.fields = new SortField[n];
  for (int i = 0; i < n; ++i) {

    // keep track of the named fields
    SortField.Type type = fields[i].getType();
    if (type!=SortField.Type.SCORE && type!=SortField.Type.DOC) {
      fieldNames.add(fields[i].getField());
    }

    String fieldname = fields[i].getField();
    comparators[i] = getCachedComparator(fields[i], searcher);

   if (fields[i].getType() == SortField.Type.STRING) {
      this.fields[i] = new SortField(fieldname, SortField.Type.STRING,
          fields[i].getReverse());
    } else {
      this.fields[i] = new SortField(fieldname, fields[i].getType(),
          fields[i].getReverse());
    }

    //System.out.println("%%%%%%%%%%%%%%%%%% got "+fields[i].getType() +"   for "+ fieldname +"  fields[i].getReverse(): "+fields[i].getReverse());
  }
}
 
Example 7
Source File: CoreIndexedStoreImpl.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private Sort toLuceneSort(List<SearchFieldSorting> orderings) {
  if (orderings.isEmpty()) {
    return new Sort();
  }

  SortField[] sortFields = new SortField[orderings.size()];
  int i = 0;
  for(SearchFieldSorting ordering: orderings) {
    final SortField.Type fieldType;
    switch(ordering.getType()) {
    case STRING:
      fieldType = SortField.Type.STRING;
      break;
    case LONG:
      fieldType = SortField.Type.LONG;
      break;
    case DOUBLE:
      fieldType = SortField.Type.DOUBLE;
      break;
    case INTEGER:
      fieldType = SortField.Type.INT;
      break;
    default:
      throw new AssertionError("Unknown field type: " + ordering.getType());
    }
    sortFields[i++] = new SortField(ordering.getField(), fieldType, ordering.getOrder() != SortOrder.ASCENDING);
  }

  return new Sort(sortFields);
}
 
Example 8
Source File: SortSymbolVisitor.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public SortField visitFunction(final Function function, final SortSymbolContext context) {
    // our boolean functions return booleans, no BytesRefs, handle them differently
    // this is a hack, but that is how it worked before, so who cares :)
    SortField.Type type = function.valueType().equals(DataTypes.BOOLEAN) ? null : LUCENE_TYPE_MAP.get(function.valueType());
    SortField.Type reducedType = MoreObjects.firstNonNull(type, SortField.Type.DOC);
    return customSortField(function.toString(), function, context, reducedType, type == null);
}
 
Example 9
Source File: FloatValuesComparatorSource.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public SortField.Type reducedType() {
    return SortField.Type.FLOAT;
}
 
Example 10
Source File: DoubleValuesComparatorSource.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public SortField.Type reducedType() {
    return SortField.Type.DOUBLE;
}
 
Example 11
Source File: LuceneRecord.java    From HongsCORE with MIT License 4 votes vote down vote up
/**
 * 组织排序规则
 * 可覆盖此方法进行补充排序
 *
 * @param of
 * @param rd
 * @throws HongsException
 */
protected void padSrt(List<SortField> of, Map rd) throws HongsException {
    Set<String> ob = Synt.toTerms(rd.get(Cnst.OB_KEY));
    if (ob == null) {
        return;
    }

    Map<String, Map> fields = getFields();
    for (String fn: ob) {
        // 相关
        if (fn.equals("-")) {
            of.add(SortField.FIELD_SCORE);
            continue;
        }

        // 文档
        if (fn.equals("_")) {
            of.add(SortField.FIELD_DOC);
            continue;
        }

        // 逆序
        boolean rv = fn.startsWith("-");
        if (rv) fn = fn.substring ( 1 );

        // 自定义排序
        if (! padSrt (of, rd, fn, rv) ) {
            continue;
        }

        Map m  = (Map) fields.get(fn);
        if (m == null) {
            continue ;
        }
        if (! sortable(m)) {
            continue ;
        }

        SortField.Type st;
        String t = datatype(m);
        if (   "int".equals(t)) {
            st = SortField.Type.INT;
        } else
        if (  "long".equals(t)) {
            st = SortField.Type.LONG;
        } else
        if ( "float".equals(t)) {
            st = SortField.Type.FLOAT;
        } else
        if ("double".equals(t)) {
            st = SortField.Type.DOUBLE;
        } else
        if (  "date".equals(t)) {
            st = SortField.Type.LONG;
        } else
        if ("sorted".equals(t)) {
            st = SortField.Type.LONG;
        } else
        if ("search".equals(t)) {
            st = SortField.Type.STRING;
        } else
        if ("string".equals(t)) {
            st = SortField.Type.STRING;
        } else
        {
            continue;
        }

        /**
         * 因为 Lucene 5 必须使用 DocValues 才能排序
         * 在更新数据时, 会加前缀 '#','%' 的排序字段
         * 2020/03/07 多个值的普通排序只能用其中一个
         */
    //  if (repeated(m)) {
    //      of.add(new SortField("%" + fn, st, rv));
    //  } else {
            of.add(new SortField("#" + fn, st, rv));
    //  }
    }
}
 
Example 12
Source File: IndexNumericFieldData.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public final SortField.Type sortFieldType() {
    return type;
}
 
Example 13
Source File: BytesRefFieldComparatorSource.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public SortField.Type reducedType() {
    return SortField.Type.STRING;
}
 
Example 14
Source File: LongValuesComparatorSource.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public SortField.Type reducedType() {
    return SortField.Type.LONG;
}
 
Example 15
Source File: SortConstructor.java    From linden with Apache License 2.0 4 votes vote down vote up
public static Sort constructSort(LindenSearchRequest request, IndexSearcher indexSearcher, LindenConfig config) throws IOException {
  if (!request.isSetSort())
    return null;

  LindenSort lindenSort = request.getSort();
  SortField[] sortFields = new SortField[lindenSort.getFieldsSize()];
  for (int i = 0; i < lindenSort.getFieldsSize(); ++i) {
    LindenSortField field = lindenSort.getFields().get(i);
    SortField.Type type = SortField.Type.STRING;
    boolean isReverse = field.isReverse();
    switch (field.getType()) {
      case STRING:
        type = SortField.Type.STRING;
        break;
      case DOUBLE:
        type = SortField.Type.DOUBLE;
        break;
      case FLOAT:
        type = SortField.Type.FLOAT;
        break;
      case INTEGER:
        type = SortField.Type.INT;
        break;
      case LONG:
        type = SortField.Type.LONG;
        break;
      case SCORE:
        type = SortField.Type.SCORE;
        isReverse = !isReverse;
        break;
      case DISTANCE:
        if (request.isSetSpatialParam()) {
          Point point = SpatialContext.GEO.makePoint(
              request.getSpatialParam().getCoordinate().getLongitude(),
              request.getSpatialParam().getCoordinate().getLatitude());
          ValueSource valueSource = config.getSpatialStrategy().makeDistanceValueSource(point, DistanceUtils.DEG_TO_KM);
          sortFields[i] = valueSource.getSortField(false).rewrite(indexSearcher);
        }
        continue;
    }
    sortFields[i] = new SortField(field.getName(), type, isReverse);
  }
  return new Sort(sortFields);
}
 
Example 16
Source File: SortSymbolVisitor.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
private SortField customSortField(String name,
                                  final Symbol symbol,
                                  final SortSymbolContext context,
                                  final SortField.Type reducedType,
                                  final boolean missingNullValue) {
    CollectInputSymbolVisitor.Context inputContext = inputSymbolVisitor.extractImplementations(symbol);
    List<Input<?>> inputs = inputContext.topLevelInputs();
    assert inputs.size() == 1;
    final Input input = inputs.get(0);
    @SuppressWarnings("unchecked")
    final List<LuceneCollectorExpression> expressions = inputContext.docLevelExpressions();

    return new SortField(name, new IndexFieldData.XFieldComparatorSource() {
        @Override
        public FieldComparator<?> newComparator(String fieldName, int numHits, int sortPos, boolean reversed) throws IOException {
            for (LuceneCollectorExpression collectorExpression : expressions) {
                collectorExpression.startCollect(context.context);
            }
            if (context.context.visitor().required()) {
                return new FieldsVisitorInputFieldComparator(
                        numHits,
                        context.context.visitor(),
                        expressions,
                        input,
                        symbol.valueType(),
                        missingNullValue ? null : missingObject(SortOrder.missing(context.reverseFlag, context.nullFirst), reversed)
                );

            } else {
                return new InputFieldComparator(
                        numHits,
                        expressions,
                        input,
                        symbol.valueType(),
                        missingNullValue ? null : missingObject(SortOrder.missing(context.reverseFlag, context.nullFirst), reversed)
                );
            }
        }

        @Override
        public SortField.Type reducedType() {
            return reducedType;
        }
    }, context.reverseFlag);
}
 
Example 17
Source File: NullFieldComparatorSource.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public SortField.Type reducedType() {
    return sortFieldType;
}
 
Example 18
Source File: NullFieldComparatorSource.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
NullFieldComparatorSource(SortField.Type sortFieldType, boolean reversed, Boolean nullsFirst) {
    this.sortFieldType = sortFieldType;
    missingValue = missingObject(SortOrder.missing(reversed, nullsFirst), reversed);
}
 
Example 19
Source File: FieldType.java    From lucene-solr with Apache License 2.0 3 votes vote down vote up
/**
 * <p>A Helper utility method for use by subclasses.</p>
 * <p>This method deals with:</p>
 * <ul>
 *  <li>{@link SchemaField#checkSortability}</li>
 *  <li>Creating a {@link SortField} on <code>field</code> with the specified 
 *      <code>reverse</code> &amp; <code>sortType</code></li>
 *  <li>Setting the {@link SortField#setMissingValue} to <code>missingLow</code> or <code>missingHigh</code>
 *      as appropriate based on the value of <code>reverse</code> and the 
 *      <code>sortMissingFirst</code> &amp; <code>sortMissingLast</code> properties of the 
 *      <code>field</code></li>
 * </ul>
 *
 * @param field The SchemaField to sort on.  May use <code>sortMissingFirst</code> or <code>sortMissingLast</code> or neither.
 * @param sortType The sort Type of the underlying values in the <code>field</code>
 * @param reverse True if natural order of the <code>sortType</code> should be reversed
 * @param missingLow The <code>missingValue</code> to be used if the other params indicate that docs w/o values should sort as "low" as possible.
 * @param missingHigh The <code>missingValue</code> to be used if the other params indicate that docs w/o values should sort as "high" as possible.
 * @see #getSortedSetSortField
 */
protected static SortField getSortField(SchemaField field, SortField.Type sortType, boolean reverse,
                                        Object missingLow, Object missingHigh) {
  field.checkSortability();

  SortField sf = new SortField(field.getName(), sortType, reverse);
  applySetMissingValue(field, sf, missingLow, missingHigh);
  
  return sf;
}
 
Example 20
Source File: IndexFieldData.java    From Elasticsearch with Apache License 2.0 votes vote down vote up
public abstract SortField.Type reducedType();