@Override
 public FullTextEntityManager getSearchManager() {
   return this.ftEntityManager =
       (ftEntityManager == null)
           ? Search.getFullTextEntityManager(entityManager)
           : ftEntityManager;
 }
Beispiel #2
0
  // locate a customer in the database
  public Customers extractCustomer(String email, String password) {

    FullTextEntityManager fullTextEntityManager =
        org.hibernate.search.jpa.Search.getFullTextEntityManager(em);

    QueryBuilder queryBuilder =
        fullTextEntityManager
            .getSearchFactory()
            .buildQueryBuilder()
            .forEntity(Customers.class)
            .get();
    org.apache.lucene.search.Query query =
        queryBuilder
            .bool()
            .must(queryBuilder.keyword().onField("email").matching(email).createQuery())
            .must(queryBuilder.keyword().onField("password").matching(password).createQuery())
            .createQuery();

    FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(query, Customers.class);

    fullTextQuery.initializeObjectsWith(
        ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID);

    List results = fullTextQuery.getResultList();

    if (results.isEmpty()) {
      return null;
    }

    return (Customers) results.get(0);
  }
Beispiel #3
0
  // loading categories ids and names
  public List<String> extractCategories() {

    FullTextEntityManager fullTextEntityManager =
        org.hibernate.search.jpa.Search.getFullTextEntityManager(em);

    QueryBuilder queryBuilder =
        fullTextEntityManager
            .getSearchFactory()
            .buildQueryBuilder()
            .forEntity(Categories.class)
            .get();
    org.apache.lucene.search.Query query = queryBuilder.all().createQuery();

    FullTextQuery fullTextQuery =
        fullTextEntityManager.createFullTextQuery(query, Categories.class);
    fullTextQuery.setProjection(FullTextQuery.ID, "category");
    Sort sort = new Sort(new SortField("category", SortField.STRING));
    fullTextQuery.setSort(sort);

    fullTextQuery.initializeObjectsWith(
        ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID);

    List<String> results = fullTextQuery.getResultList();

    return results;
  }
