Example usage for org.apache.lucene.search SortField getType

List of usage examples for org.apache.lucene.search SortField getType

Introduction

In this page you can find the example usage for org.apache.lucene.search SortField getType.

Prototype

public Type getType() 

Source Link

Document

Returns the type of contents in the field.

Usage

From source file:com.github.rnewson.couchdb.lucene.CustomQueryParser.java

License:Apache License

public static JSONArray toJSON(final SortField[] sortFields) throws JSONException {
    final JSONArray result = new JSONArray();
    for (final SortField field : sortFields) {
        final JSONObject col = new JSONObject();
        col.put("field", field.getField());
        col.put("reverse", field.getReverse());

        final String type;
        switch (field.getType()) {
        case DOC:
            type = "doc";
            break;
        case SCORE:
            type = "score";
            break;
        case INT:
            type = "int";
            break;
        case LONG:
            type = "long";
            break;
        case BYTE:
            type = "byte";
            break;
        case CUSTOM:
            type = "custom";
            break;
        case DOUBLE:
            type = "double";
            break;
        case FLOAT:
            type = "float";
            break;
        case SHORT:
            type = "short";
            break;
        case STRING:
            type = "string";
            break;
        default://w  w  w. j a v a2  s  .  co  m
            type = "unknown";
            break;
        }
        col.put("type", type);
        result.put(col);
    }
    return result;
}

From source file:com.github.rnewson.couchdb.lucene.SearchRequest.java

License:Apache License

private String toString(final SortField[] sortFields) {
    final JSONArray result = new JSONArray();
    for (final SortField field : sortFields) {
        final JSONObject col = new JSONObject();
        col.element("field", field.getField());
        col.element("reverse", field.getReverse());

        final String type;
        switch (field.getType()) {
        case SortField.DOC:
            type = "doc";
            break;
        case SortField.SCORE:
            type = "score";
            break;
        case SortField.INT:
            type = "int";
            break;
        case SortField.LONG:
            type = "long";
            break;
        case SortField.BYTE:
            type = "byte";
            break;
        case SortField.CUSTOM:
            type = "custom";
            break;
        case SortField.DOUBLE:
            type = "double";
            break;
        case SortField.FLOAT:
            type = "float";
            break;
        case SortField.SHORT:
            type = "short";
            break;
        case SortField.STRING:
            type = "string";
            break;
        default://  ww  w.jav a 2  s.c o m
            type = "unknown";
            break;
        }
        col.element("type", type);
        result.add(col);
    }
    return result.toString();
}

From source file:com.senseidb.search.req.SenseiRequestProtoSerializer.java

License:Apache License

private SenseiProtos.SortField convertSortField(SortField sortField) {
    SenseiProtos.SortField.Builder builder = SenseiProtos.SortField.newBuilder();
    if (sortField.getField() != null)
        builder.setField(sortField.getField());

    builder.setType(sortField.getType());

    if (sortField.getLocale() != null)
        builder.setLocale(convertLocale(sortField.getLocale()));

    builder.setReverse(sortField.getReverse());

    return builder.build();
}

From source file:com.stratio.cassandra.lucene.search.sort.GeoDistanceSortFieldTest.java

License:Apache License

@Test
public void testGeoDistanceSortFieldDefaults() {

    Schema schema = schema().mapper("field", geoPointMapper("latitude", "longitude").sorted(true)).build();

    GeoDistanceSortField sortField = new GeoDistanceSortField("field", null, 0.0, 0.0);
    org.apache.lucene.search.SortField luceneSortField = sortField.sortField(schema);

    assertNotNull("SortField is not created", luceneSortField);
    assertEquals("SortField reverse is wrong", SortField.DEFAULT_REVERSE, luceneSortField.getReverse());
    assertEquals("SortField type is wrong", luceneSortField.getType(),
            org.apache.lucene.search.SortField.Type.REWRITEABLE);
}

From source file:lux.compiler.PathOptimizer.java

License:Mozilla Public License

