示例#1
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();
  }
  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());
  }
示例#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
  // 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;
  }
示例#5
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);
 }
 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();
   }
 }
  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;
 }
示例#9
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();
  }
示例#10
0
  public void testPutMap() throws Exception {
    prepareTestData();
    SearchManager searchManager = Search.getSearchManager(cache2);
    QueryBuilder queryBuilder = searchManager.buildQueryBuilderForClass(Person.class).get();
    Query allQuery = queryBuilder.all().createQuery();
    assert searchManager.getQuery(allQuery, Person.class).list().size() == 3;

    Map<String, Person> allWrites = new HashMap<String, Person>();
    allWrites.put(key1, person1);
    allWrites.put(key2, person2);
    allWrites.put(key3, person3);

    cache2.putAll(allWrites);
    List found = searchManager.getQuery(allQuery, Person.class).list();
    AssertJUnit.assertEquals(3, found.size());

    cache2.putAll(allWrites);
    found = searchManager.getQuery(allQuery, Person.class).list();
    AssertJUnit.assertEquals(3, found.size());
  }
  @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);
  }
  private FullTextQuery buildFullTextQuery(
      ArticleSearchRequest request, Pageable pageable, Criteria criteria) {
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
    QueryBuilder qb =
        fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Article.class).get();

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

    junction.must(
        qb.keyword().onField("drafted").ignoreAnalyzer().matching("_null_").createQuery());

    if (StringUtils.hasText(request.getKeyword())) {
      Analyzer analyzer = fullTextEntityManager.getSearchFactory().getAnalyzer("synonyms");
      String[] fields =
          new String[] {
            "title", "body",
            "categories.name", "tags.name",
          };
      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 (request.getStatus() != null) {
      junction.must(qb.keyword().onField("status").matching(request.getStatus()).createQuery());
    }
    if (StringUtils.hasText(request.getLanguage())) {
      junction.must(qb.keyword().onField("language").matching(request.getLanguage()).createQuery());
    }

    if (request.getDateFrom() != null) {
      junction.must(qb.range().onField("date").above(request.getDateFrom()).createQuery());
    }
    if (request.getDateTo() != null) {
      junction.must(qb.range().onField("date").below(request.getDateTo()).createQuery());
    }

    if (!CollectionUtils.isEmpty(request.getCategoryIds())) {
      BooleanJunction<BooleanJunction> subJunction = qb.bool();
      for (long categoryId : request.getCategoryIds()) {
        subJunction.should(
            qb.keyword().onField("categories.id").matching(categoryId).createQuery());
      }
      junction.must(subJunction.createQuery());
    }
    if (!CollectionUtils.isEmpty(request.getCategoryCodes())) {
      BooleanJunction<BooleanJunction> subJunction = qb.bool();
      for (String categoryCode : request.getCategoryCodes()) {
        subJunction.should(
            qb.keyword().onField("categories.code").matching(categoryCode).createQuery());
      }
      junction.must(subJunction.createQuery());
    }

    if (!CollectionUtils.isEmpty(request.getTagIds())) {
      BooleanJunction<BooleanJunction> subJunction = qb.bool();
      for (long tagId : request.getTagIds()) {
        subJunction.should(qb.keyword().onField("tags.id").matching(tagId).createQuery());
      }
      junction.must(subJunction.createQuery());
    }
    if (!CollectionUtils.isEmpty(request.getTagNames())) {
      BooleanJunction<BooleanJunction> subJunction = qb.bool();
      for (String tagName : request.getTagNames()) {
        subJunction.should(qb.phrase().onField("tags.name").sentence(tagName).createQuery());
      }
      junction.must(subJunction.createQuery());
    }

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

    Query searchQuery = junction.createQuery();

    Sort sort =
        new Sort(
            new SortField("date", SortField.Type.STRING, true),
            new SortField("id", SortField.Type.LONG, true));

    FullTextQuery persistenceQuery =
        fullTextEntityManager
            .createFullTextQuery(searchQuery, Article.class)
            .setCriteriaQuery(criteria)
            .setSort(sort);
    if (pageable != null) {
      persistenceQuery.setFirstResult(pageable.getOffset());
      persistenceQuery.setMaxResults(pageable.getPageSize());
    }
    return persistenceQuery;
  }