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;
 }
示例#2
0
  public void testBatchSize() throws Exception {
    FullTextSession s = Search.getFullTextSession(openSession());
    Transaction tx = s.beginTransaction();
    final int loop = 14;
    s.doWork(
        new Work() {
          @Override
          public void execute(Connection connection) throws SQLException {
            for (int i = 0; i < loop; i++) {
              Statement statmt = connection.createStatement();
              statmt.executeUpdate(
                  "insert into Domain(id, name) values( + " + (i + 1) + ", 'sponge" + i + "')");
              statmt.executeUpdate(
                  "insert into Email(id, title, body, header, domain_id) values( + "
                      + (i + 1)
                      + ", 'Bob Sponge', 'Meet the guys who create the software', 'nope', "
                      + (i + 1)
                      + ")");
              statmt.close();
            }
          }
        });
    tx.commit();
    s.close();

    // check non created object does get found!!1
    s = Search.getFullTextSession(openSession());
    tx = s.beginTransaction();
    ScrollableResults results = s.createCriteria(Email.class).scroll(ScrollMode.FORWARD_ONLY);
    int index = 0;
    while (results.next()) {
      index++;
      s.index(results.get(0));
      if (index % 5 == 0) {
        s.clear();
      }
    }
    tx
        .commit(); // if you get a LazyInitializationException, that's because we clear() the
                   // session in the loop.. it only works with a batch size of 5 (the point of the
                   // test)
    s.clear();
    tx = s.beginTransaction();
    QueryParser parser =
        new QueryParser(TestConstants.getTargetLuceneVersion(), "id", TestConstants.stopAnalyzer);
    List result = s.createFullTextQuery(parser.parse("body:create")).list();
    assertEquals(14, result.size());
    for (Object object : result) {
      s.delete(object);
    }
    tx.commit();
    s.close();
  }
  @SuppressWarnings("unchecked")
  @Override
  public List<Item> findItems(String searchString) {
    List<Item> resultList = new ArrayList<Item>();
    EntityManagerFactory factory = emf;
    EntityManager em = factory.createEntityManager();
    FullTextEntityManager fullTextEntityManager =
        org.hibernate.search.jpa.Search.getFullTextEntityManager(em);
    Session session = (Session) fullTextEntityManager.getDelegate();
    FullTextSession fullTextSession = Search.getFullTextSession(session);

    //		MassIndexer massIndexer = fullTextSession.createIndexer();
    //		try {
    //			fullTextSession.createIndexer().start();
    /*		} catch (InterruptedException e) {
    	e.printStackTrace();
    }*/
    Transaction transaction = fullTextSession.beginTransaction();
    fullTextSession.setFlushMode(FlushMode.MANUAL);
    fullTextSession.setCacheMode(CacheMode.IGNORE);
    ScrollableResults results =
        fullTextSession.createCriteria(Item.class).setFetchSize(20).scroll(ScrollMode.FORWARD_ONLY);
    int index = 0;
    while (results.next()) {
      index++;
      fullTextSession.index(results.get(0)); // index each element
      if (index % 20 == 0) {
        fullTextSession.flushToIndexes(); // apply changes to indexes
        fullTextSession.clear(); // free memory since the queue is processed
      }
    }
    transaction.commit();

    em.getTransaction().begin();

    QueryBuilder qb =
        fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Item.class).get();
    Query query =
        qb.keyword()
            .fuzzy()
            .onFields("alias", "tagName")
            .ignoreFieldBridge()
            .matching(searchString)
            .createQuery();
    FullTextQuery ftq = fullTextEntityManager.createFullTextQuery(query, Item.class);
    resultList = ftq.getResultList();
    em.getTransaction().commit();
    em.close();

    return resultList;
  }
示例#4
0
  private Criteria criteria(FullTextSession session) {
    final Class<?> cls = values.onlyTypes.get(0);
    Criteria criteria = session.createCriteria(cls);
    AnnotationCriteria ann = new AnnotationCriteria(criteria, values.fetchAnnotations);

    ids(criteria);
    ownerOrGroup(cls, criteria);
    createdOrModified(cls, criteria);
    annotatedBy(ann);
    annotatedBetween(ann);

    // annotatedWith
    if (values.onlyAnnotatedWith != null) {
      if (values.onlyAnnotatedWith.size() > 1) {
        throw new ApiUsageException(
            "HHH-879: "
                + "At the moment Hibernate cannot fulfill this request.\n"
                + "Please use only a single onlyAnnotatedWith "
                + "parameter when performing full text searches.");
      } else if (values.onlyAnnotatedWith.size() > 0) {
        if (!IAnnotated.class.isAssignableFrom(cls)) {
          // A non-IAnnotated object cannot have any
          // Annotations, and so our results are null
          return null; // EARLY EXIT !
        } else {
          for (Class<?> annCls : values.onlyAnnotatedWith) {
            SimpleExpression ofType = new TypeEqualityExpression("class", annCls);
            ann.getChild().add(ofType);
          }
        }
      } else {
        criteria.add(Restrictions.isEmpty("annotationLinks"));
      }
    }

    // orderBy
    if (values.orderBy.size() > 0) {
      for (int i = 0; i < values.orderBy.size(); i++) {
        String orderBy = values.orderBy.get(i);
        String orderWithoutMode = orderByPath(orderBy);
        boolean ascending = orderByAscending(orderBy);
        if (ascending) {
          criteria.addOrder(Order.asc(orderWithoutMode));
        } else {
          criteria.addOrder(Order.desc(orderWithoutMode));
        }
      }
    }
    return criteria;
  }
