Пример #1
0
  @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 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 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();
  }
  @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();
  }
  @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 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();
  }
 private int nbrOfMatchingResults(String field, String token, FullTextSession s)
     throws ParseException {
   QueryParser parser = new QueryParser(field, TestConstants.standardAnalyzer);
   org.apache.lucene.search.Query luceneQuery = parser.parse(token);
   FullTextQuery query = s.createFullTextQuery(luceneQuery);
   return query.getResultSize();
 }
  @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();
  }
 private void addPaginationToQuery(FullTextQuery fullTextQuery, Integer page) {
   if (page != null && page > 0) {
     fullTextQuery.setFirstResult((page - 1) * PAGE_LENGTH).setMaxResults(PAGE_LENGTH);
   } else {
     fullTextQuery.setFirstResult(0).setMaxResults(PAGE_LENGTH);
   }
 }
 @Override
 public StorageResults visit(Paging paging) {
   query.setFirstResult(paging.getStart());
   query.setFetchSize(AbstractQueryHandler.JDBC_FETCH_SIZE);
   query.setMaxResults(paging.getLimit());
   return null;
 }
  @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();
  }
  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();
  }
Пример #13
0
 private FullTextQuery queryHondaWithFacet(FacetingRequest request) {
   Query luceneQuery =
       queryBuilder(Car.class).keyword().onField("make").matching("Honda").createQuery();
   FullTextQuery query = fullTextSession.createFullTextQuery(luceneQuery, Car.class);
   query.getFacetManager().enableFaceting(request);
   assertEquals("Wrong number of query matches", 13, query.getResultSize());
   return query;
 }
Пример #14
0
 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();
 }
Пример #15
0
  public List<Object> listProjection(String... fields) {
    fullTextQuery.setProjection(fields);

    @SuppressWarnings("unchecked")
    List<Object> list = fullTextQuery.list();

    return list;
  }
Пример #16
0
  private void applyPartialResults(FullTextQuery fullTextQuery, Long firstResult, Long maxResults) {
    if (firstResult != null) {
      fullTextQuery.setFirstResult(firstResult.intValue());
    }

    if (maxResults != null) {
      fullTextQuery.setMaxResults(maxResults.intValue());
    }
  }
  @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;
 }
  /**
   * Creates a full-text query on Locations entities and checks the term is found exactly the
   * expected number of times (or fails the test)
   */
  private void assertFoundLocations(
      FullTextSession fullTextSession, String locationGroupName, int expectedFoundLocations) {
    final Transaction transaction = fullTextSession.beginTransaction();
    TermQuery luceneQuery = new TermQuery(new Term("locationGroup.name", locationGroupName));
    FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(luceneQuery, Location.class);
    int resultSize = fullTextQuery.getResultSize();
    transaction.commit();

    Assert.assertEquals(expectedFoundLocations, resultSize);
  }
Пример #20
0
  @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();
  }
Пример #21
0
 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();
 }
Пример #22
0
 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();
 }
Пример #23
0
  public void testSimpleFaceting() throws Exception {
    FacetingRequest request =
        queryBuilder(Car.class)
            .facet()
            .name(facetName)
            .onField(indexFieldName)
            .discrete()
            .createFacetingRequest();
    FullTextQuery query = queryHondaWithFacet(request);

    List<Facet> facetList = query.getFacetManager().getFacets(facetName);
    assertEquals("Wrong number of facets", 4, facetList.size());
  }
Пример #24
0
  public void testDefaultSortOrderIsCount() throws Exception {
    FacetingRequest request =
        queryBuilder(Car.class)
            .facet()
            .name(facetName)
            .onField(indexFieldName)
            .discrete()
            .createFacetingRequest();
    FullTextQuery query = queryHondaWithFacet(request);

    List<Facet> facetList = query.getFacetManager().getFacets(facetName);
    assertFacetCounts(facetList, new int[] {5, 4, 4, 0});
  }
Пример #25
0
  public void testUnknownFieldNameReturnsEmptyResults() {
    FacetingRequest request =
        queryBuilder(Car.class)
            .facet()
            .name("foo")
            .onField("foobar")
            .discrete()
            .createFacetingRequest();
    FullTextQuery query = queryHondaWithFacet(request);

    List<Facet> facetList = query.getFacetManager().getFacets(facetName);
    assertTrue(facetList.isEmpty());
  }
Пример #26
0
 @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();
 }
Пример #27
0
  /**
   * 全文检索
   *
   * @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;
  }
Пример #28
0
  @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());
  }
Пример #29
0
  @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 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();
  }