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

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

Introduction

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

Prototype

public String getField() 

Source Link

Document

Returns the name of 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://from   w  ww  .  j  a v  a2s. c  om
            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:/*from w  w  w .  jav a2 s .  c om*/
            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.SimpleSortFieldTest.java

License:Apache License

@Test
public void testSortFieldDefaults() {

    Schema schema = schema().mapper("field", stringMapper().sorted(true)).build();

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

    assertNotNull("SortField is not created", luceneSortField);
    assertEquals("SortField name is wrong", "field", luceneSortField.getField());
    assertEquals("SortField reverse is wrong", SortField.DEFAULT_REVERSE, luceneSortField.getReverse());
}

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

License:Apache License

@Test
public void testSimpleSortField() {

    Schema schema = schema().mapper("field", stringMapper().sorted(true)).build();

    SimpleSortField sortField = new SimpleSortField("field", false);
    org.apache.lucene.search.SortField luceneSortField = sortField.sortField(schema);

    assertNotNull("SortField is not created", luceneSortField);
    assertEquals("SortField name is wrong", "field", luceneSortField.getField());
    assertFalse("SortField reverse is wrong", luceneSortField.getReverse());
}

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

License:Apache License

@Test
public void testSortFieldReverse() {

    Schema schema = schema().mapper("field", stringMapper().sorted(true)).build();

    SimpleSortField sortField = new SimpleSortField("field", true);
    org.apache.lucene.search.SortField luceneSortField = sortField.sortField(schema);

    assertNotNull("SortField is not created", luceneSortField);
    assertEquals("SortField name is wrong", "field", luceneSortField.getField());
    assertTrue("sortField reverse is wrong", luceneSortField.getReverse());
}

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 a va 2  s.  c  o 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.alfresco.repo.search.impl.querymodel.impl.lucene.LuceneQueryEngine.java

License:Open Source License

