Пример #1
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;
  }
Пример #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);
  }
Пример #3
0
  public static List<Object> performSearch(
      Select command, Class<?> type, String cacheName, CacheContainerWrapper cache)
      throws TranslatorException {

    LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Using Lucene Searching."); // $NON-NLS-1$

    // Map<?, ?> cache,
    SearchManager searchManager = Search.getSearchManager((Cache<?, ?>) cache.getCache(cacheName));

    QueryBuilder queryBuilder = searchManager.buildQueryBuilderForClass(type).get();

    BooleanJunction<BooleanJunction> junction = queryBuilder.bool();
    boolean createdQueries = buildQueryFromWhereClause(command.getWhere(), junction, queryBuilder);

    Query query = null;
    if (createdQueries) {
      query = junction.createQuery();
    } else {
      query = queryBuilder.all().createQuery();
    }

    CacheQuery cacheQuery = searchManager.getQuery(query, type); // rootNodeType

    List<Object> results = cacheQuery.list();
    if (results == null || results.isEmpty()) {
      return Collections.emptyList();
    }

    return results;
  }
Пример #4
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();
  }
Пример #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();
    }
  }
Пример #6
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();
  }
Пример #7
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;
  }
Пример #8
0
  public void testFaceting() throws Exception {
    QueryBuilder queryBuilder = qf.buildQueryBuilderForClass(Car.class).get();

    FacetingRequest request =
        queryBuilder
            .facet()
            .name(facetName)
            .onField(indexFieldName)
            .discrete()
            .createFacetingRequest();

    Query luceneQuery = queryBuilder.all().createQuery();

    CacheQuery query = qf.getQuery(luceneQuery);

    query.getFacetManager().enableFaceting(request);

    List<Facet> facetList = query.getFacetManager().getFacets(facetName);

    assertEquals("Wrong number of facets", 2, facetList.size());

    assertEquals("4000", facetList.get(0).getValue());
    assertEquals(2, facetList.get(0).getCount());
    assertEquals(indexFieldName, facetList.get(0).getFieldName());

    assertEquals("2341", facetList.get(1).getValue());
    assertEquals(1, facetList.get(1).getCount());
    assertEquals(indexFieldName, facetList.get(1).getFieldName());
  }
Пример #9
0
  @Test
  @SuppressWarnings("unchecked")
  public void testBoolean() throws Exception {
    Transaction transaction = fullTextSession.beginTransaction();
    final QueryBuilder monthQb =
        fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Month.class).get();

    // must
    Query query =
        monthQb
            .bool()
            .must(monthQb.keyword().onField("mythology").matching("colder").createQuery())
            .createQuery();

    List<Month> results = fullTextSession.createFullTextQuery(query, Month.class).list();
    assertEquals(1, results.size());
    assertEquals("January", results.get(0).getName());

    // must not + all
    query =
        monthQb
            .bool()
            .should(monthQb.all().createQuery())
            .must(monthQb.keyword().onField("mythology").matching("colder").createQuery())
            .not()
            .createQuery();

    results = fullTextSession.createFullTextQuery(query, Month.class).list();
    assertEquals(2, results.size());
    assertEquals("February", results.get(0).getName());
    assertEquals("March", results.get(1).getName());

    // implicit must not + all (not recommended)
    query =
        monthQb
            .bool()
            .must(monthQb.keyword().onField("mythology").matching("colder").createQuery())
            .not()
            .createQuery();
    results = fullTextSession.createFullTextQuery(query, Month.class).list();
    assertEquals(2, results.size());
    assertEquals("February", results.get(0).getName());
    assertEquals("March", results.get(1).getName());

    // all except (recommended)
    query =
        monthQb
            .all()
            .except(monthQb.keyword().onField("mythology").matching("colder").createQuery())
            .createQuery();

    results = fullTextSession.createFullTextQuery(query, Month.class).list();
    assertEquals(2, results.size());
    assertEquals("February", results.get(0).getName());
    assertEquals("March", results.get(1).getName());

    transaction.commit();
  }