@Override
public OrderByClause visit(OrderByClause orderByClause) {
    LinkedList<SortField> sortFields = new LinkedList<SortField>();
    ArrayList<SortKey> sortKeys = orderByClause.getSortKeys();
    boolean foundUnindexedSort = false;
    int stackOffset = queryStack.size() - sortKeys.size();
    for (int i = 0; i < sortKeys.size(); i++) {
        // pop the queries off the stack that correspond to each sort key in
        // this order by clause.
        // Accumulate a list of contiguous indexed order keys. Merge them
        // with the
        // query on the stack as an ordering criterion (not as a filter)

        // Pull queries from middle of stack since they get pushed in
        // reverse order
        XPathQuery q = queryStack.remove(stackOffset);
        SortKey sortKey = sortKeys.get(i);
        AbstractExpression key = sortKey.getKey();
        if (q.getSortFields() == null) {
            // TODO: analyze the expression, matching against xpath indexes 
            // once we find an unindexed sort field, stop adding sort
            // indexes to the query
            foundUnindexedSort = true;/* ww  w. j  ava  2  s .co  m*/
        } else if (!foundUnindexedSort) {
            // previous analysis determined this order by clause should be optimized
            if (key instanceof FunCall) {
                // field-values() with one argument depends on context 
                FunCall keyFun = (FunCall) key;
                if (keyFun.getName().equals(FunCall.LUX_KEY)
                        || keyFun.getName().equals(FunCall.LUX_FIELD_VALUES)) {
                    if (keyFun.getSubs().length < 2) {
                        throw new LuxException(
                                "lux:key($key) depends on the context where there is no context defined");
                    }
                }
            }
            String order = sortKey.getOrder().getValue().toString();
            SortField sortField = q.getSortFields()[0];
            if (!sortKey.isEmptyLeast()) {
                // empty greatest
                sortField = new SortField(sortField.getField(), SearchResultIterator.MISSING_LAST,
                        order.equals("descending"));
            } else if (order.equals("descending")) {
                // reverse sort order
                sortField = new SortField(sortField.getField(), sortField.getType(), true);
            }
            // add at the beginning: fields pop off the stack in reverse
            // order
            sortFields.add(sortField);
            sortKeys.remove(i);
            --i; // don't advance: we shrank the list
        }
    }
    if (sortFields.isEmpty()) {
        push(MATCH_ALL);
    } else {
        XPathQuery query = XPathQuery.getQuery(MATCH_ALL.getBooleanQuery(), null, MATCH_ALL.getFacts(),
                MATCH_ALL.getResultType(), indexConfig, sortFields.toArray(new SortField[sortFields.size()]));
        push(query);
    }
    return orderByClause;
}

From source file:org.apache.solr.handler.component.HelloHandlerComponent.java

License:Apache License

protected void doFieldSortValues(ResponseBuilder rb, SolrIndexSearcher searcher) throws IOException {
    SolrQueryRequest req = rb.req;// w w  w. j  av  a 2 s.  co  m
    SolrQueryResponse rsp = rb.rsp;
    final CharsRef spare = new CharsRef();
    // The query cache doesn't currently store sort field values, and SolrIndexSearcher doesn't
    // currently have an option to return sort field values.  Because of this, we
    // take the documents given and re-derive the sort values.
    boolean fsv = req.getParams().getBool(ResponseBuilder.FIELD_SORT_VALUES, false);
    if (fsv) {
        Sort sort = searcher.weightSort(rb.getSortSpec().getSort());
        SortField[] sortFields = sort == null ? new SortField[] { SortField.FIELD_SCORE } : sort.getSort();
        NamedList<Object[]> sortVals = new NamedList<Object[]>(); // order is important for the sort fields
        Field field = new StringField("dummy", "", Field.Store.NO); // a dummy Field
        IndexReaderContext topReaderContext = searcher.getTopReaderContext();
        List<AtomicReaderContext> leaves = topReaderContext.leaves();
        AtomicReaderContext currentLeaf = null;
        if (leaves.size() == 1) {
            // if there is a single segment, use that subReader and avoid looking up each time
            currentLeaf = leaves.get(0);
            leaves = null;
        }

        DocList docList = rb.getResults().docList;

        // sort ids from lowest to highest so we can access them in order
        int nDocs = docList.size();
        long[] sortedIds = new long[nDocs];
        DocIterator it = rb.getResults().docList.iterator();
        for (int i = 0; i < nDocs; i++) {
            sortedIds[i] = (((long) it.nextDoc()) << 32) | i;
        }
        Arrays.sort(sortedIds);

        for (SortField sortField : sortFields) {
            SortField.Type type = sortField.getType();
            if (type == SortField.Type.SCORE || type == SortField.Type.DOC)
                continue;

            FieldComparator comparator = null;

            String fieldname = sortField.getField();
            FieldType ft = fieldname == null ? null : req.getSchema().getFieldTypeNoEx(fieldname);

            Object[] vals = new Object[nDocs];

            int lastIdx = -1;
            int idx = 0;

            for (long idAndPos : sortedIds) {
                int doc = (int) (idAndPos >>> 32);
                int position = (int) idAndPos;

                if (leaves != null) {
                    idx = ReaderUtil.subIndex(doc, leaves);
                    currentLeaf = leaves.get(idx);
                    if (idx != lastIdx) {
                        // we switched segments.  invalidate comparator.
                        comparator = null;
                    }
                }

                if (comparator == null) {
                    comparator = sortField.getComparator(1, 0);
                    comparator = comparator.setNextReader(currentLeaf);
                }

                doc -= currentLeaf.docBase; // adjust for what segment this is in
                comparator.copy(0, doc);
                Object val = comparator.value(0);

                // Sortable float, double, int, long types all just use a string
                // comparator. For these, we need to put the type into a readable
                // format.  One reason for this is that XML can't represent all
                // string values (or even all unicode code points).
                // indexedToReadable() should be a no-op and should
                // thus be harmless anyway (for all current ways anyway)
                if (val instanceof String) {
                    field.setStringValue((String) val);
                    val = ft.toObject(field);
                }

                // Must do the same conversion when sorting by a
                // String field in Lucene, which returns the terms
                // data as BytesRef:
                if (val instanceof BytesRef) {
                    UnicodeUtil.UTF8toUTF16((BytesRef) val, spare);
                    field.setStringValue(spare.toString());
                    val = ft.toObject(field);
                }

                vals[position] = val;
            }

            sortVals.add(fieldname, vals);
        }

        rsp.add("sort_values", sortVals);
    }
}