Beispiel #4
0
  // loading products of a category
  public Map<Integer, List<Products>> extractProducts(String id, int page) {

    FullTextEntityManager fullTextEntityManager =
        org.hibernate.search.jpa.Search.getFullTextEntityManager(em);

    QueryBuilder queryBuilder =
        fullTextEntityManager
            .getSearchFactory()
            .buildQueryBuilder()
            .forEntity(Products.class)
            .get();
    org.apache.lucene.search.Query query =
        queryBuilder.keyword().onField("category.id").matching(id).createQuery();

    FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(query, Products.class);
    Sort sort = new Sort(new SortField("price", SortField.DOUBLE));
    fullTextQuery.setSort(sort);

    fullTextQuery.initializeObjectsWith(
        ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID);

    fullTextQuery.setFirstResult(page * 3);
    fullTextQuery.setMaxResults(3);
    List<Products> results = fullTextQuery.getResultList();

    Map<Integer, List<Products>> results_and_total = new HashMap<Integer, List<Products>>();
    results_and_total.put(fullTextQuery.getResultSize(), results);

    return results_and_total;
  }
 private void purge() {
   FullTextEntityManager ftEm = org.hibernate.search.jpa.Search.getFullTextEntityManager(em);
   ftEm.purgeAll(Book.class);
   ftEm.flushToIndexes();
   ftEm.close();
   emf.close();
 }
  /** {@inheritDoc} */
  @SuppressWarnings("unchecked")
  @Override
  public List<AbstractPermissionsOwner> search(
      String queryString, boolean withUsers, boolean withGroups) {
    List<AbstractPermissionsOwner> results = new ArrayList<AbstractPermissionsOwner>();
    // No query should be realized while re-indexing resources.
    if (!inhibitSearch) {
      // Gets the Hibernate search object to performs queries.
      FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);

      // Parse the the queryString.
      MultiFieldQueryParser parser =
          new MultiFieldQueryParser(
              Version.LUCENE_30,
              new String[] {"name", "firstName", "lastName", "email", "login"},
              new StandardAnalyzer(Version.LUCENE_31));
      parser.setDefaultOperator(Operator.OR);

      try {
        Query luceneQuery = parser.parse(queryString);

        FullTextQuery query = null;
        // Because of the poor design of the Hibernate Search API and the usage of varagrs, we must
        // have this
        // if-else algorihm. TODO refactor with reflection.
        if (withUsers && withGroups) {
          query = fullTextEntityManager.createFullTextQuery(luceneQuery, User.class, Group.class);
        } else if (withUsers) {
          query = fullTextEntityManager.createFullTextQuery(luceneQuery, User.class);
        } else if (withGroups) {
          query = fullTextEntityManager.createFullTextQuery(luceneQuery, Group.class);
        }
        // Finally execute the query.
        if (query != null) {
          List<AbstractPermissionsOwner> found = query.getResultList();
          // Keeps only distinct results.
          for (AbstractPermissionsOwner foundObject : found) {
            if (!results.contains(foundObject)) {
              // TODO Remove this Hibernate specific block.
              // Sometimes hibernate Search returns Javassist proxies, which can't be properly
              // deserialize by Jackson.
              if (foundObject instanceof HibernateProxy) {
                HibernateProxy h = (HibernateProxy) foundObject;
                foundObject =
                    (AbstractPermissionsOwner) h.getHibernateLazyInitializer().getImplementation();
              }
              results.add(foundObject);
            }
          }
        }
      } catch (ParseException exc) {
        // Handle parsing failure
        String error = "Misformatted queryString '" + queryString + "': " + exc.getMessage();
        logger.debug("[search] " + error);
        throw new IllegalArgumentException(error, exc);
      }
    }
    return results;
  } // search().
 private void startAndWaitMassIndexing(Class<?>... entityTypes) throws InterruptedException {
   FullTextEntityManager fullTextEm = Search.getFullTextEntityManager(createEntityManager());
   fullTextEm.createIndexer(entityTypes).purgeAllOnStart(true).startAndWait();
   int numDocs =
       fullTextEm.getSearchFactory().getIndexReaderAccessor().open(entityTypes).numDocs();
   fullTextEm.close();
   assertThat(numDocs).isGreaterThan(0);
 }
 private void index() {
   FullTextEntityManager ftEm = org.hibernate.search.jpa.Search.getFullTextEntityManager(em);
   try {
     ftEm.createIndexer().startAndWait();
   } catch (InterruptedException e) {
     log.error("Was interrupted during indexing", e);
   }
 }
 private void purgeAll(Class<?>... entityTypes) throws Exception {
   FullTextEntityManager fullTextEm = Search.getFullTextEntityManager(createEntityManager());
   for (Class<?> entityType : entityTypes) {
     fullTextEm.purgeAll(entityType);
     fullTextEm.flushToIndexes();
   }
   int numDocs =
       fullTextEm.getSearchFactory().getIndexReaderAccessor().open(entityTypes).numDocs();
   fullTextEm.close();
   assertThat(numDocs).isEqualTo(0);
 }
  @PostConstruct
  public void indexaBaseDeDados() {
    try {

      FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);

      fullTextEntityManager.createIndexer().startAndWait();

    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
  private FullTextQuery buildFullTextQuery(
      UserSearchRequest request, Pageable pageable, Criteria criteria) {
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
    QueryBuilder qb =
        fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(User.class).get();

    @SuppressWarnings("rawtypes")
    BooleanJunction<BooleanJunction> junction = qb.bool();
    junction.must(qb.all().createQuery());

    if (StringUtils.hasText(request.getKeyword())) {
      Analyzer analyzer = fullTextEntityManager.getSearchFactory().getAnalyzer("synonyms");
      String[] fields =
          new String[] {
            "loginId", "name.firstName", "name.lastName",
          };
      MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);
      parser.setDefaultOperator(QueryParser.Operator.AND);
      Query query = null;
      try {
        query = parser.parse(request.getKeyword());
      } catch (ParseException e1) {
        try {
          query = parser.parse(QueryParser.escape(request.getKeyword()));
        } catch (ParseException e2) {
          throw new RuntimeException(e2);
        }
      }
      junction.must(query);
    }

    if (!CollectionUtils.isEmpty(request.getRoles())) {
      for (User.Role role : request.getRoles()) {
        junction.must(qb.keyword().onField("roles").matching(role).createQuery());
      }
    }

    Query searchQuery = junction.createQuery();

    Sort sort = new Sort(new SortField("id", SortField.Type.STRING, false));

    FullTextQuery persistenceQuery =
        fullTextEntityManager
            .createFullTextQuery(searchQuery, User.class)
            .setCriteriaQuery(criteria)
            //				.setProjection("id")
            .setSort(sort);
    if (pageable != null) {
      persistenceQuery.setFirstResult(pageable.getOffset());
      persistenceQuery.setMaxResults(pageable.getPageSize());
    }
    return persistenceQuery;
  }