Пример #10
0
 @Test(expected = SearchException.class)
 public void testIllegalBooleanJunction() {
   final QueryBuilder monthQb =
       fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Month.class).get();
   // forgetting to set any condition on the boolean, an exception shall be thrown:
   BooleanJunction<BooleanJunction> booleanJunction = monthQb.bool();
   assertTrue(booleanJunction.isEmpty());
   Query query = booleanJunction.createQuery();
   Assert.fail("should not reach this point");
 }
Пример #11
0
 @Override
 public void setUp() throws Exception {
   super.setUp();
   fts = Search.getFullTextSession(openSession());
   QueryBuilder builder = fts.getSearchFactory().buildQueryBuilder().forEntity(Clock.class).get();
   allSeikoClocksQuery = builder.keyword().onField("brand").matching("Seiko").createQuery();
   allSwatchClocksQuery = builder.keyword().onField("brand").matching("Swatch").createQuery();
   noMatchQuery = builder.keyword().onField("brand").matching("Blah").createQuery();
   matchAllQuery = builder.all().createQuery();
   storeClocks(fts);
 }
Пример #12
0
 /**
  * This method filters task based on the input
  *
  * @param input - string to filter on
  * @return
  */
 public Collection<Task> filter(String input) {
   SearchManager sm = Search.getSearchManager(cache);
   QueryBuilder qb = sm.buildQueryBuilderForClass(Task.class).get();
   Query q = qb.keyword().onField("title").matching(input).createQuery();
   CacheQuery cq = sm.getQuery(q, Task.class);
   List<Task> tasks = new ArrayList<Task>();
   for (Object object : cq) {
     tasks.add((Task) object);
   }
   return tasks;
 }
 private Query getQuery(QueryBuilder queryBuilder, List<Query> queries) {
   if (queries.isEmpty()) {
     return queryBuilder.all().createQuery();
   } else {
     BooleanJunction<BooleanJunction> bool = queryBuilder.bool();
     for (Query query : queries) {
       bool.must(query);
     }
     return bool.createQuery();
   }
 }
Пример #14
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();
  }
  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;
  }
 private List<Clock> searchAll(String tenantId) {
   FullTextSession session = Search.getFullTextSession(openSessionWithTenantId(tenantId));
   QueryBuilder queryBuilder =
       session.getSearchFactory().buildQueryBuilder().forEntity(Clock.class).get();
   Query luceneQuery = queryBuilder.all().createQuery();
   Transaction transaction = session.beginTransaction();
   @SuppressWarnings("unchecked")
   List<Clock> list = session.createFullTextQuery(luceneQuery).list();
   transaction.commit();
   session.clear();
   session.close();
   return list;
 }
Пример #17
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();
 }
 private CacheQuery createAppLogLinesQuery(RequestLogs requestLogs) {
   QueryBuilder queryBuilder =
       searchManager.buildQueryBuilderForClass(CapedwarfAppLogLine.class).get();
   Query query =
       queryBuilder
           .keyword()
           .onField(CapedwarfAppLogLine.REQUEST_ID)
           .matching(requestLogs.getRequestId())
           .createQuery();
   CacheQuery cacheQuery = searchManager.getQuery(query, CapedwarfAppLogLine.class);
   cacheQuery.sort(new Sort(new SortField(CapedwarfAppLogLine.SEQUENCE_NUMBER, SortField.LONG)));
   return cacheQuery;
 }