From source file:org.apache.solr.handler.component.QueryComponent.java

License:Apache License

protected void doFieldSortValues(ResponseBuilder rb, SolrIndexSearcher searcher) throws IOException {
    SolrQueryRequest req = rb.req;/*from  www. j  a  v  a 2s.  c  o m*/
    SolrQueryResponse rsp = rb.rsp;
    final CharsRef spare = new CharsRef();
    // The query cache doesn't currently store sort field values, and SolrIndexSearcher doesn't
    // currently have an option to return sort field values.  Because of this, we
    // take the documents given and re-derive the sort values.
    boolean fsv = req.getParams().getBool(ResponseBuilder.FIELD_SORT_VALUES, false);
    if (fsv) {
        Sort sort = searcher.weightSort(rb.getSortSpec().getSort());
        SortField[] sortFields = sort == null ? new SortField[] { SortField.FIELD_SCORE } : sort.getSort();
        NamedList<Object[]> sortVals = new NamedList<Object[]>(); // order is important for the sort fields
        Field field = new StringField("dummy", "", Field.Store.NO); // a dummy Field
        IndexReaderContext topReaderContext = searcher.getTopReaderContext();
        List<AtomicReaderContext> leaves = topReaderContext.leaves();
        AtomicReaderContext currentLeaf = null;
        if (leaves.size() == 1) {
            // if there is a single segment, use that subReader and avoid looking up each time
            currentLeaf = leaves.get(0);
            leaves = null;
        }

        DocList docList = rb.getResults().docList;

        // sort ids from lowest to highest so we can access them in order
        int nDocs = docList.size();
        long[] sortedIds = new long[nDocs];
        DocIterator it = rb.getResults().docList.iterator();
        for (int i = 0; i < nDocs; i++) {
            sortedIds[i] = (((long) it.nextDoc()) << 32) | i;
        }
        Arrays.sort(sortedIds);

        for (SortField sortField : sortFields) {
            SortField.Type type = sortField.getType();
            if (type == SortField.Type.SCORE || type == SortField.Type.DOC)
                continue;

            FieldComparator comparator = null;

            String fieldname = sortField.getField();
            FieldType ft = fieldname == null ? null : searcher.getSchema().getFieldTypeNoEx(fieldname);

            Object[] vals = new Object[nDocs];

            int lastIdx = -1;
            int idx = 0;

            for (long idAndPos : sortedIds) {
                int doc = (int) (idAndPos >>> 32);
                int position = (int) idAndPos;

                if (leaves != null) {
                    idx = ReaderUtil.subIndex(doc, leaves);
                    currentLeaf = leaves.get(idx);
                    if (idx != lastIdx) {
                        // we switched segments.  invalidate comparator.
                        comparator = null;
                    }
                }

                if (comparator == null) {
                    comparator = sortField.getComparator(1, 0);
                    comparator = comparator.setNextReader(currentLeaf);
                }

                doc -= currentLeaf.docBase; // adjust for what segment this is in
                comparator.copy(0, doc);
                Object val = comparator.value(0);

                // Sortable float, double, int, long types all just use a string
                // comparator. For these, we need to put the type into a readable
                // format.  One reason for this is that XML can't represent all
                // string values (or even all unicode code points).
                // indexedToReadable() should be a no-op and should
                // thus be harmless anyway (for all current ways anyway)
                if (val instanceof String) {
                    field.setStringValue((String) val);
                    val = ft.toObject(field);
                }

                // Must do the same conversion when sorting by a
                // String field in Lucene, which returns the terms
                // data as BytesRef:
                if (val instanceof BytesRef) {
                    UnicodeUtil.UTF8toUTF16((BytesRef) val, spare);
                    field.setStringValue(spare.toString());
                    val = ft.toObject(field);
                }

                vals[position] = val;
            }

            sortVals.add(fieldname, vals);
        }

        rsp.add("sort_values", sortVals);
    }
}

