@SuppressWarnings("unchecked") @GET @Produces(MediaType.APPLICATION_JSON) public Response volumes( @QueryParam("categoryId") Long categoryId, @QueryParam("page") Integer page, @QueryParam("q") String q) { Volumes volumes = new Volumes(); VolumeDAO volumeDAO = DAOFactory.getInstance().getVolumeDAO(); FullTextSession fts = org.hibernate.search.Search.getFullTextSession(volumeDAO.getSession()); try { Query query = buildLuceneQuery(categoryId, page, q); FullTextQuery createFullTextQuery = fts.createFullTextQuery(query, com.book.identification.model.Volume.class); addPaginationToQuery(createFullTextQuery, page); List<Volume> list = createFullTextQuery.list(); for (Volume volume : list) { volume.setPage(page); volume.setQ(q); } volumes.setVolumes(createFullTextQuery.list()); } catch (ParseException e1) { e1.printStackTrace(); } if (volumes.getVolumes().isEmpty()) { return Response.ok("volumes : {}").build(); } return Response.ok(volumes).build(); }
@Test public void testSortableField() throws Exception { FullTextSession s = Search.getFullTextSession(openSession()); Transaction tx = s.beginTransaction(); Item item1 = new Item(); item1.setId(3); item1.setPrice((short) 3454); s.persist(item1); Item item2 = new Item(); item2.setId(2); item2.setPrice((short) 3354); s.persist(item2); Item item3 = new Item(); item3.setId(1); item3.setPrice((short) 3554); s.persist(item3); tx.commit(); s.clear(); tx = s.beginTransaction(); Query q = s.getSearchFactory().buildQueryBuilder().forEntity(Item.class).get().all().createQuery(); FullTextQuery query = s.createFullTextQuery(q, Item.class); query.setSort(new Sort(new SortField("price", SortField.Type.INT))); List<?> results = query.list(); assertThat(results) .onProperty("price") .describedAs("Sortable field via programmatic config") .containsExactly((short) 3354, (short) 3454, (short) 3554); query.setSort(new Sort(new SortField("id", SortField.Type.STRING))); results = query.list(); assertThat(results) .onProperty("id") .describedAs("Sortable field via programmatic config") .containsExactly(1, 2, 3); s.delete(results.get(0)); s.delete(results.get(1)); s.delete(results.get(2)); tx.commit(); s.close(); }
@Test public void testRangeQueryBelow() throws Exception { Transaction transaction = fullTextSession.beginTransaction(); final QueryBuilder monthQb = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Month.class).get(); calendar.setTimeZone(TimeZone.getTimeZone("UTC")); calendar.set(10 + 1800, 2, 12, 0, 0, 0); Date to = calendar.getTime(); Query query = monthQb .range() .onField("estimatedCreation") .andField("justfortest") .ignoreFieldBridge() .ignoreAnalyzer() .below(to) .createQuery(); FullTextQuery hibQuery = fullTextSession.createFullTextQuery(query, Month.class); assertEquals(1, hibQuery.getResultSize()); assertEquals("March", ((Month) hibQuery.list().get(0)).getName()); query = monthQb .range() .onField("estimatedCreation") .ignoreFieldBridge() .andField("justfortest") .ignoreFieldBridge() .ignoreAnalyzer() .below(DateTools.round(to, DateTools.Resolution.MINUTE)) .createQuery(); hibQuery = fullTextSession.createFullTextQuery(query, Month.class); assertEquals(1, hibQuery.getResultSize()); assertEquals("March", ((Month) hibQuery.list().get(0)).getName()); query = monthQb.range().onField("raindropInMm").below(0.24d).createQuery(); assertTrue(query.getClass().isAssignableFrom(NumericRangeQuery.class)); List<?> results = fullTextSession.createFullTextQuery(query, Month.class).list(); assertEquals("test range numeric ", 1, results.size()); assertEquals("test range numeric ", "January", ((Month) results.get(0)).getName()); transaction.commit(); }
@Test public void testAnalyzerDef() throws Exception { Address address = new Address(); address.setStreet1("3340 Peachtree Rd NE"); address.setStreet2("JBoss"); FullTextSession s = Search.getFullTextSession(openSession()); Transaction tx = s.beginTransaction(); s.persist(address); tx.commit(); s.clear(); tx = s.beginTransaction(); QueryParser parser = new QueryParser("id", TestConstants.standardAnalyzer); org.apache.lucene.search.Query luceneQuery = parser.parse("street1_ngram:pea"); final FullTextQuery query = s.createFullTextQuery(luceneQuery); assertEquals("Analyzer inoperant", 1, query.getResultSize()); s.delete(query.list().get(0)); tx.commit(); s.close(); }
@Test public void testBridgeMapping() throws Exception { Address address = new Address(); address.setStreet1("Peachtree Rd NE"); address.setStreet2("JBoss"); FullTextSession s = Search.getFullTextSession(openSession()); Transaction tx = s.beginTransaction(); s.persist(address); tx.commit(); s.clear(); tx = s.beginTransaction(); QueryParser parser = new QueryParser("id", TestConstants.standardAnalyzer); org.apache.lucene.search.Query luceneQuery = parser.parse("street1:peac"); FullTextQuery query = s.createFullTextQuery(luceneQuery); assertEquals("PrefixQuery should not be on", 0, query.getResultSize()); luceneQuery = parser.parse("street1_abridged:peac"); query = s.createFullTextQuery(luceneQuery); assertEquals("Bridge not used", 1, query.getResultSize()); s.delete(query.list().get(0)); tx.commit(); s.close(); }
@Test public void testMapping() throws Exception { Address address = new Address(); address.setStreet1("3340 Peachtree Rd NE"); address.setStreet2("JBoss"); FullTextSession s = Search.getFullTextSession(openSession()); Transaction tx = s.beginTransaction(); s.persist(address); tx.commit(); s.clear(); tx = s.beginTransaction(); QueryParser parser = new QueryParser("id", TestConstants.standardAnalyzer); org.apache.lucene.search.Query luceneQuery = parser.parse("" + address.getAddressId()); FullTextQuery query = s.createFullTextQuery(luceneQuery); assertEquals("documentId does not work properly", 1, query.getResultSize()); luceneQuery = parser.parse("street1:peachtree"); query = s.createFullTextQuery(luceneQuery).setProjection("idx_street2", FullTextQuery.THIS); assertEquals("Not properly indexed", 1, query.getResultSize()); Object[] firstResult = (Object[]) query.list().get(0); assertEquals("@Field.store not respected", "JBoss", firstResult[0]); // Verify that AddressClassBridge was applied as well: luceneQuery = parser.parse("AddressClassBridge:Applied\\!"); assertEquals(1, s.createFullTextQuery(luceneQuery).getResultSize()); s.delete(firstResult[1]); tx.commit(); s.close(); }
@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(); }
@Test @SkipForDialect( value = {SybaseASE15Dialect.class, Sybase11Dialect.class}, comment = "Sybase does not support @Lob") public void testCreateIndexSearchEntityWithLobField() { // create and index Session session = openSession(); Transaction tx = session.beginTransaction(); LobHolder lobHolder = new LobHolder(); lobHolder.setVeryLongText("this text is very long ..."); session.persist(lobHolder); tx.commit(); session.close(); // search session = openSession(); tx = session.beginTransaction(); FullTextSession fullTextSession = Search.getFullTextSession(session); QueryBuilder qb = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(LobHolder.class).get(); Query query = qb.keyword().onField("veryLongText").matching("text").createQuery(); FullTextQuery hibernateQuery = fullTextSession.createFullTextQuery(query); List<LobHolder> result = hibernateQuery.list(); assertEquals("We should have a match for the single LobHolder", 1, result.size()); tx.commit(); session.close(); }
@Test public void testClassBridgeInstanceMapping() throws Exception { OrderLine orderLine = new OrderLine(); orderLine.setName("Sequoia"); FullTextSession s = Search.getFullTextSession(openSession()); Transaction tx = s.beginTransaction(); s.persist(orderLine); tx.commit(); s.clear(); tx = s.beginTransaction(); QueryParser parser = new QueryParser("id", TestConstants.standardAnalyzer); org.apache.lucene.search.Query luceneQuery = parser.parse("orderLineName:Sequoia"); FullTextQuery query = s.createFullTextQuery(luceneQuery); assertEquals("Bridge not used", 1, query.getResultSize()); luceneQuery = parser.parse("orderLineName_ngram:quo"); query = s.createFullTextQuery(luceneQuery); assertEquals("Analyzer configuration not applied", 1, query.getResultSize()); luceneQuery = parser.parse("orderLineNameViaParam:Sequoia"); query = s.createFullTextQuery(luceneQuery); assertEquals("Parameter configuration not applied", 1, query.getResultSize()); s.delete(query.list().get(0)); tx.commit(); s.close(); }
public void testQueryOnAllEntities() throws Exception { FullTextSession s = Search.getFullTextSession(openSession()); Transaction tx = s.beginTransaction(); Person person = new Person(); person.setName("Jon Doe"); s.save(person); tx.commit(); tx = s.beginTransaction(); QueryParser parser = new QueryParser( TestConstants.getTargetLuceneVersion(), "name", TestConstants.standardAnalyzer); Query query = parser.parse("name:foo"); FullTextQuery hibQuery = s.createFullTextQuery(query); try { hibQuery.list(); fail(); } catch (SearchException e) { assertTrue("Wrong message", e.getMessage().startsWith("There are no mapped entities")); } tx.rollback(); s.close(); }
@Test(groups = "ch07") public void testPrefixQuery() throws Exception { FullTextSession session = Search.getFullTextSession(openSession()); Transaction tx = session.beginTransaction(); buildIndex(session, tx); String userInput = "sea"; tx = session.beginTransaction(); PrefixQuery query = new PrefixQuery(new Term("title", userInput)); System.out.println(query.toString()); org.hibernate.search.FullTextQuery hibQuery = session.createFullTextQuery(query, Dvd.class); List<Dvd> results = hibQuery.list(); assert results.size() == 4 : "incorrect hit count"; for (Dvd dvd : results) { assert dvd.getTitle().indexOf("Sea") >= 0; System.out.println(dvd.getTitle()); } for (Object element : session.createQuery("from " + Dvd.class.getName()).list()) session.delete(element); tx.commit(); session.close(); }
@Override public List<T> list() { @SuppressWarnings("unchecked") List<T> list = fullTextQuery.list(); return list; }
/** * 全文检索 * * @param page 分页对象 * @param query 关键字查询对象 * @param queryFilter 查询过滤对象 * @param sort 排序对象 * @return 分页对象 */ @SuppressWarnings("unchecked") public Page<T> search(Page<T> page, BooleanQuery query, BooleanQuery queryFilter, Sort sort) { // 按关键字查询 FullTextQuery fullTextQuery = getFullTextSession().createFullTextQuery(query, entityClass); // 过滤无效的内容 if (queryFilter != null) { fullTextQuery.setFilter(new CachingWrapperFilter(new QueryWrapperFilter(queryFilter))); } // 设置排序 if (sort != null) { fullTextQuery.setSort(sort); } // 定义分页 page.setCount(fullTextQuery.getResultSize()); fullTextQuery.setFirstResult(page.getFirstResult()); fullTextQuery.setMaxResults(page.getMaxResults()); // 先从持久化上下文中查找对象,如果没有再从二级缓存中查找 fullTextQuery.initializeObjectsWith( ObjectLookupMethod.SECOND_LEVEL_CACHE, DatabaseRetrievalMethod.QUERY); // 返回结果 page.setList(fullTextQuery.list()); return page; }
public List<Object> listProjection(String... fields) { fullTextQuery.setProjection(fields); @SuppressWarnings("unchecked") List<Object> list = fullTextQuery.list(); return list; }
private void assertExecutionTimeoutHasNoPartialResult() { FullTextQuery hibernateQuery = fts.createFullTextQuery(allSeikoClocksQuery, Clock.class); hibernateQuery.limitExecutionTimeTo(30, TimeUnit.SECONDS); List results = hibernateQuery.list(); assertEquals("Test below limit termination", 500, results.size()); assertFalse(hibernateQuery.hasPartialResults()); fts.clear(); }
@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 int countBusLinesByFullText() { FullTextSession fullTextSession = Search.getFullTextSession(sessions.openSession()); Transaction tx = fullTextSession.beginTransaction(); org.apache.lucene.search.Query ftQuery = new MatchAllDocsQuery(); FullTextQuery query = fullTextSession.createFullTextQuery(ftQuery, BusLine.class); int count = query.list().size(); tx.commit(); fullTextSession.close(); return count; }
@SuppressWarnings("unchecked") @Override public List<Page> fetch(Query query, Criteria crit) { assertCriteriaEntity(crit); FullTextSession fullTextSession = getFullTextSession(); FullTextQuery fq = fullTextSession.createFullTextQuery(query, Page.class); fq.setCriteriaQuery(crit != null ? crit : pageDao.criteria()); return fq.list(); }
@Test public void testFieldBridge() { Transaction transaction = fullTextSession.beginTransaction(); final QueryBuilder monthQb = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Month.class).get(); Query query = monthQb.keyword().onField("monthRomanNumber").matching(2).createQuery(); FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(query, Month.class); List<?> results = fullTextQuery.list(); assertEquals(1, results.size()); Month february = (Month) results.get(0); assertEquals(2, february.getMonthValue()); transaction.commit(); }
@Test public void testRangeQueryAbove() throws Exception { Transaction transaction = fullTextSession.beginTransaction(); final QueryBuilder monthQb = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Month.class).get(); calendar.setTimeZone(TimeZone.getTimeZone("UTC")); calendar.set(10 + 1900, 2, 12, 0, 0, 0); Date to = calendar.getTime(); Query query = monthQb .range() .onField("estimatedCreation") .andField("justfortest") .ignoreFieldBridge() .ignoreAnalyzer() .above(to) .createQuery(); FullTextQuery hibQuery = fullTextSession.createFullTextQuery(query, Month.class); assertEquals(1, hibQuery.getResultSize()); assertEquals("February", ((Month) hibQuery.list().get(0)).getName()); query = monthQb .range() .onField("estimatedCreation") .ignoreFieldBridge() .andField("justfortest") .ignoreFieldBridge() .ignoreAnalyzer() .above(DateTools.round(to, DateTools.Resolution.MINUTE)) .createQuery(); hibQuery = fullTextSession.createFullTextQuery(query, Month.class); assertEquals(1, hibQuery.getResultSize()); assertEquals("February", ((Month) hibQuery.list().get(0)).getName()); transaction.commit(); }
@SuppressWarnings("unchecked") @Test public void testResultOrderedByIdAlteringSortStyle() throws Exception { Transaction tx = fullTextSession.beginTransaction(); Query query = queryParser.parse("summary:lucene"); FullTextQuery hibQuery = fullTextSession.createFullTextQuery(query, Book.class); hibQuery.setSort(new Sort(new SortField("id", SortField.Type.LONG, false))); List<Book> result = hibQuery.list(); assertThat(result).onProperty("id").containsExactly(1, 2, 3, 10); hibQuery.setSort(new Sort(new SortField("id", SortField.Type.STRING, false))); result = hibQuery.list(); assertThat(result).onProperty("id").containsExactly(1, 10, 2, 3); hibQuery.setSort(new Sort(new SortField("id", SortField.Type.LONG, false))); result = hibQuery.list(); assertThat(result).onProperty("id").containsExactly(1, 2, 3, 10); tx.commit(); }
private void assertExecutionTimeoutOccursOnList() { FullTextQuery hibernateQuery = fts.createFullTextQuery(allSwatchClocksQuery, Clock.class); hibernateQuery.limitExecutionTimeTo(1, TimeUnit.NANOSECONDS); List result = hibernateQuery.list(); System.out.println("Result size early: " + result.size()); assertEquals( "Test early failure, before the number of results are even fetched", 0, result.size()); if (result.size() == 0) { // sometimes, this assertTrue(hibernateQuery.hasPartialResults()); } fts.clear(); }
private void assertTimeoutOccursOnList() { FullTextQuery hibernateQuery = fts.createFullTextQuery(allSeikoClocksQuery, Clock.class); hibernateQuery.setTimeout(10, TimeUnit.MICROSECONDS); try { hibernateQuery.list(); fail("timeout exception should happen"); } catch (QueryTimeoutException e) { // good } catch (Exception e) { fail("Expected a QueryTimeoutException"); } fts.clear(); }
public void testFilteredClasses() throws Exception { createDoeFamily(); FullTextSession fts = Search.getFullTextSession(openSession()); Transaction tx = fts.beginTransaction(); Query q = new TermQuery(new Term("name", "doe")); assertEquals(2, fts.createFullTextQuery(q).getResultSize()); assertEquals(2, fts.createFullTextQuery(q, Detective.class, Suspect.class).getResultSize()); FullTextQuery detectiveQuery = fts.createFullTextQuery(q, Detective.class); assertEquals(1, detectiveQuery.getResultSize()); assertTrue(detectiveQuery.list().get(0) instanceof Detective); FullTextQuery suspectQuery = fts.createFullTextQuery(q, Suspect.class); assertEquals(1, suspectQuery.getResultSize()); assertTrue(suspectQuery.list().get(0) instanceof Suspect); assertEquals(2, fts.createFullTextQuery(q).getResultSize()); assertEquals(2, fts.createFullTextQuery(q, Detective.class, Suspect.class).getResultSize()); tx.commit(); fts.close(); }
@Override public ListPart<T> listPart(Long firstResult, Long maxResults) { applyPartialResults(fullTextQuery, firstResult, maxResults); @SuppressWarnings("unchecked") List<T> list = fullTextQuery.list(); return ListPart.newListPart( list, firstResult, maxResults, Long.valueOf(fullTextQuery.getResultSize()), !fullTextQuery.hasPartialResults()); }
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()); }
@SkipForDialect( value = PostgreSQLDialect.class, jiraKey = "JBPAPP-2945", comment = "PostgreSQL driver does not implement query timeout") public void testEnoughTime() { Transaction tx = fts.beginTransaction(); FullTextQuery hibernateQuery = fts.createFullTextQuery(matchAllQuery, Clock.class); hibernateQuery.setTimeout(5, TimeUnit.MINUTES); List results = hibernateQuery.list(); assertFalse(hibernateQuery.hasPartialResults()); assertEquals(1000, results.size()); tx.commit(); }
@SuppressWarnings("unchecked") @Test public void testResultOrderedByDocId() 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(null, SortField.Type.DOC, false)); hibQuery.setSort(sort); List<Book> result = hibQuery.list(); assertNotNull(result); assertThat(result).onProperty("id").containsOnly(1, 2, 3, 10); tx.commit(); }
/** {@inheritDoc} */ public List<T> search(String searchTerm) throws SearchException { Session sess = getSession(); FullTextSession txtSession = Search.getFullTextSession(sess); org.apache.lucene.search.Query qry; try { qry = HibernateSearchTools.generateQuery( searchTerm, this.persistentClass, sess, defaultAnalyzer); } catch (ParseException ex) { throw new SearchException(ex); } org.hibernate.search.FullTextQuery hibQuery = txtSession.createFullTextQuery(qry, this.persistentClass); return hibQuery.list(); }
@Test public void testFullTextFilterDefAtMappingLevel() throws Exception { FullTextSession s = Search.getFullTextSession(openSession()); Transaction tx = s.beginTransaction(); Address address = new Address(); address.setStreet1("Peachtree Rd NE"); address.setStreet2("Peachtnot Rd NE"); address.setOwner("test"); Calendar c = GregorianCalendar.getInstance( TimeZone.getTimeZone("GMT"), Locale.ROOT); // for the sake of tests c.set(2009, Calendar.NOVEMBER, 15); address.setLastUpdated(c); s.persist(address); address = new Address(); address.setStreet1("Peachtnot Rd NE"); address.setStreet2("Peachtree Rd NE"); address.setLastUpdated(c); address.setOwner("testowner"); s.persist(address); tx.commit(); s.clear(); tx = s.beginTransaction(); QueryParser parser = new QueryParser("id", TestConstants.standardAnalyzer); org.apache.lucene.search.Query luceneQuery = parser.parse("street1:Peachtnot"); FullTextQuery query = s.createFullTextQuery(luceneQuery).setProjection(FullTextQuery.THIS, FullTextQuery.SCORE); query.enableFullTextFilter("security").setParameter("ownerName", "testowner"); assertEquals("expecting 1 results", 1, query.getResultSize()); @SuppressWarnings("unchecked") List<Object[]> results = query.list(); for (Object[] result : results) { s.delete(result[0]); } tx.commit(); s.close(); }