Beispiel #12
0
 public synchronized void reindex(Class clazz) {
   log.info("reindex job started for entity {} ", clazz.getName());
   FullTextEntityManager fullTextEntityManager =
       Search.getFullTextEntityManager(getEntityManagerForActiveEntities());
   try {
     fullTextEntityManager.createIndexer(clazz).startAndWait();
     log.info("reindex job ended for entity {} ", clazz.getName());
   } catch (InterruptedException e) {
     if (log.isErrorEnabled()) {
       log.error("Reindex job interrupted", e);
     }
   }
 }
  /**
   * Test that a entity manager can successfully be serialized and deserialized.
   *
   * @throws Exception in case the test fails.
   */
  @Test
  public void testSerialization() throws Exception {
    FullTextEntityManager em = Search.getFullTextEntityManager(factory.createEntityManager());

    indexSearchAssert(em);

    FullTextEntityManager clone = SerializationTestHelper.duplicateBySerialization(em);

    indexSearchAssert(clone);

    clone.close();
    em.close();
  }
Beispiel #14
0
  @SuppressWarnings("unchecked")
  public SearchResult<Subject> searchSubjectsBasic(int resultsPerPage, int page, String text) {

    int firstResult = page * resultsPerPage;

    StringBuilder queryBuilder = new StringBuilder();

    if (!StringUtils.isBlank(text)) {
      queryBuilder.append("+(");
      addTokenizedSearchCriteria(queryBuilder, "name", text, false);
      addTokenizedSearchCriteria(queryBuilder, "educationType.name", text, false);
      queryBuilder.append(")");
    }

    EntityManager entityManager = getEntityManager();
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);

    try {
      String queryString = queryBuilder.toString();
      Query luceneQuery;
      QueryParser parser =
          new QueryParser(Version.LUCENE_29, "", new StandardAnalyzer(Version.LUCENE_29));
      if (StringUtils.isBlank(queryString)) {
        luceneQuery = new MatchAllDocsQuery();
      } else {
        luceneQuery = parser.parse(queryString);
      }

      FullTextQuery query =
          (FullTextQuery)
              fullTextEntityManager
                  .createFullTextQuery(luceneQuery, Subject.class)
                  .setFirstResult(firstResult)
                  .setMaxResults(resultsPerPage);
      query.enableFullTextFilter("ArchivedSubject").setParameter("archived", Boolean.FALSE);

      int hits = query.getResultSize();
      int pages = hits / resultsPerPage;
      if (hits % resultsPerPage > 0) {
        pages++;
      }

      int lastResult = Math.min(firstResult + resultsPerPage, hits) - 1;

      return new SearchResult<Subject>(
          page, pages, hits, firstResult, lastResult, query.getResultList());

    } catch (ParseException e) {
      throw new PersistenceException(e);
    }
  }
  @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;
  }