From source file:org.apache.solr.handler.component.QueryElevationComponent.java

License:Apache License

private Sort modifySort(SortField[] current, boolean force, ElevationComparatorSource comparator) {
    boolean modify = false;
    ArrayList<SortField> sorts = new ArrayList<SortField>(current.length + 1);
    // Perhaps force it to always sort by score
    if (force && current[0].getType() != SortField.Type.SCORE) {
        sorts.add(new SortField("_elevate_", comparator, true));
        modify = true;//ww  w. ja  v a 2 s. c  om
    }
    for (SortField sf : current) {
        if (sf.getType() == SortField.Type.SCORE) {
            sorts.add(new SortField("_elevate_", comparator, !sf.getReverse()));
            modify = true;
        }
        sorts.add(sf);
    }

    return modify ? new Sort(sorts.toArray(new SortField[sorts.size()])) : null;
}

From source file:org.apache.solr.handler.component.ShardFieldSortedHitQueue.java

License:Apache License

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;
        };/* w ww .j a  va2  s.co m*/
    } 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);
}

From source file:org.apache.solr.search.CursorMark.java

License:Apache License

/**
 * Generates an empty CursorMark bound for use with the 
 * specified schema and {@link SortSpec}.
 *
 * @param schema used for basic validation
 * @param sortSpec bound to this totem (un)marshalling serialized values
 *///w  w  w  .ja  va  2 s  .  c o m
public CursorMark(IndexSchema schema, SortSpec sortSpec) {

    final SchemaField uniqueKey = schema.getUniqueKeyField();
    if (null == uniqueKey) {
        throw new SolrException(ErrorCode.BAD_REQUEST,
                "Cursor functionality is not available unless the IndexSchema defines a uniqueKey field");
    }

    final Sort sort = sortSpec.getSort();
    if (null == sort) {
        // pure score, by definition we don't include the mandatyr uniqueKey tie breaker
        throw new SolrException(ErrorCode.BAD_REQUEST,
                "Cursor functionality requires a sort containing a uniqueKey field tie breaker");
    }

    if (!sortSpec.getSchemaFields().contains(uniqueKey)) {
        throw new SolrException(ErrorCode.BAD_REQUEST,
                "Cursor functionality requires a sort containing a uniqueKey field tie breaker");
    }

    if (0 != sortSpec.getOffset()) {
        throw new SolrException(ErrorCode.BAD_REQUEST, "Cursor functionality requires start=0");
    }

    for (SortField sf : sort.getSort()) {
        if (sf.getType().equals(SortField.Type.DOC)) {
            throw new SolrException(ErrorCode.BAD_REQUEST,
                    "Cursor functionality can not be used with internal doc ordering sort: _docid_");
        }
    }

    if (sort.getSort().length != sortSpec.getSchemaFields().size()) {
        throw new SolrException(ErrorCode.SERVER_ERROR, "Cursor SortSpec failure: sort length != SchemaFields: "
                + sort.getSort().length + " != " + sortSpec.getSchemaFields().size());
    }

    this.sortSpec = sortSpec;
    this.values = null;
}