List of usage examples for org.apache.lucene.search Sort Sort
public Sort(SortField... fields)
From source file:com.edgenius.wiki.search.service.AbstractSearchService.java
License:Open Source License
private Sort createSort(String[] advance) { if (advance != null) { //parse all possible type for (String str : advance) { if (str.length() < 2) continue; if (str.charAt(0) == SearchService.ADV_GROUP_BY) { if (NumberUtils .toInt(Character.valueOf(str.charAt(1)).toString()) == SearchService.GROUP_SPACE) { return new Sort(new SortField(FieldName.UNSEARCH_SPACE_UNIXNAME, SortField.STRING)); } else if (NumberUtils .toInt(Character.valueOf(str.charAt(1)).toString()) == SearchService.GROUP_TYPE) { return new Sort(new SortField(FieldName.DOC_TYPE, SortField.INT)); }/*from w w w . ja v a 2 s . c o m*/ } } } return null; }
From source file:com.epam.catgenome.dao.index.FeatureIndexDao.java
License:Open Source License
/** * Searches genes by it's ID in project's gene files. Minimum featureId prefix length == 2 * * @param featureId a feature ID prefix to search for * @param featureFiles a gene file ,from which to search * @return a {@code List} of {@code FeatureIndexEntry} * @throws IOException//from ww w . j a v a 2s.c o m */ public IndexSearchResult<FeatureIndexEntry> searchFeatures(String featureId, List<? extends FeatureFile> featureFiles, Integer maxResultsCount) throws IOException { if (featureId == null || featureId.length() < 2) { return new IndexSearchResult<>(Collections.emptyList(), false, 0); } BooleanQuery.Builder mainBuilder = new BooleanQuery.Builder(); PrefixQuery prefixQuery = new PrefixQuery( new Term(FeatureIndexFields.FEATURE_ID.getFieldName(), featureId.toLowerCase())); BooleanQuery.Builder prefixQueryBuilder = new BooleanQuery.Builder(); prefixQueryBuilder.add(prefixQuery, BooleanClause.Occur.SHOULD); prefixQueryBuilder.add( new PrefixQuery(new Term(FeatureIndexFields.FEATURE_NAME.getFieldName(), featureId.toLowerCase())), BooleanClause.Occur.SHOULD); mainBuilder.add(prefixQueryBuilder.build(), BooleanClause.Occur.MUST); BooleanQuery.Builder featureTypeBuilder = new BooleanQuery.Builder(); featureTypeBuilder.add( new TermQuery( new Term(FeatureIndexFields.FEATURE_TYPE.getFieldName(), FeatureType.GENE.getFileValue())), BooleanClause.Occur.SHOULD); featureTypeBuilder.add( new TermQuery( new Term(FeatureIndexFields.FEATURE_TYPE.getFieldName(), FeatureType.MRNA.getFileValue())), BooleanClause.Occur.SHOULD); featureTypeBuilder.add(new TermQuery( new Term(FeatureIndexFields.FEATURE_TYPE.getFieldName(), FeatureType.BOOKMARK.getFileValue())), BooleanClause.Occur.SHOULD); featureTypeBuilder.add(new TermQuery( new Term(FeatureIndexFields.FEATURE_TYPE.getFieldName(), FeatureType.BED_FEATURE.getFileValue())), BooleanClause.Occur.SHOULD); mainBuilder.add(featureTypeBuilder.build(), BooleanClause.Occur.MUST); return searchFileIndexes(featureFiles, mainBuilder.build(), null, maxResultsCount, new Sort(new SortField(FeatureIndexFields.FEATURE_NAME.getFieldName(), SortField.Type.STRING))); }
From source file:com.epam.catgenome.dao.index.FeatureIndexDao.java
License:Open Source License
private void setSorting(List<VcfFilterForm.OrderBy> orderBy, GroupingSearch groupingSearch, List<? extends FeatureFile> files) throws IOException { if (CollectionUtils.isNotEmpty(orderBy)) { ArrayList<SortField> sortFields = new ArrayList<>(); for (VcfFilterForm.OrderBy o : orderBy) { IndexSortField sortField = IndexSortField.getByName(o.getField()); if (sortField == null) { VcfFilterInfo info = vcfManager .getFiltersInfo(files.stream().map(BaseEntity::getId).collect(Collectors.toList())); InfoItem infoItem = info.getInfoItemMap().get(o.getField()); Assert.notNull(infoItem, "Unknown sort field: " + o.getField()); SortField.Type type = determineSortType(infoItem); SortField sf = new SortField(infoItem.getName().toLowerCase(), type, o.isDesc()); setMissingValuesOrder(sf, type, o.isDesc()); sortFields.add(sf);//from www . j av a 2s . c o m } else { SortField sf = new SortField(sortField.getField().fieldName, sortField.getType(), o.isDesc()); setMissingValuesOrder(sf, sortField.getType(), o.isDesc()); sortFields.add(sf); } } groupingSearch.setGroupSort(new Sort(sortFields.toArray(new SortField[sortFields.size()]))); } }
From source file:com.esri.gpt.catalog.lucene.LuceneQueryAdapter.java
License:Apache License
/** * Makes the sort option for the query.//w w w . ja v a 2s . c om * @param discoveryQuery the active query */ private Sort makeSortOption(DiscoveryQuery discoveryQuery) { Sort sortOption = null; Sortables sortables = discoveryQuery.getSortables(); ArrayList<SortField> sortFields = new ArrayList<SortField>(); if ((sortables != null) && (sortables.size() > 0)) { Storeable storable; for (Sortable sortable : sortables) { storable = (Storeable) sortable.getStorable(); if (storable != null) { DatastoreField comparisonField = storable.getComparisonField(); if (comparisonField != null) { int sortFieldType = comparisonField.sortFieldType(); LOGGER.finer("Sorting on " + comparisonField.getName() + " " + sortable.getDirection()); if (sortable.getDirection().equals(Sortable.SortDirection.ASC)) { sortFields.add(new SortField(comparisonField.getName(), sortFieldType, false)); } else { sortFields.add(new SortField(comparisonField.getName(), sortFieldType, true)); } } } } } // if sort fields have not been supplied and the query does not contain // a scored expression then sort by descending date if (sortFields.size() == 0) { if (!this.getHasScoredExpression()) { String sModifiedDate = Storeables.FIELD_DATEMODIFIED; sortFields.add(new SortField(sModifiedDate, SortField.LONG, true)); LOGGER.finer("Auto-sorting on " + sModifiedDate + " DESC"); } else { LOGGER.finer("Sorting on relevance."); } } if (sortFields.size() > 0) { sortOption = new Sort(sortFields.toArray(new SortField[0])); } return sortOption; }
From source file:com.esri.gpt.server.assertion.handler.AsnCommentHandler.java
License:Apache License
/** * Queries comments./*from www . j a va 2s.com*/ * @param context the assertion operation context * @throws Exception if an exception occurs */ private void query(AsnContext context) throws Exception { // initialize AsnOperation operation = context.getOperation(); AsnAssertionSet asnSet = operation.getAssertionSet(); AsnValueType vType = asnSet.getValueType(); String subject = operation.getSubject().getURN(); String predicate = vType.getRdfPredicate(); // build a query to match all occurrences of the subject/predicate pair BooleanQuery query = new BooleanQuery(); Query qSubject = new TermQuery(new Term(AsnConstants.FIELD_RDF_SUBJECT, subject)); Query qPredicate = new TermQuery(new Term(AsnConstants.FIELD_RDF_PREDICATE, predicate)); query.add(qSubject, BooleanClause.Occur.MUST); query.add(qPredicate, BooleanClause.Occur.MUST); // sort on descending timestamp String tsField = AsnConstants.FIELD_SYS_TIMESTAMP; Sort sortOption = new Sort(new SortField(tsField, SortField.STRING, true)); // determine the start and end positions int startRecord = context.getRequestOptions().getStartRecord() - 1; int maxRecords = context.getRequestOptions().getMaxRecords(); if (startRecord < 0) startRecord = 0; int recordsPerPage = maxRecords; if (recordsPerPage <= 0) recordsPerPage = 1; int hitsToReturn = startRecord + recordsPerPage; int nextRecord = 0; int numDocs = 0; IndexReader reader = null; IndexSearcher searcher = null; try { // make the reader and searcher, execute the search reader = this.getIndexAdapter().makeIndexReader(); searcher = new IndexSearcher(reader); TopDocs topDocs = searcher.search(query, null, hitsToReturn, sortOption); ScoreDoc[] scoreDocs = null; int totalHits = topDocs.totalHits; if (maxRecords > 0) { scoreDocs = topDocs.scoreDocs; if ((scoreDocs != null) && (scoreDocs.length) > 0) { numDocs = scoreDocs.length; if (totalHits > numDocs) { nextRecord = numDocs + 1; } } } // root property for the response String rootSubject = subject; String roorPredicate = operation.getPredicate().getURN() + "response"; AsnProperty rootProp = new AsnProperty(rootSubject, roorPredicate, null); // hit count and next record String queryPfx = asnSet.getURNPrefix() + ":query"; rootProp.getChildren().add(new AsnProperty(null, queryPfx + ":hits", "" + totalHits)); if (nextRecord > 0) { rootProp.getChildren().add(new AsnProperty(null, queryPfx + ":nextRecord", "" + nextRecord)); } // canCreate capability for the active user String canCreatePred = asnSet.getURNPrefix() + ":activeUser:canCreate"; String canCreateVal = "" + context.getAuthorizer().canCreate(context, asnSet.getAuthPolicy()); rootProp.getChildren().add(new AsnProperty(null, canCreatePred, canCreateVal)); // process the documents, generate the response AsnAssertionRenderer renderer = new AsnAssertionRenderer(); for (int i = startRecord; i < numDocs; i++) { Document document = reader.document(scoreDocs[i].doc); Assertion assertion = asnSet.newAssertion(context, false); assertion.load(document); rootProp.getChildren().add(renderer.makeProperty(context, assertion)); } context.getOperationResponse().generateResponse(context, rootProp.getChildren()); } finally { this.getIndexAdapter().closeReader(reader); this.getIndexAdapter().closeSearcher(searcher); } }
From source file:com.gitblit.tickets.TicketIndexer.java
License:Apache License
/** * Search for tickets matching the query. The returned tickets are * shadows of the real ticket, but suitable for a results list. * * @param text/*from w w w. ja v a 2 s .c o m*/ * @param page * @param pageSize * @param sortBy * @param desc * @return */ public List<QueryResult> queryFor(String queryText, int page, int pageSize, String sortBy, boolean desc) { if (StringUtils.isEmpty(queryText)) { return Collections.emptyList(); } Set<QueryResult> results = new LinkedHashSet<QueryResult>(); StandardAnalyzer analyzer = new StandardAnalyzer(); try { QueryParser qp = new QueryParser(Lucene.content.name(), analyzer); Query query = qp.parse(queryText); IndexSearcher searcher = getSearcher(); Query rewrittenQuery = searcher.rewrite(query); log.debug(rewrittenQuery.toString()); Sort sort; if (sortBy == null) { sort = new Sort(Lucene.created.asSortField(desc)); } else { sort = new Sort(Lucene.fromString(sortBy).asSortField(desc)); } int maxSize = 5000; TopFieldDocs docs = searcher.search(rewrittenQuery, maxSize, sort, false, false); int size = (pageSize <= 0) ? maxSize : pageSize; int offset = Math.max(0, (page - 1) * size); ScoreDoc[] hits = subset(docs.scoreDocs, offset, size); for (int i = 0; i < hits.length; i++) { int docId = hits[i].doc; Document doc = searcher.doc(docId); QueryResult result = docToQueryResult(doc); result.docId = docId; result.totalResults = docs.totalHits; results.add(result); } } catch (Exception e) { log.error(MessageFormat.format("Exception while searching for {0}", queryText), e); } return new ArrayList<QueryResult>(results); }
From source file:com.github.rnewson.couchdb.lucene.CustomQueryParser.java
License:Apache License
public static Sort toSort(final String sort) throws ParseException { if (sort == null) { return null; } else {//from w w w . j a v a 2 s . c om final String[] split = sort.split(","); final SortField[] sort_fields = new SortField[split.length]; for (int i = 0; i < split.length; i++) { String tmp = split[i]; final boolean reverse = tmp.charAt(0) == '\\'; // Strip sort order character. if (tmp.charAt(0) == '\\' || tmp.charAt(0) == '/') { tmp = tmp.substring(1); } final SortField sortField; if ("_score".equals(tmp)) { sortField = new SortField(null, SortField.Type.SCORE, reverse); } else if ("_doc".equals(tmp)) { sortField = new SortField(null, SortField.Type.DOC, reverse); } else { final TypedField typedField = new TypedField(tmp); sortField = new SortField(typedField.getName(), typedField.toSortField(), reverse); } sort_fields[i] = sortField; } return new Sort(sort_fields); } }
From source file:com.google.gerrit.lucene.LuceneAccountIndex.java
License:Apache License
@Override public DataSource<AccountState> getSource(Predicate<AccountState> p, QueryOptions opts) throws QueryParseException { return new QuerySource(opts, queryBuilder.toQuery(p), new Sort(new SortField(ID_SORT_FIELD, SortField.Type.LONG, true))); }
From source file:com.google.gerrit.lucene.LuceneGroupIndex.java
License:Apache License
@Override public DataSource<AccountGroup> getSource(Predicate<AccountGroup> p, QueryOptions opts) throws QueryParseException { return new QuerySource(opts, queryBuilder.toQuery(p), new Sort(new SortField(UUID_SORT_FIELD, SortField.Type.STRING, false))); }
From source file:com.hospitalsearch.util.Page.java
public List<T> getPageList(Integer page) { FullTextSession session = Search.getFullTextSession(this.sessionFactory.openSession()); Order order = this.sortType.startsWith("Ascen") ? Order.asc("name") : Order.desc("name"); QueryBuilder builder = session.getSearchFactory().buildQueryBuilder().forEntity(Hospital.class).get(); Query query = builder.keyword().fuzzy().onFields(projection).matching(this.query).createQuery(); FullTextQuery fullTextQuery = session.createFullTextQuery(query, Hospital.class) .setCriteriaQuery(session.createCriteria(Hospital.class).addOrder(order)); this.resultListCount = fullTextQuery.getResultSize(); if (this.pageSize < this.resultListCount) { this.pageCount = this.resultListCount / this.pageSize; this.paginated = true; } else {/* www . ja v a 2s. c o m*/ this.pageCount = 1; this.paginated = false; } fullTextQuery.setFirstResult((pageSize * (page - 1))).setMaxResults(pageSize); fullTextQuery.setSort(new Sort(new SortField("name", Type.STRING_VAL))); List<T> result = (List<T>) fullTextQuery.list(); session.close(); return result; }