Beispiel #16
0
  /**
   * Serch method
   *
   * @param f
   * @param luquery
   * @param entities
   * @return
   * @throws Exception
   */
  @Transactional(propagation = Propagation.REQUIRED)
  public List<Object> search(
      String[] f,
      String luquery,
      SortField[] sortFields,
      int firstResult,
      int maxResults,
      Class<?>... entities)
      throws Exception {

    // create FullTextEntityManager ----------------------------
    FullTextEntityManager fullTextEntityManager =
        org.hibernate.search.jpa.Search.getFullTextEntityManager(entityManager);

    // ---------------------------------------------------------

    MultiFieldQueryParser parser =
        new MultiFieldQueryParser(Version.LUCENE_31, f, new StandardAnalyzer(Version.LUCENE_31));

    org.apache.lucene.search.Query query = parser.parse(luquery.trim());

    System.out.println(luquery + " --> QUERY: " + query + " entitys size:" + entities.length);

    // wrap Lucene query in a javax.persistence.Query
    // javax.persistence.Query persistenceQuery = fullTextEntityManager
    // .createFullTextQuery(query, entities);

    org.hibernate.search.jpa.FullTextQuery persistenceQuery =
        fullTextEntityManager.createFullTextQuery(query, entities);

    // org.apache.lucene.search.Sort sort = new Sort(
    // new SortField("title", SortField.STRING));

    if (sortFields != null && sortFields.length > 0) {
      persistenceQuery.setSort(new Sort(sortFields));
      System.out.println("Sort setted");
    }

    if (firstResult >= 0) {
      persistenceQuery.setFirstResult(firstResult);
      persistenceQuery.setMaxResults(maxResults);
    }

    // execute search
    @SuppressWarnings("unchecked")
    List<Object> result = persistenceQuery.getResultList();

    return result;
  }
 /** {@inheritDoc} */
 @Override
 public void resetIndexes() {
   logger.info("[resetIndexes] Re-indexing all users, groups and roles...");
   this.inhibitSearch = true;
   try {
     FullTextEntityManager searchFactory = Search.getFullTextEntityManager(entityManager);
     searchFactory.createIndexer(User.class, Group.class, Role.class).startAndWait();
   } catch (InterruptedException exc) {
     logger.error(
         "[reset] Fatal error while re-indexing users, groups and roles " + exc.getMessage(), exc);
   }
   // Remove inhibition flag
   this.inhibitSearch = false;
   logger.info("[resetIndexes] Re-indexation finished");
 } // resetIndexes().
Beispiel #18
0
  @Override
  public List<User> searchUsers(String querySearch) {
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
    QueryBuilder qb =
        fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(User.class).get();

    // query nativa do apache lucene
    org.apache.lucene.search.Query query =
        qb.keyword().onFields("userName").matching(querySearch).createQuery();

    javax.persistence.Query jpaQuery = fullTextEntityManager.createFullTextQuery(query, User.class);

    // @TODO: paginação
    return jpaQuery.getResultList();
  }
Beispiel #19
0
 public void indexAllItems() {
   FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
   List results =
       fullTextEntityManager
           .createQuery("from " + persistentClass.getCanonicalName())
           .getResultList();
   int counter = 0, numItemsInGroup = 10;
   Iterator resultsIt = results.iterator();
   while (resultsIt.hasNext()) {
     fullTextEntityManager.index(resultsIt.next());
     if (counter++ % numItemsInGroup == 0) {
       fullTextEntityManager.flushToIndexes();
       fullTextEntityManager.clear();
     }
   }
 }
Beispiel #20
0
  @Transactional(propagation = Propagation.REQUIRED)
  public int searchCount(String[] f, String luquery, Class<?>... entities) throws Exception {

    // create FullTextEntityManager ----------------------------
    FullTextEntityManager fullTextEntityManager =
        org.hibernate.search.jpa.Search.getFullTextEntityManager(entityManager);
    // ---------------------------------------------------------

    QueryParser parser =
        new MultiFieldQueryParser(Version.LUCENE_31, f, new StandardAnalyzer(Version.LUCENE_31));

    org.apache.lucene.search.Query query = parser.parse(luquery.trim());

    // wrap Lucene query in a javax.persistence.Query
    return fullTextEntityManager.createFullTextQuery(query, entities).getResultSize();
  }
Beispiel #21
0
  // loading promotional products
  public List<Products> extractPromotionalProducts() {

    FullTextEntityManager fullTextEntityManager =
        org.hibernate.search.jpa.Search.getFullTextEntityManager(em);

    org.apache.lucene.search.Query query =
        NumericRangeQuery.newDoubleRange("old_price", 0.0d, 1000d, false, true);
    FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(query, Products.class);
    Sort sort = new Sort(new SortField("price", SortField.DOUBLE));
    fullTextQuery.setSort(sort);

    fullTextQuery.initializeObjectsWith(
        ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID);

    List results = fullTextQuery.getResultList();

    return results;
  }
