@Test public void testProjectedValueGetsConvertedToNull() throws Exception { ProgrammaticConfiguredValue nullValue = new ProgrammaticConfiguredValue(null); FullTextSession fullTextSession = Search.getFullTextSession(openSession()); Transaction tx = fullTextSession.beginTransaction(); getSession().save(nullValue); tx.commit(); fullTextSession.clear(); tx = fullTextSession.beginTransaction(); Query query = new MatchAllDocsQuery(); FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(query, ProgrammaticConfiguredValue.class); fullTextQuery.setProjection("id", "value"); fullTextQuery.setResultTransformer(new ProjectionToMapResultTransformer()); List<?> mappedResults = fullTextQuery.list(); assertTrue("Wrong result size", mappedResults.size() == 1); Map<?, ?> map = (Map<?, ?>) mappedResults.get(0); Integer id = (Integer) map.get("id"); assertNotNull(id); String value = (String) map.get("value"); assertEquals("The null token should be converted back to null", null, value); tx.commit(); fullTextSession.close(); }
public List<Object> listProjection(String... fields) { fullTextQuery.setProjection(fields); @SuppressWarnings("unchecked") List<Object> list = fullTextQuery.list(); return list; }
@Test(groups = "ch12") public void vectorTest() throws Exception { FullTextSession session = Search.getFullTextSession(openSession()); Transaction tx = session.beginTransaction(); buildIndex(session, tx); try { tx = session.beginTransaction(); Query query = new TermQuery(new Term("content", "properties")); System.out.println(query.toString()); FullTextQuery hibQuery = session.createFullTextQuery(query, ElectricalProperties.class); hibQuery.setProjection( FullTextQuery.DOCUMENT, FullTextQuery.DOCUMENT_ID, FullTextQuery.SCORE); reader = getReader(session); List<Object[]> results = hibQuery.list(); assert results.size() > 0 : "no results returned"; for (int x = 0; x < results.size(); x++) { Integer docId = (Integer) results.get(x)[1]; TermPositionVector vector = (TermPositionVector) reader.getTermFreqVector(docId, "content"); String[] terms = vector.getTerms(); int[] f = vector.getTermFrequencies(); System.out.println(results.get(x)[2]); for (int y = 0; y < vector.size(); y++) { System.out.print("docID# =>" + docId); System.out.print(" term => " + terms[y]); System.out.print(" freq => " + f[y]); int[] positions = vector.getTermPositions(y); TermVectorOffsetInfo[] offsets = vector.getOffsets(y); for (int z = 0; z < positions.length; z++) { System.out.print(" position => " + positions[z]); System.out.print(" starting offset => " + offsets[z].getStartOffset()); System.out.println(" ending offset => " + offsets[z].getEndOffset()); } System.out.println("---------------"); } } for (Object element : session.createQuery("from " + ElectricalProperties.class.getName()).list()) session.delete(element); tx.commit(); } finally { session.close(); if (provider != null) { provider.closeReader(reader); } } }
public ListPart<Object> listPartProjection(Long firstResult, Long maxResults, String... fields) { applyPartialResults(fullTextQuery, firstResult, maxResults); fullTextQuery.setProjection(fields); @SuppressWarnings("unchecked") List<Object> list = fullTextQuery.list(); return ListPart.newListPart( list, firstResult, maxResults, Long.valueOf(fullTextQuery.getResultSize()), !fullTextQuery.hasPartialResults()); }
public static void FacetTest() { Session session = null; FullTextSession fullTextSession = null; SessionFactory sessionFactory = null; try { sessionFactory = new Configuration().configure(hibernateConfigurationFile).buildSessionFactory(); session = sessionFactory.openSession(); session.beginTransaction(); fullTextSession = Search.getFullTextSession(session); org.apache.lucene.search.Query luceneQuery; FullTextQuery hibQuery; Point center = Point.fromDegrees(46, 4); double radius = 50.0d; luceneQuery = SpatialQueryBuilderFromPoint.buildSpatialQueryByGrid(center, radius, "location"); hibQuery = fullTextSession.createFullTextQuery(luceneQuery, POI.class); hibQuery.setProjection("id", "name", "type"); FacetManager facetManager = hibQuery.getFacetManager(); QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(POI.class).get(); FacetingRequest facetingRequest = queryBuilder .facet() .name("typeFacet") .onField("type") .discrete() .orderedBy(FacetSortOrder.COUNT_DESC) .includeZeroCounts(false) .createFacetingRequest(); facetManager.enableFaceting(facetingRequest); Integer size = hibQuery.getResultSize(); List list = hibQuery.list(); List<Facet> facets = facetManager.getFacets("typeFacet"); System.out.println(facets); session.getTransaction().commit(); session.close(); sessionFactory.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (fullTextSession != null && fullTextSession.isOpen()) { Transaction transaction = fullTextSession.getTransaction(); if (transaction != null && transaction.isActive()) { transaction.rollback(); } fullTextSession.close(); } if (sessionFactory != null && !sessionFactory.isClosed()) { sessionFactory.close(); } } }
public static void Bench() { Session session = null; FullTextSession fullTextSession = null; SessionFactory sessionFactory = null; try { sessionFactory = new Configuration().configure(hibernateConfigurationFile).buildSessionFactory(); session = sessionFactory.openSession(); session.beginTransaction(); fullTextSession = Search.getFullTextSession(session); long gridTotalDuration = 0; long spatialTotalDuration = 0; long doubleRangeTotalDuration = 0; long distanceDoubleRangeTotalDuration = 0; long gridDocsFetched = 0; long spatialDocsFetched = 0; long doubleRangeDocsFetched = 0; long distanceDoubleRangeDocsFetched = 0; org.apache.lucene.search.Query luceneQuery; long startTime, endTime, duration; FullTextQuery hibQuery; List gridResults, rangeResults; final QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(POI.class).get(); org.apache.lucene.search.Query query; final Integer iterations = 2000; final Integer warmUp = 50; Random random = new Random(42); for (int i = 0; i < iterations; i++) { Point center = Point.fromDegrees(random.nextDouble() * 2 + 44, random.nextDouble() * 2 + 3); double radius = 25.0d; Rectangle boundingBox = Rectangle.fromBoundingCircle(center, radius); query = queryBuilder .bool() .must( queryBuilder .range() .onField("latitude") .from(boundingBox.getLowerLeft().getLatitude()) .to(boundingBox.getUpperRight().getLatitude()) .createQuery()) .must( queryBuilder .range() .onField("longitude") .from(boundingBox.getLowerLeft().getLongitude()) .to(boundingBox.getUpperRight().getLongitude()) .createQuery()) .createQuery(); hibQuery = fullTextSession.createFullTextQuery(query, POI.class); hibQuery.setProjection("id", "name"); startTime = System.nanoTime(); try { doubleRangeDocsFetched += hibQuery.getResultSize(); } finally { endTime = System.nanoTime(); } duration = endTime - startTime; if (i > warmUp) { doubleRangeTotalDuration += duration; } session.clear(); query = queryBuilder .bool() .must( queryBuilder .range() .onField("latitude") .from(boundingBox.getLowerLeft().getLatitude()) .to(boundingBox.getUpperRight().getLatitude()) .createQuery()) .must( queryBuilder .range() .onField("longitude") .from(boundingBox.getLowerLeft().getLongitude()) .to(boundingBox.getUpperRight().getLongitude()) .createQuery()) .createQuery(); org.apache.lucene.search.Query filteredQuery = new ConstantScoreQuery( SpatialQueryBuilderFromPoint.buildDistanceFilter( new QueryWrapperFilter(query), center, radius, "location")); hibQuery = fullTextSession.createFullTextQuery(filteredQuery, POI.class); hibQuery.setProjection("id", "name"); startTime = System.nanoTime(); try { distanceDoubleRangeDocsFetched += hibQuery.getResultSize(); } finally { endTime = System.nanoTime(); } duration = endTime - startTime; if (i > warmUp) { distanceDoubleRangeTotalDuration += duration; } rangeResults = hibQuery.list(); session.clear(); luceneQuery = SpatialQueryBuilderFromPoint.buildGridQuery(center, radius, "location"); hibQuery = fullTextSession.createFullTextQuery(luceneQuery, POI.class); hibQuery.setProjection("id", "name"); startTime = System.nanoTime(); try { gridDocsFetched += hibQuery.getResultSize(); } finally { endTime = System.nanoTime(); } duration = endTime - startTime; if (i > warmUp) { gridTotalDuration += duration; } session.clear(); luceneQuery = SpatialQueryBuilderFromPoint.buildSpatialQueryByGrid(center, radius, "location"); hibQuery = fullTextSession.createFullTextQuery(luceneQuery, POI.class); hibQuery.setProjection("id", "name"); startTime = System.nanoTime(); try { spatialDocsFetched += hibQuery.getResultSize(); } finally { endTime = System.nanoTime(); } duration = endTime - startTime; if (i > warmUp) { spatialTotalDuration += duration; } gridResults = hibQuery.list(); session.clear(); if (rangeResults.size() != gridResults.size()) { luceneQuery = SpatialQueryBuilderFromPoint.buildDistanceQuery(center, radius, "location"); hibQuery = fullTextSession.createFullTextQuery(luceneQuery, POI.class); hibQuery.setProjection("id", "name"); System.out.println( ">>>>> Different numbers of documents fetched for point (" + Double.toString(center.getLatitude()) + "," + Double.toString(center.getLongitude()) + ") and radius " + Double.toString(radius)); System.out.println("Range results : " + rangeResults); System.out.println("Grid results : " + gridResults); System.out.println("Pure distance results : " + hibQuery.getResultSize()); List<Integer> rangeIds = new ArrayList<Integer>(); for (int index = 0; index < rangeResults.size(); index++) { rangeIds.add((Integer) ((Object[]) rangeResults.get(index))[0]); } List<Integer> gridIds = new ArrayList<Integer>(); for (int index = 0; index < gridResults.size(); index++) { gridIds.add((Integer) ((Object[]) gridResults.get(index))[0]); } rangeIds.removeAll(gridIds); System.out.println("Missing Ids : " + rangeIds); } } session.getTransaction().commit(); session.close(); sessionFactory.close(); System.out.println( "Mean time with Grid : " + Double.toString( (double) gridTotalDuration * Math.pow(10, -6) / (iterations - warmUp)) + " ms. Average number of docs fetched : " + Double.toString(gridDocsFetched / ((iterations - warmUp) * 1.0d))); System.out.println( "Mean time with Grid + Distance filter : " + Double.toString( (double) spatialTotalDuration * Math.pow(10, -6) / (iterations - warmUp)) + " ms. Average number of docs fetched : " + Double.toString(spatialDocsFetched / ((iterations - warmUp) * 1.0d))); System.out.println( "Mean time with DoubleRange : " + Double.toString( (double) doubleRangeTotalDuration * Math.pow(10, -6) / (iterations - warmUp)) + " ms. Average number of docs fetched : " + Double.toString(doubleRangeDocsFetched / ((iterations - warmUp) * 1.0d))); System.out.println( "Mean time with DoubleRange + Distance filter : " + Double.toString( (double) distanceDoubleRangeTotalDuration * Math.pow(10, -6) / (iterations - warmUp)) + " ms. Average number of docs fetched : " + Double.toString(distanceDoubleRangeDocsFetched / ((iterations - warmUp) * 1.0d))); } catch (Exception e) { e.printStackTrace(); } finally { if (fullTextSession != null && fullTextSession.isOpen()) { Transaction transaction = fullTextSession.getTransaction(); if (transaction != null && transaction.isActive()) { transaction.rollback(); } fullTextSession.close(); } if (sessionFactory != null && !sessionFactory.isClosed()) { sessionFactory.close(); } } }
/** * Allows settings offset and limit on the query. The default implementation calls setProjection * with SCORE and ID, which MUST BE the first two projection values. Any overriding method may add * further projections but must start with these two. * * @param ftQuery */ protected void initializeQuery(FullTextQuery ftQuery) { ftQuery.setProjection(ProjectionConstants.SCORE, ProjectionConstants.ID); }
/** * This is the same test as above with a projection query to show the presence of the ClassBridge * impl built fields just in case you don't believe us. * * @throws Exception */ public void testClassBridgesWithProjection() throws Exception { org.hibernate.Session s = openSession(); Transaction tx = s.beginTransaction(); s.persist(getDepts1()); s.persist(getDepts2()); s.persist(getDepts3()); s.persist(getDepts4()); s.flush(); tx.commit(); tx = s.beginTransaction(); FullTextSession session = Search.getFullTextSession(s); // The equipment field is the manufacturer field in the // Departments entity after being massaged by passing it // through the EquipmentType class. This field is in // the Lucene document but not in the Department entity itself. QueryParser parser = new QueryParser( TestConstants.getTargetLuceneVersion(), "equipment", TestConstants.simpleAnalyzer); // Check the second ClassBridge annotation Query query = parser.parse("equiptype:Cisco"); org.hibernate.search.FullTextQuery hibQuery = session.createFullTextQuery(query, Departments.class); hibQuery.setProjection(FullTextQuery.THIS, FullTextQuery.DOCUMENT); ScrollableResults projections = hibQuery.scroll(); assertNotNull(projections); projections.beforeFirst(); projections.next(); Object[] projection = projections.get(); assertTrue("DOCUMENT incorrect", projection[0] instanceof Departments); assertEquals("id incorrect", 1, ((Departments) projection[0]).getId()); assertTrue("DOCUMENT incorrect", projection[1] instanceof Document); assertEquals("DOCUMENT size incorrect", 8, ((Document) projection[1]).getFields().size()); assertNotNull("equiptype is null", ((Document) projection[1]).getField("equiptype")); assertEquals( "equiptype incorrect", "Cisco", ((Document) projection[1]).getField("equiptype").stringValue()); assertNotNull("branchnetwork is null", ((Document) projection[1]).getField("branchnetwork")); assertEquals( "branchnetwork incorrect", "Salt Lake City 1A", ((Document) projection[1]).getField("branchnetwork").stringValue()); projections.next(); projection = projections.get(); assertTrue("DOCUMENT incorrect", projection[0] instanceof Departments); assertEquals("id incorrect", 4, ((Departments) projection[0]).getId()); assertTrue("DOCUMENT incorrect", projection[1] instanceof Document); assertEquals("DOCUMENT size incorrect", 8, ((Document) projection[1]).getFields().size()); assertNotNull("equiptype is null", ((Document) projection[1]).getField("equiptype")); assertEquals( "equiptype incorrect", "Cisco", ((Document) projection[1]).getField("equiptype").stringValue()); assertNotNull("branchnetwork is null", ((Document) projection[1]).getField("branchnetwork")); assertEquals( "branchnetwork incorrect", "St. George 1D", ((Document) projection[1]).getField("branchnetwork").stringValue()); assertTrue("incorrect result count returned", projections.isLast()); // cleanup for (Object element : s.createQuery("from " + Departments.class.getName()).list()) { s.delete(element); } tx.commit(); s.close(); }