/** * Returns all {@link News} of the given news group except the {@link News} with the given id. * @param newsGroupId the news group id * @param exceptId the news which should not be returned * @return a {@link List} with all {@link News} of the requested news group except the {@link News} with the exceptId. */ private List<News> getNewsOfNewsGroup(final long newsGroupId, final long exceptId) { final BooleanQuery query = new BooleanQuery(); QueryUtil.addTypeConf(query, NewsIndexType.getInstance()); final NumericRangeQuery<Long> groupQuery = NumericRangeQuery.newLongRange( NewsIndexType.FIELD_NEWSGROUPID, newsGroupId, newsGroupId, true, true); query.add(groupQuery, Occur.MUST); // exclude news query.add(new TermQuery(new Term(IIndexElement.FIELD_ID, String.valueOf(exceptId))), Occur.MUST_NOT); final SearchOptions options = new SearchOptions(); options.setSort(new Sort(ESortField.PUBLISH_DATE.getSortField(ESortOrder.DESC))); final DocumentsSearchResult result = IndexSearch.getInstance().search(query, options); return NewsIndexType.docsToNews(result.getResults()); }
/** * Returns the amount of {@link News} which are assigned to news groups (news group id > 0) * for the given {@link Query}. */ private int getAmountOfNewsInNewsGroups(final Query filterQuery) { final BooleanQuery query = new BooleanQuery(); query.add(filterQuery, Occur.MUST); // get only news that are in real groups (newsGroupId > 0) final NumericRangeQuery<Long> newsGroupFilterQuery = NumericRangeQuery.newLongRange( NewsIndexType.FIELD_NEWSGROUPID, 0l, null, false, true); query.add(newsGroupFilterQuery, Occur.MUST); final SearchOptions options = new SearchOptions(); options.setMaxResults(0); // we only want the totalHits, not the results. final TopDocs topDocs = IndexSearch.getInstance().getTopDocs(query, options); return topDocs.totalHits; }
@Override public Collection<IndexedItem> search(IndexSearcher searcher) throws IOException { BooleanQuery overall = new BooleanQuery(); BooleanQuery collections = new BooleanQuery(); for( Institution inst : institutions ) { collections.add( new TermQuery(new Term(FreeTextQuery.FIELD_INSTITUTION, Long.toString(inst.getUniqueId()))), Occur.SHOULD); } overall.add(collections, Occur.MUST); overall.add(NumericRangeQuery.newLongRange(FreeTextQuery.FIELD_ID_RANGEABLE, firstId, lastId, true, true), Occur.MUST); searcher.search(overall, compareDates); return compareDates.getModifiedDocs(); }
@Override public void delDoucmentFromIndex(List<Integer> appIds) throws IOException { synchronized (lock) { logger.info("Before deleting history .Search's indexWriter has numDos: {}", indexWriter.numDocs()); if (CollectionUtils.isEmpty(appIds)) { return; } logger.info("prepare delete ids:{}", appIds); NumericRangeQuery<Integer> idQuery = null; for (Integer id : appIds) { idQuery = NumericRangeQuery.newIntRange(LuceneFieldCollection.ColumnName.ID.getName(), id, id, true, true); indexWriter.deleteDocuments(idQuery); } indexWriter.commit(); } }
@Override public ScoreDoc[] prefixSearch(String keywords) throws IOException { if (StringUtils.isEmpty(keywords) || keywords.length() > appConfig.getKeywordMaxLength()) { logger.error("empty keywords or over-length! {}", keywords); return null; } Sort sort = new Sort(new SortField("downloadRank", SortField.INT, true)); Term nameFldTerm = new Term(fieldName, keywords); PrefixQuery nameFldQuery = new PrefixQuery(nameFldTerm); NumericRangeQuery<Integer> catalogQuery = NumericRangeQuery.newIntRange("catalog", (int) EnumCatalog.SOFT.getCatalog(), (int) EnumCatalog.GAME.getCatalog(), true, true); BooleanQuery booleanQuery = new BooleanQuery(); booleanQuery.add(catalogQuery, Occur.MUST); booleanQuery.add(nameFldQuery, Occur.MUST); TopDocs topDocs = quickTipsSearcher.search(booleanQuery, appConfig.getQuickTipsNum() * 2, sort); ScoreDoc[] docs = topDocs.scoreDocs; return docs; }
@Override public ScoreDoc[] prefixSearch(String q) throws IOException { if (StringUtils.isEmpty(q) || q.length() > appConfig.getKeywordMaxLength()) { logger.error("empty keywords or over-length! {}", q); return null; } final TopDocs[] rstTopDocs = new TopDocs[2]; final Query nameFldQuery = new PrefixQuery(new Term(NAME.getName(), q)); rstTopDocs[0] = indexSearcher.search(nameFldQuery, appConfig.getQuickTipsNum() * 2, sort); final Query downLoadRankQuery = NumericRangeQuery.newIntRange(DOWNOLOAD_RANK.getName(), MIN_DOWNLOAD_RANK, Integer.MAX_VALUE, true, false); // 从下载量最高的1000条记录中,再过滤符合关键字的记录 rstTopDocs[1] = indexSearcher.search(downLoadRankQuery, MAX_TOP, sort); TopDocs rst = TopDocsUtil.mergeDuplicateDocId(TopDocs.merge(sort, MAX_TOP + appConfig.getQuickTipsNum() * 2, rstTopDocs)); if (rst != null) { return rst.scoreDocs; } return null; }
@Override public ScoreDoc[] prefixSearch(String q) throws IOException { if (StringUtils.isEmpty(q) || q.length() > appConfig.getKeywordMaxLength()) { logger.error("empty keywords or over-length! {}", q); return null; } final TopDocs[] rstTopDocs = new TopDocs[2]; final Query nameFldQuery = new PrefixQuery(new Term(NAME.getName(), q)); rstTopDocs[0] = indexSearcher.search(nameFldQuery, appConfig.getQuickTipsNum() * 2, sort); final Query downLoadRankQuery = NumericRangeQuery.newIntRange(DOWNOLOAD_RANK.getName(), MIN_DOWNLOAD_RANK, Integer.MAX_VALUE, true, false); //从下载量最高的1000条记录中,再过滤符合关键字的记录 rstTopDocs[1] = indexSearcher.search(downLoadRankQuery, MAX_TOP, sort); TopDocs rst = TopDocsUtil.mergeDuplicateDocId(TopDocs.merge(sort, MAX_TOP + appConfig.getQuickTipsNum() * 2, rstTopDocs)); if(rst != null) { return rst.scoreDocs; } return null; }
@Override public void addQueryTerms(BooleanQuery query, AdvancedSearchParams params) { try { ZipscriptQueryParams queryParams = params.getExtensionData(ZipscriptQueryParams.ZIPSCRIPTQUERYPARAMS); if (queryParams.getMinPresent() != null || queryParams.getMaxPresent() != null) { Query presentQuery = NumericRangeQuery.newIntRange("present", queryParams.getMinPresent(), queryParams.getMaxPresent(), true, true); query.add(presentQuery, Occur.MUST); } if (queryParams.getMinMissing() != null || queryParams.getMaxMissing() != null) { Query missingQuery = NumericRangeQuery.newIntRange("missing", queryParams.getMinMissing(), queryParams.getMaxMissing(), true, true); query.add(missingQuery, Occur.MUST); } if (queryParams.getMinPercent() != null || queryParams.getMaxPercent() != null) { Query percentQuery = NumericRangeQuery.newIntRange("percent", queryParams.getMinPercent(), queryParams.getMaxPercent(), true, true); query.add(percentQuery, Occur.MUST); } } catch (KeyNotFoundException e) { // No MP3 terms to include, return without amending query } }
/** * Sort the results of a numeric range query if the query in this context * is a {@link NumericRangeQuery}, see {@link #numericRange(String, Number, Number)}, * Otherwise an {@link IllegalStateException} will be thrown. * * @param key the key to sort on. * @param reversed if the sort order should be reversed or not. {@code true} * for lowest first (ascending), {@code false} for highest first (descending) * @return a QueryContext with sorting by numeric value. */ public QueryContext sortNumeric( String key, boolean reversed ) { if ( !( queryOrQueryObject instanceof NumericRangeQuery ) ) { throw new IllegalStateException( "Not a numeric range query" ); } Number number = ((NumericRangeQuery)queryOrQueryObject).getMin(); number = number != null ? number : ((NumericRangeQuery)queryOrQueryObject).getMax(); SortField.Type fieldType = SortField.Type.INT; if ( number instanceof Long ) { fieldType = SortField.Type.LONG; } else if ( number instanceof Float ) { fieldType = SortField.Type.FLOAT; } else if ( number instanceof Double ) { fieldType = SortField.Type.DOUBLE; } sort( new Sort( new SortedNumericSortField( key, fieldType, reversed ) ) ); return this; }
/** * Will create a {@link Query} with a query for numeric ranges, that is * values that have been indexed using {@link ValueContext#indexNumeric()}. * It will match the type of numbers supplied to the type of values that * are indexed in the index, f.ex. long, int, float and double. * If both {@code from} and {@code to} is {@code null} then it will default * to int. * * @param key the property key to query. * @param from the low end of the range (inclusive) * @param to the high end of the range (inclusive) * @param includeFrom whether or not {@code from} (the lower bound) is inclusive * or not. * @param includeTo whether or not {@code to} (the higher bound) is inclusive * or not. * @return a {@link Query} to do numeric range queries with. */ public static Query rangeQuery( String key, Number from, Number to, boolean includeFrom, boolean includeTo ) { if ( from instanceof Long || to instanceof Long ) { return NumericRangeQuery.newLongRange( key, from != null ? from.longValue() : 0, to != null ? to.longValue() : Long.MAX_VALUE, includeFrom, includeTo ); } else if ( from instanceof Double || to instanceof Double ) { return NumericRangeQuery.newDoubleRange( key, from != null ? from.doubleValue() : 0, to != null ? to.doubleValue() : Double.MAX_VALUE, includeFrom, includeTo ); } else if ( from instanceof Float || to instanceof Float ) { return NumericRangeQuery.newFloatRange( key, from != null ? from.floatValue() : 0, to != null ? to.floatValue() : Float.MAX_VALUE, includeFrom, includeTo ); } else { return NumericRangeQuery.newIntRange( key, from != null ? from.intValue() : 0, to != null ? to.intValue() : Integer.MAX_VALUE, includeFrom, includeTo ); } }
private void testNumericValues( Index<Node> index ) { Node node10 = graphDb.createNode(); Node node6 = graphDb.createNode(); Node node31 = graphDb.createNode(); String key = "key"; index.add( node10, key, numeric( 10 ) ); index.add( node6, key, numeric( 6 ) ); index.add( node31, key, numeric( 31 ) ); for ( int i = 0; i < 2; i++ ) { assertThat( index.query( NumericRangeQuery.newIntRange( key, 4, 40, true, true ) ), contains( node10, node6, node31 ) ); assertThat( index.query( NumericRangeQuery.newIntRange( key, 6, 15, true, true ) ), contains( node10, node6 ) ); assertThat( index.query( NumericRangeQuery.newIntRange( key, 6, 15, false, true ) ), contains( node10 ) ); restartTx(); } index.remove( node6, key, numeric( 6 ) ); assertThat( index.query( NumericRangeQuery.newIntRange( key, 4, 40, true, true ) ), contains( node10, node31 ) ); restartTx(); assertThat( index.query( NumericRangeQuery.newIntRange( key, 4, 40, true, true ) ), contains( node10, node31 ) ); }
/** * Set up the filters for collections - this is for searching within collections. * * @param collection - to search within * @return - created filter * @throws ParseException */ private List<Filter> getCollectionFilters(InstitutionalCollection collection) throws ParseException { List<Filter> filters = new LinkedList<Filter>(); //isolate the collection root Term t = new Term("collection_root_id", NumericUtils.longToPrefixCoded(collection.getTreeRoot().getId())); Query subQuery = new TermQuery( t ); filters.add(new QueryWrapperFilter(subQuery)); //isolate the range of children subQuery = NumericRangeQuery.newLongRange("collection_left_value", collection.getLeftValue(), collection.getRightValue(), true, true); filters.add(new QueryWrapperFilter(subQuery)); return filters; }
public List<Products> extractPromotionalProducts() { FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager( em ); org.apache.lucene.search.Query query = NumericRangeQuery.newDoubleRange( "old_price" , 0.0d , 1000d , false , true ); FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery( query , Products.class ); Sort sort = new Sort( new SortField( "price" , SortField.DOUBLE ) ); fullTextQuery.setSort( sort ); //fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); List results = fullTextQuery.getResultList(); return results; }
private MultiFieldQueryParser getQueryParser() { MultiFieldQueryParser queryParser = new MultiFieldQueryParser(getAllDefaultSearchableFields(), analyzer) { @Override protected Query getRangeQuery(String field, String part1, String part2, boolean startInclusive, boolean endInclusive) throws ParseException { if (field != null && getIndex(field).numeric) { Long min = getWithDefault(part1, null); Long max = getWithDefault(part2, null); return NumericRangeQuery.newLongRange(field, min, max, true, true); } else if (field != null) { return new TermQuery(new Term(field)); } return super.getRangeQuery(null, part1, part2, startInclusive, endInclusive); } }; queryParser.setDefaultOperator(QueryParser.Operator.AND); queryParser.setLocale(LOCALE); queryParser.setAnalyzeRangeTerms(true); queryParser.setLowercaseExpandedTerms(true); return queryParser; }
/** * Constructs a query for documents that are equal to the * input time period. * @return the query */ private Query makeEquals() { /** * one determinate and boundaries are equal */ int nStep = this.precisionStep; String fSMeta = this.summaryMetaFieldName; String fLower = this.getLowerFieldName(0); String fUpper = this.getUpperFieldName(0); String sMeta = "is1determinate"; Query qIs1Determinate = new TermQuery(new Term(fSMeta,sMeta)); Query qDocLowerEq = NumericRangeQuery.newLongRange( fLower,nStep,queryLower,queryLower,true,true); Query qDocUpperEq = NumericRangeQuery.newLongRange( fUpper,nStep,queryUpper,queryUpper,true,true); BooleanQuery bq = new BooleanQuery(); bq.add(qIs1Determinate,BooleanClause.Occur.MUST); bq.add(qDocLowerEq,BooleanClause.Occur.MUST); bq.add(qDocUpperEq,BooleanClause.Occur.MUST); return bq; }
/** * Creates a directory filter; also filters a range of pages * @param constrainField The field that contains the directory info * @param constrainValues The directories to which the filters shold limit * @return The created filter */ private Filter getFilter(String constrainField, List<String> constrainValues, int type, int startPage, int endPage){ BooleanQuery cqry = new BooleanQuery(); if(constrainValues.size() == 1){ cqry.add(new TermQuery(new Term(constrainField, constrainValues.get(0))), BooleanClause.Occur.MUST); } else { for(String s : constrainValues) { cqry.add(new TermQuery(new Term(constrainField, s)), BooleanClause.Occur.SHOULD); } } if(type == FileSearcher.QUERY_BOOLEAN && startPage != -1 && endPage != -1) { cqry.add(NumericRangeQuery.newIntRange("page", startPage, endPage, true, true), BooleanClause.Occur.MUST); } return new QueryWrapperFilter(cqry); }
/** {@inheritDoc} */ @Override protected Query makeQuery(Token lower, Token upper, boolean includeLower, boolean includeUpper) { Long start = lower == null ? null : (Long) lower.getTokenValue(); Long stop = upper == null ? null : (Long) upper.getTokenValue(); if (lower != null && lower.isMinimum()) { start = null; } if (upper != null && upper.isMinimum()) { stop = null; } if (start == null && stop == null) { return null; } return NumericRangeQuery.newLongRange(FIELD_NAME, start, stop, includeLower, includeUpper); }
@Test public void testInteger() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperInteger(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); MatchCondition matchCondition = new MatchCondition(0.5f, "name", 42); Query query = matchCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals(42, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(42, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
@Test public void testLong() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperLong(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); MatchCondition matchCondition = new MatchCondition(0.5f, "name", 42L); Query query = matchCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals(42L, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(42L, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
@Test public void testFloat() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperFloat(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); MatchCondition matchCondition = new MatchCondition(0.5f, "name", 42.42F); Query query = matchCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals(42.42F, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(42.42F, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
@Test public void testDouble() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperDouble(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); MatchCondition matchCondition = new MatchCondition(0.5f, "name", 42.42D); Query query = matchCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals(42.42D, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(42.42D, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
@Test public void testIntegerClose() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperInteger(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); RangeCondition rangeCondition = new RangeCondition(0.5f, "name", 42, 43, false, false); Query query = rangeCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals("name", ((NumericRangeQuery<?>) query).getField()); Assert.assertEquals(42, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(43, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
@Test public void testIntegerOpen() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperInteger(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); RangeCondition rangeCondition = new RangeCondition(0.5f, "name", 42, null, true, false); Query query = rangeCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals("name", ((NumericRangeQuery<?>) query).getField()); Assert.assertEquals(42, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(null, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
@Test public void testLongClose() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperLong(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); RangeCondition rangeCondition = new RangeCondition(0.5f, "name", 42L, 43, false, false); Query query = rangeCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals("name", ((NumericRangeQuery<?>) query).getField()); Assert.assertEquals(42L, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(43L, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
@Test public void testLongOpen() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperLong(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); RangeCondition rangeCondition = new RangeCondition(0.5f, "name", 42f, null, true, false); Query query = rangeCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals("name", ((NumericRangeQuery<?>) query).getField()); Assert.assertEquals(42L, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(null, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
@Test public void testFloatClose() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperFloat(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); RangeCondition rangeCondition = new RangeCondition(0.5f, "name", 42.42D, 43.42F, false, false); Query query = rangeCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals("name", ((NumericRangeQuery<?>) query).getField()); Assert.assertEquals(42.42F, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(43.42f, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
@Test public void testFloatOpen() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperFloat(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); RangeCondition rangeCondition = new RangeCondition(0.5f, "name", 42.42f, null, true, false); Query query = rangeCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals("name", ((NumericRangeQuery<?>) query).getField()); Assert.assertEquals(42.42f, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(null, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
@Test public void testDoubleClose() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperDouble(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); RangeCondition rangeCondition = new RangeCondition(0.5f, "name", 42.42D, 43.42D, false, false); Query query = rangeCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals("name", ((NumericRangeQuery<?>) query).getField()); Assert.assertEquals(42.42D, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(43.42D, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
@Test public void testDoubleOpen() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperDouble(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); RangeCondition rangeCondition = new RangeCondition(0.5f, "name", 42.42D, null, true, false); Query query = rangeCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals("name", ((NumericRangeQuery<?>) query).getField()); Assert.assertEquals(42.42D, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(null, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
private <T extends Enum<T> & HasIndex> Query toRangeQuery(String field, Set<T> set) { Set<Integer> indexes = Sets.newHashSet(); for (T element : set) { indexes.add(element.getIndex()); } BooleanQuery query = new BooleanQuery(); int begin = -1; for (int i = 0; i < 31; ++i) { if (indexes.contains(i)) { if (begin == -1) { begin = i; } } else { if (begin == -1) { continue; } Query q = NumericRangeQuery.newIntRange(field, begin, i, true, false); query.add(q, Occur.SHOULD); begin = -1; } } return query; }
/** * Sort the results of a numeric range query if the query in this context * is a {@link NumericRangeQuery}, see {@link #numericRange(String, Number, Number)}, * Otherwise an {@link IllegalStateException} will be thrown. * * @param key the key to sort on. * @param reversed if the sort order should be reversed or not. {@code true} * for lowest first (ascending), {@code false} for highest first (descending) * @return a QueryContext with sorting by numeric value. */ public QueryContext sortNumeric( String key, boolean reversed ) { if ( !( queryOrQueryObject instanceof NumericRangeQuery ) ) { throw new IllegalStateException( "Not a numeric range query" ); } Number number = ((NumericRangeQuery)queryOrQueryObject).getMin(); number = number != null ? number : ((NumericRangeQuery)queryOrQueryObject).getMax(); int fieldType = SortField.INT; if ( number instanceof Long ) { fieldType = SortField.LONG; } else if ( number instanceof Float ) { fieldType = SortField.FLOAT; } else if ( number instanceof Double ) { fieldType = SortField.DOUBLE; } sort( new Sort( new SortField( key, fieldType, reversed ) ) ); return this; }
@Test public void testRangeParsing() throws Exception { NumericConfig numericConfig = new NumericConfig(8, NumberFormat.getNumberInstance(Locale.ENGLISH), FieldType.NumericType.FLOAT); HashMap<String, NumericConfig> numericConfigMap = new HashMap<String, NumericConfig>(); numericConfigMap.put("reflec_7", numericConfig); numericConfigMap.put("reflec_8", numericConfig); numericConfigMap.put("reflec_9", numericConfig); StandardQueryParser parser = new StandardQueryParser(); parser.setNumericConfigMap(numericConfigMap); Query query1 = parser.parse("reflec_8:[0.0 TO 1.0]", "x"); assertEquals(NumericRangeQuery.class, query1.getClass()); Query query2 = parser.parse("reflec_8:[0.0 TO 1.0] AND reflec_9:[0.2 TO 0.6]^3.1", "x"); assertEquals(BooleanQuery.class, query2.getClass()); BooleanClause clause1 = ((BooleanQuery) query2).getClauses()[0]; BooleanClause clause2 = ((BooleanQuery) query2).getClauses()[1]; NumericRangeQuery<Float> nrq1 = NumericRangeQuery.newFloatRange("reflec_8", 8, 0.0F, 1.0F, true, true); NumericRangeQuery<Float> nrq2 = NumericRangeQuery.newFloatRange("reflec_9", 8, 0.2F, 0.6F, true, true); nrq2.setBoost(3.1F); assertEquals(nrq1, clause1.getQuery()); assertEquals(BooleanClause.Occur.MUST, clause1.getOccur()); assertEquals(nrq2, clause2.getQuery()); assertEquals(BooleanClause.Occur.MUST, clause2.getOccur()); }
public void testAnd() throws Exception { TermQuery searchingBooks = new TermQuery(new Term("subject","search")); //#1 Query books2010 = //#2 NumericRangeQuery.newIntRange("pubmonth", 201001, //#2 201012, //#2 true, true); //#2 BooleanQuery searchingBooks2010 = new BooleanQuery(); //#3 searchingBooks2010.add(searchingBooks, BooleanClause.Occur.MUST); //#3 searchingBooks2010.add(books2010, BooleanClause.Occur.MUST); //#3 Directory dir = TestUtil.getBookIndexDirectory(); IndexSearcher searcher = new IndexSearcher(dir); TopDocs matches = searcher.search(searchingBooks2010, 10); assertTrue(TestUtil.hitsIncludeTitle(searcher, matches, "Lucene in Action, Second Edition")); searcher.close(); dir.close(); }
public void testInclusive() throws Exception { Directory dir = TestUtil.getBookIndexDirectory(); IndexSearcher searcher = new IndexSearcher(dir); // pub date of TTC was September 2006 NumericRangeQuery query = NumericRangeQuery.newIntRange("pubmonth", 200605, 200609, true, true); TopDocs matches = searcher.search(query, 10); /* for(int i=0;i<matches.totalHits;i++) { LOGGER.info("match " + i + ": " + searcher.doc(matches.scoreDocs[i].doc).get("author")); } */ assertEquals(1, matches.totalHits); searcher.close(); dir.close(); }
public Query getRangeQuery(String field, String part1, String part2, boolean inclusive) throws ParseException { TermRangeQuery query = (TermRangeQuery) super.getRangeQuery(field, part1, part2, inclusive); if ("price".equals(field)) { return NumericRangeQuery.newDoubleRange( "price", Double.parseDouble( query.getLowerTerm()), Double.parseDouble( query.getUpperTerm()), query.includesLower(), query.includesUpper()); } else { return query; } }
public Query getRangeQuery(String field, String part1, String part2, boolean inclusive) throws ParseException { TermRangeQuery query = (TermRangeQuery) super.getRangeQuery(field, part1, part2, inclusive); if ("pubmonth".equals(field)) { return NumericRangeQuery.newIntRange( "pubmonth", Integer.parseInt(query.getLowerTerm()), Integer.parseInt(query.getUpperTerm()), query.includesLower(), query.includesUpper()); } else { return query; } }