Пример #19
0
 @SuppressWarnings("unchecked")
 @Override
 public List<Event> search(String keyword) {
   Session session = getCurrentSession();
   FullTextSession fullTextSession = Search.getFullTextSession(session);
   QueryBuilder queryBuilder =
       fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Event.class).get();
   Query luceneQuery =
       queryBuilder.keyword().onFields("name", "description").matching(keyword).createQuery();
   org.hibernate.Query hibernateQuery =
       fullTextSession.createFullTextQuery(luceneQuery, Event.class);
   return hibernateQuery.list();
 }
  @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;
  }
  public void testFieldBridge() throws Exception {
    LeakingLuceneBackend.reset();

    PersonPK johnDoePk = new PersonPK();
    johnDoePk.setFirstName("John");
    johnDoePk.setLastName("Doe");
    PersonCustomDocumentId johnDoe = new PersonCustomDocumentId();
    johnDoe.setFavoriteColor("Blue");
    johnDoe.setPersonNames(johnDoePk);
    johnDoe.setSecurityNumber("AB123");

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.save(johnDoe);
    tx.commit();
    s.clear();

    List<LuceneWork> lastProcessedQueue = LeakingLuceneBackend.getLastProcessedQueue();
    assertEquals(1, lastProcessedQueue.size());
    LuceneWork luceneWork = lastProcessedQueue.get(0);
    assertEquals("AB123", luceneWork.getIdInString());

    tx = s.beginTransaction();

    QueryBuilder queryBuilder =
        getSearchFactory().buildQueryBuilder().forEntity(PersonCustomDocumentId.class).get();
    Query query =
        queryBuilder.keyword().onField("id").ignoreAnalyzer().matching("AB123").createQuery();

    List results =
        Search.getFullTextSession(s)
            .createFullTextQuery(query, PersonCustomDocumentId.class)
            .list();
    assertEquals(1, results.size());
    johnDoe = (PersonCustomDocumentId) results.get(0);
    johnDoe.setFavoriteColor("Red");
    tx.commit();
    s.clear();

    tx = s.beginTransaction();
    results =
        Search.getFullTextSession(s)
            .createFullTextQuery(query, PersonCustomDocumentId.class)
            .list();
    assertEquals(1, results.size());
    johnDoe = (PersonCustomDocumentId) results.get(0);
    assertEquals("Red", johnDoe.getFavoriteColor());
    s.delete(results.get(0));
    tx.commit();
    s.close();
  }
Пример #22
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();
  }
  private CacheQuery createRequestLogsQuery(CapedwarfLogQuery logQuery) {
    LogQuery query = logQuery.getQuery();
    QueryBuilder queryBuilder =
        searchManager.buildQueryBuilderForClass(CapedwarfRequestLogs.class).get();
    List<Query> queries = new ArrayList<Query>();
    if (query.getStartTimeUsec() != null) {
      queries.add(
          queryBuilder
              .range()
              .onField(CapedwarfRequestLogs.END_TIME_USEC)
              .above(query.getStartTimeUsec())
              .createQuery());
    }
    if (query.getEndTimeUsec() != null) {
      queries.add(
          queryBuilder
              .range()
              .onField(CapedwarfRequestLogs.END_TIME_USEC)
              .below(query.getEndTimeUsec())
              .createQuery());
    }
    if (query.getMinLogLevel() != null) {
      queries.add(
          queryBuilder
              .range()
              .onField(CapedwarfRequestLogs.MAX_LOG_LEVEL)
              .above(query.getMinLogLevel().ordinal())
              .createQuery());
    }

    boolean onlyCompleteRequests = !Boolean.TRUE.equals(query.getIncludeIncomplete());
    if (onlyCompleteRequests) {
      queries.add(
          queryBuilder
              .keyword()
              .onField(CapedwarfRequestLogs.FINISHED)
              .matching(Boolean.TRUE)
              .createQuery());
    }

    Query luceneQuery = getQuery(queryBuilder, queries);
    CacheQuery cacheQuery = searchManager.getQuery(luceneQuery, CapedwarfRequestLogs.class);
    cacheQuery.sort(
        new Sort(new SortField(CapedwarfRequestLogs.END_TIME_USEC, SortField.LONG, true)));
    cacheQuery.firstResult(logQuery.getOptions().getOffset());
    if (logQuery.getOptions().getLimit() != null) {
      cacheQuery.maxResults(logQuery.getOptions().getLimit());
    }
    return cacheQuery;
  }