public QueryEngineResults executeQuery(Query query, QueryOptions options,
        FunctionEvaluationContext functionContext) {
    Set<String> selectorGroup = null;
    if (query.getSource() != null) {
        List<Set<String>> selectorGroups = query.getSource().getSelectorGroups(functionContext);

        if (selectorGroups.size() == 0) {
            throw new UnsupportedOperationException("No selectors");
        }/*  w  ww.ja  v  a2s  .co  m*/

        if (selectorGroups.size() > 1) {
            throw new UnsupportedOperationException("Advanced join is not supported");
        }

        selectorGroup = selectorGroups.get(0);
    }

    SearchParameters searchParameters = new SearchParameters();
    if (options.getLocales().size() > 0) {
        for (Locale locale : options.getLocales()) {
            searchParameters.addLocale(locale);
        }
    }
    searchParameters.excludeDataInTheCurrentTransaction(!options.isIncludeInTransactionData());
    searchParameters.setSkipCount(options.getSkipCount());
    searchParameters.setMaxPermissionChecks(options.getMaxPermissionChecks());
    searchParameters.setMaxPermissionCheckTimeMillis(options.getMaxPermissionCheckTimeMillis());
    searchParameters.setDefaultFieldName(options.getDefaultFieldName());
    searchParameters.setMlAnalaysisMode(options.getMlAnalaysisMode());
    if (options.getMaxItems() >= 0) {
        searchParameters.setLimitBy(LimitBy.FINAL_SIZE);
        searchParameters.setLimit(options.getMaxItems());
        searchParameters.setMaxItems(options.getMaxItems());
    } else {
        searchParameters.setLimitBy(LimitBy.UNLIMITED);
    }
    searchParameters.setUseInMemorySort(options.getUseInMemorySort());
    searchParameters.setMaxRawResultSetSizeForInMemorySort(options.getMaxRawResultSetSizeForInMemorySort());
    searchParameters.setBulkFetchEnabled(options.isBulkFetchEnabled());
    searchParameters.setQueryConsistency(options.getQueryConsistency());

    try {
        StoreRef storeRef = options.getStores().get(0);
        searchParameters.addStore(storeRef);
        if (query instanceof LuceneQueryBuilder) {
            SearchService searchService = indexAndSearcher.getSearcher(storeRef,
                    options.isIncludeInTransactionData());
            if (searchService instanceof LuceneSearcher) {
                LuceneSearcher luceneSearcher = (LuceneSearcher) searchService;
                ClosingIndexSearcher searcher = luceneSearcher.getClosingIndexSearcher();
                LuceneQueryBuilderContext<org.apache.lucene.search.Query, Sort, ParseException> luceneContext = new LuceneQueryBuilderContextImpl(
                        dictionaryService, namespaceService, tenantService, searchParameters,
                        indexAndSearcher.getDefaultMLSearchAnalysisMode(), searcher.getIndexReader());

                @SuppressWarnings("unchecked")
                LuceneQueryBuilder<org.apache.lucene.search.Query, Sort, ParseException> builder = (LuceneQueryBuilder<org.apache.lucene.search.Query, Sort, ParseException>) query;
                org.apache.lucene.search.Query luceneQuery = builder.buildQuery(selectorGroup, luceneContext,
                        functionContext);

                if (logger.isDebugEnabled()) {
                    logger.debug("Executing lucene query: " + luceneQuery);
                }

                Sort sort = builder.buildSort(selectorGroup, luceneContext, functionContext);

                Hits hits = searcher.search(luceneQuery);

                boolean postSort = false;
                ;
                if (sort != null) {
                    postSort = searchParameters.usePostSort(hits.length(), useInMemorySort,
                            maxRawResultSetSizeForInMemorySort);
                    if (postSort == false) {
                        hits = searcher.search(luceneQuery, sort);
                    }
                }

                ResultSet answer;
                ResultSet result = new LuceneResultSet(hits, searcher, nodeService, tenantService,
                        searchParameters, indexAndSearcher);
                if (postSort) {
                    if (sort != null) {
                        for (SortField sf : sort.getSort()) {
                            searchParameters.addSort(sf.getField(), !sf.getReverse());
                        }
                    }

                    ResultSet sorted = new SortedResultSet(result, nodeService,
                            builder.buildSortDefinitions(selectorGroup, luceneContext, functionContext),
                            namespaceService, dictionaryService, searchParameters.getSortLocale());
                    answer = sorted;
                } else {
                    answer = result;
                }
                ResultSet rs = new PagingLuceneResultSet(answer, searchParameters, nodeService);

                Map<Set<String>, ResultSet> map = new HashMap<Set<String>, ResultSet>(1);
                map.put(selectorGroup, rs);
                return new QueryEngineResults(map);
            } else {
                throw new UnsupportedOperationException();
            }
        } else {
            throw new UnsupportedOperationException();
        }
    } catch (ParseException e) {
        throw new SearcherException("Failed to parse query: " + e);
    } catch (IOException e) {
        throw new SearcherException("IO exception during search", e);
    }
}

From source file:org.apache.jackrabbit.core.query.lucene.SearchIndex.java

License:Apache License

/**
 * Creates sort fields for the ordering specifications.
 *
 * @param orderings the ordering specifications.
 * @return the sort fields.//from ww  w . j a  v  a2 s .  c o  m
 */
protected SortField[] createSortFields(OrderingImpl[] orderings) {
    List<SortField> sortFields = new ArrayList<SortField>();
    for (final OrderingImpl ordering : orderings) {
        QOMTreeVisitor visitor = new DefaultTraversingQOMTreeVisitor() {

            public Object visit(LengthImpl node, Object data) throws Exception {
                PropertyValueImpl propValue = (PropertyValueImpl) node.getPropertyValue();
                return new SortField(propValue.getPropertyQName().toString(), new LengthSortComparator(),
                        !ordering.isAscending());
            }

            public Object visit(LowerCaseImpl node, Object data) throws Exception {
                SortField sf = (SortField) super.visit(node, data);
                return new SortField(sf.getField(), new LowerCaseSortComparator(sf.getFactory()),
                        sf.getReverse());
            }

            public Object visit(UpperCaseImpl node, Object data) throws Exception {
                SortField sf = (SortField) super.visit(node, data);
                return new SortField(sf.getField(), new UpperCaseSortComparator(sf.getFactory()),
                        sf.getReverse());
            }

            public Object visit(FullTextSearchScoreImpl node, Object data) throws Exception {
                // TODO: selector ignored
                return new SortField(null, SortField.SCORE, ordering.isAscending());
            }

            public Object visit(NodeLocalNameImpl node, Object data) throws Exception {
                return new SortField(FieldNames.LOCAL_NAME, SortField.STRING, !ordering.isAscending());
            }

            public Object visit(NodeNameImpl node, Object data) throws Exception {
                return new SortField(FieldNames.LABEL, SortField.STRING, !ordering.isAscending());
            }

            public Object visit(PropertyValueImpl node, Object data) throws Exception {
                return new SortField(node.getPropertyQName().toString(), scs, !ordering.isAscending());
            }

            public Object visit(OrderingImpl node, Object data) throws Exception {
                return ((DynamicOperandImpl) node.getOperand()).accept(this, data);
            }
        };
        try {
            sortFields.add((SortField) ordering.accept(visitor, null));
        } catch (Exception e) {
            // TODO
        }
    }
    return sortFields.toArray(new SortField[sortFields.size()]);
}

