SortField sfield = new SortField(QueryBuilder.DATE, SortField.Type.STRING, true); Sort sort = new Sort(sfield); QueryParser qparser = new QueryParser(QueryBuilder.PATH, new CompatibleAnalyser()); Query query; ScoreDoc[] hits = null; try { query = qparser.parse(path);
int numSortFields = indexSort == null ? 0 : indexSort.getSort().length; output.writeVInt(numSortFields); for (int i = 0; i < numSortFields; ++i) { SortField sortField = indexSort.getSort()[i]; SortField.Type sortType = sortField.getType(); output.writeString(sortField.getField()); int sortTypeID; switch (sortField.getType()) { case STRING: sortTypeID = 0; throw new IllegalStateException("Unexpected sort type: " + sortField.getType()); output.writeByte((byte) (sortField.getReverse() ? 0 : 1)); Object missingValue = sortField.getMissingValue(); if (missingValue == null) { output.writeByte((byte) 0); output.writeByte((byte) 2); } else { throw new AssertionError("unrecognized missing value for STRING field \"" + sortField.getField() + "\": " + missingValue); break; default: throw new IllegalStateException("Unexpected sort type: " + sortField.getType());
public MergeSortQueue(Sort sort, TopDocs[] shardHits) { super(shardHits.length); this.shardHits = new ScoreDoc[shardHits.length][]; for(int shardIDX=0;shardIDX<shardHits.length;shardIDX++) { final ScoreDoc[] shard = shardHits[shardIDX].scoreDocs; //System.out.println(" init shardIdx=" + shardIDX + " hits=" + shard); if (shard != null) { this.shardHits[shardIDX] = shard; // Fail gracefully if API is misused: for(int hitIDX=0;hitIDX<shard.length;hitIDX++) { final ScoreDoc sd = shard[hitIDX]; if (!(sd instanceof FieldDoc)) { throw new IllegalArgumentException("shard " + shardIDX + " was not sorted by the provided Sort (expected FieldDoc but got ScoreDoc)"); } final FieldDoc fd = (FieldDoc) sd; if (fd.fields == null) { throw new IllegalArgumentException("shard " + shardIDX + " did not set sort field values (FieldDoc.fields is null); you must pass fillFields=true to IndexSearcher.search on each shard"); } } } } final SortField[] sortFields = sort.getSort(); comparators = new FieldComparator[sortFields.length]; reverseMul = new int[sortFields.length]; for(int compIDX=0;compIDX<sortFields.length;compIDX++) { final SortField sortField = sortFields[compIDX]; comparators[compIDX] = sortField.getComparator(1, compIDX); reverseMul[compIDX] = sortField.getReverse() ? -1 : 1; } }
private void validateIndexSortDVType(Sort indexSort, String fieldName, DocValuesType dvType) { for (SortField sortField : indexSort.getSort()) { if (sortField.getField().equals(fieldName)) { switch (dvType) { case NUMERIC: if (sortField.getType().equals(SortField.Type.INT) == false && sortField.getType().equals(SortField.Type.LONG) == false && sortField.getType().equals(SortField.Type.FLOAT) == false && sortField.getType().equals(SortField.Type.DOUBLE) == false) { throw new IllegalArgumentException("invalid doc value type:" + dvType + " for sortField:" + sortField); if (sortField.getType().equals(SortField.Type.STRING) == false) { throw new IllegalArgumentException("invalid doc value type:" + dvType + " for sortField:" + sortField);
if (sortField.getMissingValue() == SortField.STRING_LAST) { missingOrd = Integer.MAX_VALUE; } else { if (sortField.getMissingValue() != null) { missingValue = (Long) sortField.getMissingValue(); } else { missingValue = 0L; if (sortField.getMissingValue() != null) { missingValue = (Integer) sortField.getMissingValue(); } else { missingValue = 0; if (sortField.getMissingValue() != null) { missingValue = (Double) sortField.getMissingValue(); } else { missingValue = 0.0; if (sortField.getMissingValue() != null) { missingValue = (Float) sortField.getMissingValue(); } else { missingValue = 0.0f; throw new IllegalArgumentException("unhandled SortField.getType()=" + sortField.getType());
@SuppressWarnings("unchecked") @Test public void testResultOrderedByIdAsString() throws Exception { Transaction tx = fullTextSession.beginTransaction(); Query query = queryParser.parse( "summary:lucene" ); FullTextQuery hibQuery = fullTextSession.createFullTextQuery( query, Book.class ); Sort sort = new Sort( new SortField( "id", SortField.Type.STRING, false ) ); hibQuery.setSort( sort ); List<Book> result = hibQuery.list(); assertNotNull( result ); assertThat( result ).extracting( "id" ).containsExactly( 1, 10, 2, 3 ); tx.commit(); }
@Test public void testResultTransformToDelimString() throws Exception { FullTextSession s = Search.getFullTextSession( openSession() ); prepEmployeeIndex( s ); Transaction tx; s.clear(); tx = s.beginTransaction(); QueryParser parser = new QueryParser( "dept", TestConstants.standardAnalyzer ); Query query = parser.parse( "dept:ITech" ); org.hibernate.search.FullTextQuery hibQuery = s.createFullTextQuery( query, Employee.class ); hibQuery.setProjection( "id", "lastname", "dept", FullTextQuery.THIS, FullTextQuery.SCORE, FullTextQuery.ID ); hibQuery.setResultTransformer( new ProjectionToDelimStringResultTransformer() ); hibQuery.setSort( new Sort( new SortField( "id", SortField.Type.STRING ), SortField.FIELD_SCORE ) ); @SuppressWarnings("unchecked") List<String> result = hibQuery.list(); assertTrue( "incorrect transformation", result.get( 0 ).startsWith( "1000, Griffin, ITech" ) ); assertTrue( "incorrect transformation", result.get( 1 ).startsWith( "1002, Jimenez, ITech" ) ); //cleanup for ( Object element : s.createQuery( "from " + Employee.class.getName() ).list() ) { s.delete( element ); } tx.commit(); s.close(); }
@Test public void testFetchSizeLargerThanHits() throws Exception { FullTextSession fullTextSession = Search.getFullTextSession( openSession() ); Transaction tx = fullTextSession.beginTransaction(); QueryParser parser = new QueryParser( "dept", TestConstants.standardAnalyzer ); Query query = parser.parse( "dept:ITech" ); org.hibernate.search.FullTextQuery hibQuery = fullTextSession.createFullTextQuery( query, Employee.class ); hibQuery.setSort( new Sort( new SortField( "id", SortField.Type.STRING ) ) ); hibQuery.setProjection( "id", "lastname", "dept" ); hibQuery.setFetchSize( 6 ); ScrollableResults results = hibQuery.scroll(); results.beforeFirst(); results.next(); Object[] result = results.get(); assertEquals( "incorrect entityInfo returned", 1000, result[0] ); tx.commit(); fullTextSession.close(); }
@Test public void testTwoSortableFieldsConfiguredThroughAnnotationAndCustomFieldLevelBridge() throws Exception { FullTextSession fullTextSession = Search.getFullTextSession( openSession() ); Transaction tx = fullTextSession.beginTransaction(); @SuppressWarnings("unchecked") List<Book> result = fullTextSession.createFullTextQuery( new MatchAllDocsQuery(), Explorer.class ) .setSort( new Sort( new SortField( "exploredCountries", SortField.Type.INT ), new SortField( "nameParts_lastName", SortField.Type.STRING ) ) ) .list(); assertNotNull( result ); assertThat( result ).extracting( "id" ).containsExactly( 3, 2, 1 ); tx.commit(); fullTextSession.close(); }
private List<?> getResultsFiltered(FullTextSession session, Query query, Class<? extends BaseEntity>... classes) { return session.createFullTextQuery( query, classes ) .setSort( new Sort( new SortField( "idSort", SortField.Type.INT ) ) ) .list(); }
@Test public void testEntityCanSortOnId() { try ( Session session = openSession() ) { FullTextSession fullTextSession = Search.getFullTextSession( session ); Transaction transaction = fullTextSession.beginTransaction(); Sort sort = new Sort( new SortField( "id", SortField.Type.STRING ) ); QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity( Villain.class ).get(); Query q = queryBuilder.keyword().onField( "name" ).matching( LEX ).createQuery(); FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery( q, Villain.class ); fullTextQuery.setSort( sort ); List list = fullTextQuery.list(); assertThat( list ).hasSize( 1 ); Villain actual = (Villain) list.get( 0 ); assertThat( actual.getName() ).isEqualTo( LEX ); transaction.commit(); } }
@Test public void testFirstResultAndMaxResults() throws Exception { Session s = openSession(); FullTextSession session = Search.getFullTextSession( s ); Transaction tx = s.beginTransaction(); QueryDescriptor query = ElasticsearchQueries.fromJson( "{ 'query': { 'match' : { 'abstract' : 'Hibernate' } } }" ); List<?> result = session.createFullTextQuery( query, ScientificArticle.class ) .setFirstResult( 1 ) .setMaxResults( 2 ) .setSort( new Sort( new SortField( "id", SortField.Type.STRING, false ) ) ) .list(); assertThat( result ).extracting( "title" ).containsExactlyInAnyOrder( "Latest in ORM", "High-performance ORM" ); tx.commit(); s.close(); }
@Override protected void execute(FullTextSession fts) { Query q = fts.getSearchFactory() .buildQueryBuilder() .forEntity( Book.class ) .get() .all() .createQuery(); fts.createFullTextQuery( q, Book.class ) .setSort( new Sort( new SortField( "rating", SortField.Type.FLOAT, true ) ) ) .setMaxResults( 100 ) .list(); }
public Sort toSort(List<? extends OrderSpecifier<?>> orderBys) { List<SortField> sorts = new ArrayList<SortField>(orderBys.size()); for (OrderSpecifier<?> order : orderBys) { if (!(order.getTarget() instanceof Path<?>)) { throw new IllegalArgumentException("argument was not of type Path."); } Class<?> type = order.getTarget().getType(); boolean reverse = !order.isAscending(); Path<?> path = getPath(order.getTarget()); if (Number.class.isAssignableFrom(type)) { sorts.add(new SortField(toField(path), sortFields.get(type), reverse)); } else { sorts.add(new SortField(toField(path), SortField.Type.STRING, reverse)); } } Sort sort = new Sort(); sort.setSort(sorts.toArray(new SortField[sorts.size()])); return sort; } }
public static SortField readSortField(StreamInput in) throws IOException { String field = null; if (in.readBoolean()) { field = in.readString(); } SortField.Type sortType = readSortType(in); Object missingValue = readMissingValue(in); boolean reverse = in.readBoolean(); SortField sortField = new SortField(field, sortType, reverse); if (missingValue != null) { sortField.setMissingValue(missingValue); } return sortField; }
sortFields[i] = new SortedNumericSortField(fieldName, sortType, reverse, sortedNumericSelector); } else { sortFields[i] = new SortField(fieldName, sortType, reverse); sortFields[i].setMissingValue(missingValue); indexSort = new Sort(sortFields); } else if (numSortFields < 0) { throw new CorruptIndexException("invalid index sort field count: " + numSortFields, input);
SortField newSortField = new SortField(sortField.getField(), SortField.Type.DOUBLE); newSortField.setMissingValue(sortField.getMissingValue()); sortField = newSortField; } else if (sortField.getClass() == SortedSetSortField.class) { SortField newSortField = new SortField(sortField.getField(), SortField.Type.STRING, sortField.getReverse()); newSortField.setMissingValue(sortField.getMissingValue()); sortField = newSortField; } else if (sortField.getClass() == SortedNumericSortField.class) { SortField newSortField = new SortField(sortField.getField(), ((SortedNumericSortField) sortField).getNumericType(), sortField.getReverse()); newSortField.setMissingValue(sortField.getMissingValue()); sortField = newSortField; if (sortField.getField() == null) { out.writeBoolean(false); } else { out.writeBoolean(true); out.writeString(sortField.getField()); if (sortField.getComparatorSource() != null) { IndexFieldData.XFieldComparatorSource comparatorSource = (IndexFieldData.XFieldComparatorSource) sortField.getComparatorSource(); writeSortType(out, comparatorSource.reducedType()); writeMissingValue(out, comparatorSource.missingValue(sortField.getReverse())); } else { writeSortType(out, sortField.getType());
final String[] fields = new String[]{ "field1", "field2", "field3" }; final float[] scalars = new float[]{ 0.5f, 1.4f, 1.8f }; Sort sort = new Sort( new SortField( "", new FieldComparatorSource() { public FieldComparator newComparator(String fieldname, int numHits, int sortPos, boolean reversed) throws IOException { return new ScaledComparator(numHits, fields, scalars); } } ) );
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()); }