Пример #24
0
  @Test
  @SuppressWarnings("unchecked")
  public void testMultipleFields() throws Exception {
    Transaction transaction = fullTextSession.beginTransaction();
    final QueryBuilder monthQb =
        fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Month.class).get();

    // combined query, January and february both contain whitening but February in a longer text
    Query query =
        monthQb
            .keyword()
            .onField("mythology")
            .andField("history")
            .matching("whitening")
            .createQuery();

    List<Month> results = fullTextSession.createFullTextQuery(query, Month.class).list();
    assertEquals(2, results.size());
    assertEquals("January", results.get(0).getName());

    // combined query, January and february both contain whitening but February in a longer text
    query =
        monthQb
            .keyword()
            .onFields("mythology", "history")
            .boostedTo(30)
            .matching("whitening")
            .createQuery();

    results = fullTextSession.createFullTextQuery(query, Month.class).list();
    assertEquals(2, results.size());
    assertEquals("January", results.get(0).getName());

    // boosted query, January and february both contain whitening but February in a longer text
    // since history is boosted, February should come first though
    query =
        monthQb
            .keyword()
            .onField("mythology")
            .andField("history")
            .boostedTo(30)
            .matching("whitening")
            .createQuery();

    results = fullTextSession.createFullTextQuery(query, Month.class).list();
    assertEquals(2, results.size());
    assertEquals("February", results.get(0).getName());

    transaction.commit();
  }
Пример #25
0
  @Test
  @TestForIssue(jiraKey = "HSEARCH-703")
  public void testPolymorphicQueryForUnindexedSuperTypeReturnsIndexedSubType() {
    Transaction transaction = fullTextSession.beginTransaction();

    final QueryBuilder builder =
        fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Object.class).get();

    Query query = builder.all().createQuery();
    List<?> results = fullTextSession.createFullTextQuery(query, Object.class).list();

    assertEquals("expected all instances of all indexed types", 7, results.size());

    transaction.commit();
  }
Пример #26
0
  @Test
  @TestForIssue(jiraKey = "HSEARCH-1074")
  public void testPhraseQueryWithNoTermsAfterAnalyzerApplication() throws Exception {
    Transaction transaction = fullTextSession.beginTransaction();
    final QueryBuilder monthQb =
        fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Month.class).get();

    Query query = monthQb.phrase().onField("mythology").sentence("and").createQuery();

    assertEquals(
        "there should be no results, since all terms are stop words",
        0,
        fullTextSession.createFullTextQuery(query, Month.class).getResultSize());
    transaction.commit();
  }
Пример #27
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();
  }
Пример #28
0
  @Test
  @TestForIssue(jiraKey = "HSEARCH-703")
  public void testPolymorphicQueryWithKeywordTermForUnindexedSuperTypeReturnsIndexedSubType() {
    Transaction transaction = fullTextSession.beginTransaction();

    final QueryBuilder builder =
        fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Car.class).get();

    Query query = builder.keyword().onField("name").matching("Morris").createQuery();
    List<?> results = fullTextSession.createFullTextQuery(query).list();

    assertEquals("expected one instance of indexed sub-type", 1, results.size());
    assertEquals(180, ((SportsCar) results.get(0)).getEnginePower());

    transaction.commit();
  }
Пример #29
0
  @Test
  public void testNumericFieldsTermQuery() {
    Transaction transaction = fullTextSession.beginTransaction();
    final QueryBuilder monthQb =
        fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Month.class).get();

    Query query = monthQb.keyword().onField("raindropInMm").matching(0.231d).createQuery();

    assertTrue(query.getClass().isAssignableFrom(NumericRangeQuery.class));

    assertEquals(
        "test term numeric ",
        1,
        fullTextSession.createFullTextQuery(query, Month.class).getResultSize());

    transaction.commit();
  }
Пример #30
0
  @Test
  public void testNumericRangeQueries() {
    Transaction transaction = fullTextSession.beginTransaction();
    final QueryBuilder monthQb =
        fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Month.class).get();

    Query query = monthQb.range().onField("raindropInMm").from(0.23d).to(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();
  }