@Test
  public void testElementCollectionOfBasicTypeMapping() throws Exception {
    Session s = openSession();
    FullTextSession session = Search.getFullTextSession(s);
    Transaction tx = s.beginTransaction();

    QueryDescriptor query =
        ElasticsearchQueries.fromJson("{ 'query': { 'match' : { 'lastName' : 'Hergesheimer' } } }");
    List<?> result =
        session
            .createFullTextQuery(query, GolfPlayer.class)
            .setProjection(ProjectionConstants.SOURCE)
            .list();

    String source = (String) ((Object[]) result.iterator().next())[0];

    JsonHelper.assertJsonEqualsIgnoringUnknownFields(
        "{"
            + "\"lastName\": \"Hergesheimer\","
            + "\"strengths\": ["
            + "\"willingness\", \"precision\", \"stamina\""
            + "]"
            + "}",
        source);

    tx.commit();
    s.close();
  }
  @Test
  public void testQueryOnNullToken() {
    Session s = openSession();
    FullTextSession session = Search.getFullTextSession(s);
    Transaction tx = s.beginTransaction();

    QueryDescriptor query = ElasticSearchQueries.fromQueryString("firstName:&lt;NULL&gt;");
    List<?> result = session.createFullTextQuery(query, GolfPlayer.class).list();
    assertThat(result)
        .onProperty("id")
        .describedAs("Querying null-encoded String")
        .containsOnly(2L);

    query = ElasticSearchQueries.fromQueryString("dateOfBirth:1970-01-01");
    result = session.createFullTextQuery(query, GolfPlayer.class).list();
    assertThat(result).onProperty("id").describedAs("Querying null-encoded Date").containsOnly(2L);

    query = ElasticSearchQueries.fromQueryString("active:false");
    result = session.createFullTextQuery(query, GolfPlayer.class).list();
    assertThat(result)
        .onProperty("id")
        .describedAs("Querying null-encoded Boolean")
        .containsOnly(2L);

    query = ElasticSearchQueries.fromQueryString("driveWidth:\\-1");
    result = session.createFullTextQuery(query, GolfPlayer.class).list();
    assertThat(result)
        .onProperty("id")
        .describedAs("Querying null-encoded Integer")
        .containsOnly(2L);

    tx.commit();
    s.close();
  }
  @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();
  }
 private void rebuildIndexWithMassIndexer(Class<?> entityType, String tenantId) throws Exception {
   FullTextSession session = Search.getFullTextSession(openSessionWithTenantId(tenantId));
   session.createIndexer(entityType).purgeAllOnStart(true).startAndWait();
   int numDocs = session.getSearchFactory().getIndexReaderAccessor().open(entityType).numDocs();
   session.close();
   assertThat(numDocs).isGreaterThan(0);
 }