From source file:org.apache.jackrabbit.core.query.lucene.Ordering.java

License:Apache License

/**
 * Creates an ordering from a JCR QOM ordering.
 *
 * @param ordering   the JCR QOM ordering specification.
 * @param scs        the sort comparator source from the search index.
 * @param nsMappings the index internal namespace mappings.
 * @return an ordering.//from w  w w  . ja  v  a 2 s .c om
 * @throws RepositoryException if an error occurs while translating the JCR
 *                             QOM ordering.
 */
public static Ordering fromQOM(final OrderingImpl ordering, final SharedFieldComparatorSource scs,
        final NamespaceMappings nsMappings) throws RepositoryException {
    final Name[] selectorName = new Name[1];
    QOMTreeVisitor visitor = new DefaultTraversingQOMTreeVisitor() {

        public Object visit(LengthImpl node, Object data) throws Exception {
            PropertyValueImpl propValue = (PropertyValueImpl) node.getPropertyValue();
            selectorName[0] = propValue.getSelectorQName();
            return new SortField(propValue.getPropertyQName().toString(), new LengthSortComparator(nsMappings),
                    !ordering.isAscending());
        }

        public Object visit(LowerCaseImpl node, Object data) throws Exception {
            SortField sf = (SortField) ((DynamicOperandImpl) node.getOperand()).accept(this, data);
            selectorName[0] = node.getSelectorQName();
            return new SortField(sf.getField(), new LowerCaseSortComparator(sf.getComparatorSource()),
                    !ordering.isAscending());
        }

        public Object visit(UpperCaseImpl node, Object data) throws Exception {
            SortField sf = (SortField) ((DynamicOperandImpl) node.getOperand()).accept(this, data);
            selectorName[0] = node.getSelectorQName();
            return new SortField(sf.getField(), new UpperCaseSortComparator(sf.getComparatorSource()),
                    !ordering.isAscending());
        }

        public Object visit(FullTextSearchScoreImpl node, Object data) throws Exception {
            selectorName[0] = node.getSelectorQName();
            return new SortField(null, SortField.SCORE, !ordering.isAscending());
        }

        public Object visit(NodeLocalNameImpl node, Object data) throws Exception {
            selectorName[0] = node.getSelectorQName();
            return new SortField(FieldNames.LOCAL_NAME, SortField.STRING, !ordering.isAscending());
        }

        public Object visit(NodeNameImpl node, Object data) throws Exception {
            selectorName[0] = node.getSelectorQName();
            return new SortField(FieldNames.LABEL, SortField.STRING, !ordering.isAscending());
        }

        public Object visit(PropertyValueImpl node, Object data) throws Exception {
            selectorName[0] = node.getSelectorQName();
            return new SortField(node.getPropertyQName().toString(), scs, !ordering.isAscending());
        }

        public Object visit(OrderingImpl node, Object data) throws Exception {
            return ((DynamicOperandImpl) node.getOperand()).accept(this, data);
        }
    };
    try {
        SortField field = (SortField) ordering.accept(visitor, null);
        return new Ordering(selectorName[0], field);
    } catch (Exception e) {
        throw new RepositoryException(e);
    }
}