示例#5
0
  /**
   * Prepare to reindex lucene search index. This ensures that progress counts are properly
   * initialised before the asynchronous startReindex() method is called.
   */
  public void prepareReindex() {
    // TODO print message? throw exception?
    if (reindexing) return;

    hasError = false;
    reindexing = true;
    log.info("Re-indexing started");

    session =
        Search.getFullTextSession(
            (Session) entityManagerFactory.createEntityManager().getDelegate());

    // set up progress counter
    objectCount = 0;
    for (Class<?> clazz : indexables) {
      objectCount +=
          (Integer)
              session.createCriteria(clazz).setProjection(Projections.rowCount()).list().get(0);
    }
    objectProgress = 0;
  }
示例#6
0
  private void reindex(Class<?> clazz) {
    log.info("Re-indexing {0}", clazz);

    ScrollableResults results = null;
    try {
      session.purgeAll(clazz);

      // TODO try this, see how it affects reindexing time:
      // session.flushToIndexes();
      // session.getSearchFactory().optimize(clazz);

      session.setFlushMode(FlushMode.MANUAL);
      session.setCacheMode(CacheMode.IGNORE);

      results =
          session.createCriteria(clazz).setFetchSize(BATCH_SIZE).scroll(ScrollMode.FORWARD_ONLY);

      int index = 0;
      while (results.next()) {
        objectProgress++;
        index++;
        session.index(results.get(0)); // index each element
        if (index % BATCH_SIZE == 0) {
          session.flushToIndexes(); // apply changes to indexes
          session.clear(); // clear since the queue is processed
        }
      }
      session.flushToIndexes(); // apply changes to indexes
      // TODO try this too, see how it affects reindexing time:
      // session.getSearchFactory().optimize(clazz);
      session.clear(); // clear since the queue is processed
    } catch (Exception e) {
      log.warn("Unable to index objects of type {0}", e, clazz.getName());
      hasError = true;
    } finally {
      if (results != null) results.close();
    }
  }
示例#7
0
  public void testTransactional() throws Exception {
    FullTextSession s = Search.getFullTextSession(openSession());
    Transaction tx = s.beginTransaction();
    final int loop = 4;
    for (int i = 0; i < loop; i++) {
      Email email = new Email();
      email.setId((long) i + 1);
      email.setTitle("JBoss World Berlin");
      email.setBody("Meet the guys who wrote the software");
      s.persist(email);
    }
    tx.commit();
    s.close();

    // check non created object does get found!!1
    s = Search.getFullTextSession(openSession());
    tx = s.beginTransaction();
    QueryParser parser =
        new QueryParser(TestConstants.getTargetLuceneVersion(), "id", TestConstants.stopAnalyzer);
    List result = s.createFullTextQuery(parser.parse("body:create")).list();
    assertEquals(0, result.size());
    tx.commit();
    s.close();

    s = Search.getFullTextSession(openSession());
    s.getTransaction().begin();
    s.doWork(
        new Work() {
          @Override
          public void execute(Connection connection) throws SQLException {
            Statement stmt = connection.createStatement();
            stmt.executeUpdate("update Email set body='Meet the guys who write the software'");
            stmt.close();
          }
        });
    s.doWork(
        new Work() {
          @Override
          public void execute(Connection connection) throws SQLException {
            // insert an object never indexed
            Statement stmt = connection.createStatement();
            stmt.executeUpdate(
                "insert into Email(id, title, body, header) values( + "
                    + (loop + 1)
                    + ", 'Bob Sponge', 'Meet the guys who create the software', 'nope')");
            stmt.close();
          }
        });

    s.getTransaction().commit();
    s.close();

    s = Search.getFullTextSession(openSession());
    tx = s.beginTransaction();
    parser =
        new QueryParser(TestConstants.getTargetLuceneVersion(), "id", TestConstants.stopAnalyzer);
    result = s.createFullTextQuery(parser.parse("body:write")).list();
    assertEquals(0, result.size());
    result = s.createCriteria(Email.class).list();
    for (int i = 0; i < loop / 2; i++) {
      s.index(result.get(i));
    }
    tx.commit(); // do the process
    s.index(result.get(loop / 2)); // do the process out of tx
    tx = s.beginTransaction();
    for (int i = loop / 2 + 1; i < loop; i++) {
      s.index(result.get(i));
    }
    tx.commit(); // do the process
    s.close();

    s = Search.getFullTextSession(openSession());
    tx = s.beginTransaction();
    // object never indexed
    Email email = (Email) s.get(Email.class, Long.valueOf(loop + 1));
    s.index(email);
    tx.commit();
    s.close();

    // check non indexed object get indexed by s.index
    s = Search.getFullTextSession(openSession());
    tx = s.beginTransaction();
    result = s.createFullTextQuery(parser.parse("body:create")).list();
    assertEquals(1, result.size());
    tx.commit();
    s.close();
  }