Пример #5
0
  @SuppressWarnings("unchecked")
  public List<Dap> getDaps() {

    if (dapExample != null) {
      Example example =
          Example.create(dapExample).excludeFalse().ignoreCase().enableLike(MatchMode.ANYWHERE);
      return session.createCriteria(Dap.class).add(example).list();
    } else if (searchText != null && searchText.trim().length() > 0) {
      FullTextSession fullTextSession = Search.getFullTextSession(sessionManager.getSession());
      try {
        fullTextSession.createIndexer().startAndWait();
      } catch (java.lang.InterruptedException e) {
        logger.warn("Lucene Indexing was interrupted by something " + e);
      }

      QueryBuilder qb =
          fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Dap.class).get();
      org.apache.lucene.search.Query luceneQuery =
          qb.keyword().onFields("name").matching(searchText).createQuery();

      return fullTextSession.createFullTextQuery(luceneQuery, Dap.class).list();
    } else {
      // default - unfiltered - all entitites list
      return session.createCriteria(Dap.class).list();
    }
  }
  @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 testMapping() throws Exception {
    Session s = openSession();
    FullTextSession session = Search.getFullTextSession(s);
    Transaction tx = s.beginTransaction();

    QueryDescriptor query =
        ElasticsearchQueries.fromJson("{ 'query': { 'match' : { 'lastName' : 'Hergesheimer' } } }");
    List<?> result =
        session
            .createFullTextQuery(query, GolfPlayer.class)
            .setProjection(ProjectionConstants.SOURCE)
            .list();

    String source = (String) ((Object[]) result.iterator().next())[0];

    JsonHelper.assertJsonEqualsIgnoringUnknownFields(
        "{"
            + "\"active\": true,"
            + "\"dateOfBirth\": \"1958-04-07T00:00:00Z\","
            + "\"driveWidth\": 285,"
            + "\"firstName\": \"Klaus\","
            + "\"handicap\": 3.4,"
            + "\"lastName\": \"Hergesheimer\","
            + "\"fullName\": \"Klaus Hergesheimer\","
            + "\"age\": 34,"
            + "\"puttingStrength\": \"2.5\""
            + "}",
        source);

    tx.commit();
    s.close();
  }
  private float getScore(Query query) {
    Session session = openSession();
    Object[] queryResult;
    float score;
    try {
      FullTextSession fullTextSession = Search.getFullTextSession(session);
      List<?> resultList =
          fullTextSession
              .createFullTextQuery(query, DynamicBoostedDescLibrary.class)
              .setProjection(ProjectionConstants.SCORE, ProjectionConstants.EXPLANATION)
              .setMaxResults(1)
              .list();

      if (resultList.size() == 0) {
        score = 0.0f;
      } else {
        queryResult = (Object[]) resultList.get(0);
        score = (Float) queryResult[0];
        String explanation = queryResult[1].toString();
        log.debugf("score: %f explanation: %s", score, explanation);
      }
    } finally {
      session.close();
    }
    return score;
  }
  @Test
  public void testProjectionOfNullValues() {
    Session s = openSession();
    FullTextSession session = Search.getFullTextSession(s);
    Transaction tx = s.beginTransaction();

    QueryDescriptor query = ElasticSearchQueries.fromQueryString("lastName:Kidd");
    List<?> result =
        session
            .createFullTextQuery(query, GolfPlayer.class)
            .setProjection(
                "firstName",
                "lastName",
                "active",
                "dateOfBirth",
                "handicap",
                "driveWidth",
                "ranking.value")
            .list();

    assertThat(result).hasSize(1);

    Object[] projection = (Object[]) result.iterator().next();
    assertThat(projection[0]).describedAs("firstName").isNull();
    assertThat(projection[1]).describedAs("lastName").isEqualTo("Kidd");
    assertThat(projection[2]).describedAs("active").isNull();
    assertThat(projection[3]).describedAs("dateOfBirth").isNull();
    assertThat(projection[4]).describedAs("handicap").isEqualTo(0.0D);
    assertThat(projection[5]).describedAs("driveWidth").isNull();
    assertThat(projection[6]).describedAs("ranking value").isNull();

    tx.commit();
    s.close();
  }
  @Test
  public void verifyIndexExclusivity() {
    FullTextSessionBuilder builder = new FullTextSessionBuilder();
    FullTextSession ftSession =
        builder
            .setProperty("hibernate.search.Book.indexmanager", "near-real-time")
            .setProperty(
                "hibernate.search." + Foo.class.getName() + ".indexmanager",
                "org.hibernate.search.testsupport.indexmanager.RamIndexManager")
            .addAnnotatedClass(BlogEntry.class)
            .addAnnotatedClass(Foo.class)
            .addAnnotatedClass(org.hibernate.search.test.query.Book.class)
            .addAnnotatedClass(org.hibernate.search.test.query.Author.class)
            .openFullTextSession();
    SearchFactoryImplementor searchFactory =
        (SearchFactoryImplementor) ftSession.getSearchFactory();
    ftSession.close();
    IndexManagerHolder allIndexesManager = searchFactory.getIndexManagerHolder();

    // checks for the default implementation
    checkIndexManagerType(
        allIndexesManager,
        "org.hibernate.search.test.configuration.BlogEntry",
        org.hibernate.search.indexes.impl.DirectoryBasedIndexManager.class);

    // Uses "NRT" taken from shortcut names
    checkIndexManagerType(
        allIndexesManager, "Book", org.hibernate.search.indexes.impl.NRTIndexManager.class);

    // Uses a fully qualified name to load an implementation
    checkIndexManagerType(allIndexesManager, Foo.class.getName(), RamIndexManager.class);

    builder.close();
  }
 @Override
 public void setUp() throws Exception {
   super.setUp();
   FullTextSession fullTextSession = Search.getFullTextSession(openSession());
   searchFactory = (SearchFactoryImplementor) fullTextSession.getSearchFactory();
   fullTextSession.close();
 }
Пример #12
0
  @Test
  public void testUseOfMultipleCustomFieldBridgeInstances() throws Exception {
    Transaction transaction = fullTextSession.beginTransaction();
    final QueryBuilder monthQb =
        fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Month.class).get();

    // Rather complex code here as we're not exposing the #withFieldBridge methods on the public
    // interface
    final ConnectedTermMatchingContext field1Context =
        (ConnectedTermMatchingContext) monthQb.keyword().onField(MonthClassBridge.FIELD_NAME_1);

    final ConnectedTermMatchingContext field2Context =
        (ConnectedTermMatchingContext)
            field1Context
                .withFieldBridge(new String2FieldBridgeAdaptor(new RomanNumberFieldBridge()))
                .andField(MonthClassBridge.FIELD_NAME_2);

    Query query =
        field2Context
            .withFieldBridge(new String2FieldBridgeAdaptor(new RomanNumberFieldBridge()))
            .matching(2)
            .createQuery();

    assertEquals(1, fullTextSession.createFullTextQuery(query, Month.class).getResultSize());
    transaction.commit();
  }
  @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();
  }