Beispiel #22
0
  @SuppressWarnings("unchecked")
  public List<Book> freeTextSeachEntities(
      String searchWord,
      String[] targetFields,
      String orderBy,
      boolean reverseOrder,
      int startIndex,
      int maxResult) {
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
    QueryParser parser =
        new MultiFieldQueryParser(
            org.apache.lucene.util.Version.LUCENE_29,
            targetFields,
            new StandardAnalyzer(org.apache.lucene.util.Version.LUCENE_29));
    parser.setAllowLeadingWildcard(true);

    org.apache.lucene.search.Query luceneQuery = null;
    try {
      luceneQuery = parser.parse(searchWord);
      System.out.println("@@@luceneQuery : " + luceneQuery.toString());
    } catch (ParseException e) {
      System.out.println("@@@ParseEcxetpion : " + e.getMessage());
    }
    FullTextQuery fullTextQuery =
        fullTextEntityManager.createFullTextQuery(luceneQuery, Book.class);

    if (orderBy != null) {
      Sort sort = new Sort(new SortField(orderBy, SortField.STRING_VAL, reverseOrder));
      fullTextQuery.setSort(sort);
    }

    if (startIndex > 0 && maxResult > 0) {
      fullTextQuery.setFirstResult(startIndex);
      fullTextQuery.setMaxResults(maxResult);
    }

    Query jpaQuery = fullTextQuery;

    List<Book> resultEntities = jpaQuery.getResultList();

    return resultEntities;
  }
 @Override
 public void postSetUp() throws Exception {
   FullTextEntityManager entityManager =
       Search.getFullTextEntityManager(factory.createEntityManager());
   EntityTransaction tx = null;
   try {
     tx = entityManager.getTransaction();
     tx.begin();
     // manual indexing solution OK for small amounts of data
     List results =
         entityManager.createQuery("select i from " + Item.class.getName() + " i").getResultList();
     for (Object entity : results) {
       entityManager.index(entity); // index each element
     }
     // commit the index changes
     tx.commit();
   } finally {
     entityManager.close();
   }
 }
 @SuppressWarnings("unchecked")
 private void assertAssociatedElementsHaveBeenIndexed() throws Exception {
   FullTextEntityManager fullTextEm = Search.getFullTextEntityManager(createEntityManager());
   fullTextEm.getTransaction().begin();
   QueryBuilder b =
       fullTextEm.getSearchFactory().buildQueryBuilder().forEntity(IndexedLabel.class).get();
   {
     Query luceneQuery = b.keyword().wildcard().onField("name").matching("tes*").createQuery();
     List<IndexedLabel> labels = fullTextEm.createFullTextQuery(luceneQuery).getResultList();
     assertThat(labels).hasSize(1);
     assertThat(contains(labels, "test")).isTrue();
   }
   {
     Query luceneQuery = b.keyword().wildcard().onField("name").matching("mas*").createQuery();
     List<IndexedLabel> labels = fullTextEm.createFullTextQuery(luceneQuery).getResultList();
     assertThat(labels).hasSize(1);
     assertThat(contains(labels, "massindex")).isTrue();
   }
   fullTextEm.getTransaction().commit();
   fullTextEm.close();
 }
  private Query searchQuery(String searchQuery) throws ParseException {

    String[] bookFields = {"title", "subtitle", "authors.name", "publicationDate"};

    // lucene part
    Map<String, Float> boostPerField = new HashMap<String, Float>(4);
    boostPerField.put(bookFields[0], (float) 4);
    boostPerField.put(bookFields[1], (float) 3);
    boostPerField.put(bookFields[2], (float) 4);
    boostPerField.put(bookFields[3], (float) .5);

    FullTextEntityManager ftEm = org.hibernate.search.jpa.Search.getFullTextEntityManager(em);
    Analyzer customAnalyzer = ftEm.getSearchFactory().getAnalyzer("customanalyzer");
    QueryParser parser =
        new MultiFieldQueryParser(Version.LUCENE_34, bookFields, customAnalyzer, boostPerField);

    org.apache.lucene.search.Query luceneQuery;
    luceneQuery = parser.parse(searchQuery);

    final FullTextQuery query = ftEm.createFullTextQuery(luceneQuery, Book.class);

    return query;
  }
  private void assertEntityHasBeenIndexed() throws Exception {
    FullTextEntityManager fullTextEm = Search.getFullTextEntityManager(createEntityManager());
    fullTextEm.getTransaction().begin();
    QueryBuilder queryBuilder =
        fullTextEm.getSearchFactory().buildQueryBuilder().forEntity(IndexedNews.class).get();
    Query luceneQuery =
        queryBuilder
            .keyword()
            .wildcard()
            .onField("newsId")
            .ignoreFieldBridge()
            .matching("tit*")
            .createQuery();
    @SuppressWarnings("unchecked")
    List<IndexedNews> list = fullTextEm.createFullTextQuery(luceneQuery).getResultList();
    assertThat(list).hasSize(1);

    List<IndexedLabel> labels = list.get(0).getLabels();
    assertThat(labels).hasSize(2);
    assertThat(contains(labels, "massindex")).isTrue();
    assertThat(contains(labels, "test")).isTrue();
    fullTextEm.getTransaction().commit();
    fullTextEm.close();
  }