Пример #14
0
  @Override
  public final void run() {
    try {
      ctx.startSignal.await();
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }

    counter.incrementAndGet();

    long startTime = 0;
    if (MEASURE_TASK_TIME) {
      startTime = System.nanoTime();
    }

    FullTextSession s = Search.getFullTextSession(ctx.sf.openSession());
    Transaction tx = s.beginTransaction();
    try {
      execute(s);
      tx.commit();
    } catch (RuntimeException e) {
      tx.rollback();
      throw e;
    } finally {
      s.close();
    }

    if (MEASURE_TASK_TIME) {
      long stopTime = System.nanoTime();
      timer.addAndGet(stopTime - startTime);
    }
  }
Пример #15
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(groups = "ch04")
  public void testEmbedded() throws Exception {
    Session session = factory.openSession();
    Item item = new Item();
    item.setDescription("Great DVD");
    item.setEan("123456789012");
    item.setTitle("Great DVD");
    item.setRating(new Rating());
    item.getRating().setOverall(5);
    item.getRating().setPicture(4);
    item.getRating().setScenario(5);
    item.getRating().setSoundtrack(3);
    Transaction tx = session.beginTransaction();
    session.save(item);
    tx.commit();

    session.clear();

    tx = session.beginTransaction();
    FullTextSession fts = Search.getFullTextSession(session);
    List results =
        fts.createFullTextQuery(new TermQuery(new Term("rating.overall", "5")), Item.class).list();
    assert results.size() == 1;
    fts.delete(results.get(0));
    tx.commit();
    fts.close();
  }
Пример #17
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();
 }
 public int countBusLineByDatabaseCount() {
   FullTextSession fullTextSession = Search.getFullTextSession(sessions.openSession());
   Transaction tx = fullTextSession.beginTransaction();
   int count = fullTextSession.createCriteria(BusLine.class).list().size();
   tx.commit();
   fullTextSession.close();
   return count;
 }
 private void purgeAll(Class<?> entityType, String tenantId) {
   FullTextSession session = Search.getFullTextSession(openSessionWithTenantId(tenantId));
   session.purgeAll(entityType);
   session.flushToIndexes();
   int numDocs = session.getSearchFactory().getIndexReaderAccessor().open(entityType).numDocs();
   session.close();
   assertThat(numDocs).isEqualTo(0);
 }
  /** Changes the parent LocationGroup's name to "Airport" */
  private void updateLocationGroupName(FullTextSession fullTextSession) {
    final Transaction transaction = fullTextSession.beginTransaction();

    LocationGroup group = (LocationGroup) fullTextSession.get(LocationGroup.class, 1L);
    LocationGroup locationGroup = (LocationGroup) fullTextSession.merge(group);
    locationGroup.setName("Airport");

    transaction.commit();
  }
 private void buildIndex(FullTextSession session, Transaction tx) {
   for (int x = 0; x < titles.length; x++) {
     Dvd dvd = new Dvd();
     dvd.setTitle(titles[x]);
     dvd.setId(x);
     session.save(dvd);
   }
   tx.commit();
   session.clear();
 }
 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);
  }
  @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();
  }
Пример #25
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();
  }
Пример #26
0
  @Test
  public void testUseOfFieldBridge() throws Exception {
    Transaction transaction = fullTextSession.beginTransaction();
    final QueryBuilder monthQb =
        fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Month.class).get();

    Query query = monthQb.keyword().onField("monthValue").matching(2).createQuery();
    assertEquals(1, fullTextSession.createFullTextQuery(query, Month.class).getResultSize());

    transaction.commit();
  }
  /** Adds a single Location to the LocationGroup#1 */
  private void addLocationToGroupCollection(FullTextSession fullTextSession) {
    final Transaction transaction = fullTextSession.beginTransaction();
    LocationGroup group = (LocationGroup) fullTextSession.get(LocationGroup.class, 1L);

    Location location = new Location("New Room");
    fullTextSession.persist(location);

    group.getLocations().add(location);
    location.setLocationGroup(group);

    transaction.commit();
  }
Пример #28
0
 @Override
 @After
 public void tearDown() throws Exception {
   // check for ongoing transaction which is an indicator that something went wrong
   // don't call the cleanup methods in this case. Otherwise the original error get swallowed
   if (fullTextSession.getTransaction().getStatus() != TransactionStatus.ACTIVE) {
     deleteTestBooks();
     deleteTestNumbers();
     fullTextSession.close();
   }
   super.tearDown();
 }
Пример #29
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();
 }
Пример #30
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();
 }