Beispiel #27
0
  // search a product by name
  public List<Products> searchProducts(String search) {

    FullTextEntityManager fullTextEntityManager =
        org.hibernate.search.jpa.Search.getFullTextEntityManager(em);

    QueryBuilder queryBuilder =
        fullTextEntityManager
            .getSearchFactory()
            .buildQueryBuilder()
            .forEntity(Products.class)
            .get();
    org.apache.lucene.search.Query query =
        queryBuilder.keyword().onField("product").matching(search).createQuery();

    FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(query, Products.class);

    fullTextQuery.initializeObjectsWith(
        ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID);
    fullTextQuery.setMaxResults(3);

    List results = fullTextQuery.getResultList();

    return results;
  }
Beispiel #28
0
 /**
  * Gets the full text entity manager.
  *
  * @return the full text entity manager
  */
 protected final FullTextEntityManager getFullTextEntityManager() {
   return Search.getFullTextEntityManager(getEntityManager());
 }
  @Override
  public Page<Comment> search(CommentSearchRequest request, Pageable pageable) {
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
    QueryBuilder qb =
        fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Comment.class).get();

    @SuppressWarnings("rawtypes")
    BooleanJunction<BooleanJunction> junction = qb.bool();
    junction.must(qb.all().createQuery());

    if (StringUtils.hasText(request.getKeyword())) {
      Analyzer analyzer = fullTextEntityManager.getSearchFactory().getAnalyzer("synonyms");
      String[] fields = new String[] {"authorName", "content"};
      MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);
      parser.setDefaultOperator(QueryParser.Operator.AND);
      Query query = null;
      try {
        query = parser.parse(request.getKeyword());
      } catch (ParseException e1) {
        try {
          query = parser.parse(QueryParser.escape(request.getKeyword()));
        } catch (ParseException e2) {
          throw new RuntimeException(e2);
        }
      }
      junction.must(query);
    }

    if (StringUtils.hasText(request.getLanguage())) {
      junction.must(
          qb.keyword().onField("post.language").matching(request.getLanguage()).createQuery());
    }

    if (request.getPostId() != null) {
      junction.must(qb.keyword().onField("post.id").matching(request.getPostId()).createQuery());
    }

    if (request.getApproved() != null) {
      junction.must(qb.keyword().onField("approved").matching(request.getApproved()).createQuery());
    }

    Query searchQuery = junction.createQuery();

    Session session = (Session) entityManager.getDelegate();
    Criteria criteria =
        session
            .createCriteria(Comment.class)
            .setFetchMode("post", FetchMode.JOIN)
            .setFetchMode("author", FetchMode.JOIN);

    Sort sort = null;
    if (pageable.getSort() != null) {
      if (pageable.getSort().getOrderFor("date") != null) {
        Order order = pageable.getSort().getOrderFor("date");
        sort =
            new Sort(
                new SortField(
                    "date", SortField.Type.STRING, order.getDirection().equals(Direction.DESC)),
                new SortField(
                    "id", SortField.Type.LONG, order.getDirection().equals(Direction.DESC)));
      }
    }

    if (sort == null) {
      sort =
          new Sort(
              new SortField("date", SortField.Type.STRING),
              new SortField("id", SortField.Type.LONG));
    }

    FullTextQuery persistenceQuery =
        fullTextEntityManager
            .createFullTextQuery(searchQuery, Comment.class)
            .setCriteriaQuery(criteria)
            .setSort(sort);
    persistenceQuery.setFirstResult(pageable.getOffset());
    persistenceQuery.setMaxResults(pageable.getPageSize());

    int resultSize = persistenceQuery.getResultSize();

    @SuppressWarnings("unchecked")
    List<Comment> results = persistenceQuery.getResultList();
    return new PageImpl<>(results, pageable, resultSize);
  }
Beispiel #30
0
 public void indexEntity(T object) {
   FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
   fullTextEntityManager.index(object);
 }