Java 类org.hibernate.search.query.dsl.QueryBuilder 实例源码

项目:ait-platform    文件:AitFTSRepo.java   
@Override
public FullTextQuery getFTSQuery(String filterText, final Class<?> entityType, Integer maxResults, String... fields) {

    // entityManager para busquedas de tipo FTS
    final FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager(entityManager);

    // se crea el query usando Hibernate Search query DSL
    final QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(entityType).get();

    // se crea el query sobre los campos indicados
    final Query query = queryBuilder.keyword().onFields(fields).matching(filterText.trim()).createQuery();

    // se enmascara el query de Lucene en uno de Hibernate
    final FullTextQuery jpaQuery = fullTextEntityManager.createFullTextQuery(query, entityType);

    // se define la cantidad maxima de resultados si es mayor a cero
    if (maxResults > 0) {
        jpaQuery.setMaxResults(maxResults);
    }
    // se retorna el query listo para ejecución o para inyeccion de criterias
    return jpaQuery;
}
项目:bookManager    文件:BookDatabaseImpl.java   
@Transactional
@Override
public Page<Book> search(String query, Pageable page) {
    FullTextEntityManager manager = this.getFullTextEntityManager();

    QueryBuilder builder = manager.getSearchFactory().buildQueryBuilder().forEntity(Book.class).get();

    Query luceneQuery = builder.keyword().fuzzy()
            .onFields("author", "title", "lang", "description", "isbn", "genre", "location").matching(query)
            .createQuery();

    FullTextQuery q = manager.createFullTextQuery(luceneQuery, Book.class);
    q.setProjection(FullTextQuery.THIS, FullTextQuery.SCORE);

    long total = q.getResultSize();
    q.setFirstResult(page.getOffset()).setMaxResults(page.getPageSize());

    @SuppressWarnings("unchecked")
    List<Object[]> result = q.getResultList();
    List<Book> fine = new LinkedList<>();
    for (Object[] i : result) {
        fine.add((Book) i[0]);
    }
    return new PageImpl<>(fine, page, total);
}
项目:ait-platform    文件:AitFTSRepo.java   
@Override
public FullTextQuery getFTSWildcardQuery(String filterText, final Class<?> entityType, Integer maxResults, String field) {

    // entityManager para busquedas de tipo FTS
    final FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager(entityManager);

    // se crea el query usando Hibernate Search query DSL
    final QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(entityType).get();

    // se crea el query sobre los campos indicados
    final Query query = queryBuilder.phrase().onField(field).sentence(filterText.trim()).createQuery();

    // se enmascara el query de Lucene en uno de Hibernate
    final FullTextQuery jpaQuery = fullTextEntityManager.createFullTextQuery(query, entityType);

    // se define la cantidad maxima de resultados si es mayor a cero
    if (maxResults > 0) {
        jpaQuery.setMaxResults(maxResults);
    }
    // se retorna el query listo para ejecución o para inyeccion de criterias
    return jpaQuery;
}
项目:mblog    文件:PostDaoImpl.java   
@Override
@SuppressWarnings("unchecked")
public List<PostPO> searchByTag(Paging paigng, String tag) {
    FullTextSession fullTextSession = Search.getFullTextSession(super.session());
    SearchFactory sf = fullTextSession.getSearchFactory();
    QueryBuilder qb = sf.buildQueryBuilder().forEntity(PostPO.class).get();
    org.apache.lucene.search.Query luceneQuery  = qb.phrase().onField("tags").sentence(tag).createQuery();

    FullTextQuery query = fullTextSession.createFullTextQuery(luceneQuery);
    query.setFirstResult(paigng.getFirstResult());
    query.setMaxResults(paigng.getMaxResults());

    Sort sort = new Sort(new SortField("id", SortField.Type.LONG, true));
    query.setSort(sort);

    paigng.setTotalCount(query.getResultSize());

    return query.list();
}
项目:LSChatServer    文件:UserDatabaseImpl.java   
@Transactional
@Override
public Collection<User> search(String query) {
    FullTextEntityManager manager = this.getFullTextEntityManager();

    QueryBuilder builder = manager.getSearchFactory().buildQueryBuilder().forEntity(User.class).get();

    Query luceneQuery = builder.keyword().fuzzy()
            .onFields("username").matching(query)
            .createQuery();

    FullTextQuery q = manager.createFullTextQuery(luceneQuery, User.class);
    q.setProjection(FullTextQuery.THIS, FullTextQuery.SCORE);

    @SuppressWarnings("unchecked")
    List<Object[]> result = q.getResultList();
    List<User> fine = new LinkedList<>();
    result.stream().forEach((i) -> {
        fine.add((User) i[0]);
    });
    return fine;
}
项目:mercurius    文件:ProductDAOImpl.java   
@Override
public List<Product> searchByText(String text) {
    Product productEntity = newInstance();
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);

    QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder()
            .forEntity(productEntity.getClass()).get();
    if (!Strings.isNullOrEmpty(text)) {
        Query query = qb.keyword().onField("name").andField("details").andField("technicalDetails").matching(text)
                .createQuery();

        javax.persistence.Query persistenceQuery = fullTextEntityManager.createFullTextQuery(query,
                productEntity.getClass());
        List<Product> result = persistenceQuery.getResultList();

        if (CollectionUtils.isNotEmpty(result)) {
            for (Product product : result) {
                loadImagesFromQuantities(product.getQuantities());
            }
        }
        return result;
    }
    return Collections.emptyList();
}
项目:omg_mongodb    文件:EShopBean.java   
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;
    }
项目:omg_mongodb    文件:EShopBean.java   
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;
    }
项目:omg_mongodb    文件:EShopBean.java   
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 );
    }
项目:omg_mongodb    文件:EShopBean.java   
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;
    }
项目:sdcct    文件:SdcctCriteriaImpl.java   
@Nullable
@SuppressWarnings({ CompilerWarnings.UNCHECKED })
private Long[] processKeywords(EntityManager entityManager, @Nullable Integer maxResults) {
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
    QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(this.entityImplClass).get();
    BooleanJunction<?> conjunction = queryBuilder.bool();

    PropertyMetadata keywordPropMetadata;

    for (String keywordPropName : this.keywords.keySet()) {
        conjunction = conjunction.must(queryBuilder.keyword()
            .onFields((keywordPropMetadata = this.entityPropMetadatas.get(keywordPropName)).getLowercaseFieldName(),
                keywordPropMetadata.getEdgeNgramFieldName(), keywordPropMetadata.getNgramFieldName(), keywordPropMetadata.getPhoneticFieldName())
            .matching(StringUtils.join(this.keywords.get(keywordPropName), StringUtils.SPACE)).createQuery());
    }

    FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(new InterceptingQuery(conjunction.createQuery()), this.entityImplClass);
    fullTextQuery.setProjection(ProjectionConstants.ID);

    if (maxResults != null) {
        fullTextQuery.setMaxResults(maxResults);
    }

    return ((List<Object[]>) fullTextQuery.getResultList()).stream().map(fullTextResult -> ((Long) fullTextResult[0])).toArray(Long[]::new);
}
项目:cia    文件:SearchIndexerImplITest.java   
@Test
@Transactional(timeout=900)
public void testSearchIndex() throws Exception {

    final QueryBuilder qb = getFullTextEntityManager().getSearchFactory().buildQueryBuilder()
            .forEntity(DocumentContentData.class).get();
    final org.apache.lucene.search.Query luceneQuery = qb.keyword().onFields("content").matching("programmering")
            .createQuery();

    // wrap Lucene query in a javax.persistence.Query
    final javax.persistence.Query jpaQuery = getFullTextEntityManager().createFullTextQuery(luceneQuery,
            DocumentContentData.class);

    // execute search
    final List<DocumentContentData> result = jpaQuery.setMaxResults(500).getResultList();
    assertTrue("expect some result",result.size()> 0);
}
项目:spring-scaffy    文件:SessionHibernateSearchDao.java   
@SuppressWarnings("unchecked")
public <T> List<T> executeSearchQuery(
        RestSearchKey key,
        Class<T> typeClass,
        FullTextSession fullTextEntityManager,
        QueryBuilder queryBuilder,
        Map<String, Query> crtsMap
        ) {

    FullTextQuery fullTextQuery = createFullTextQuery(typeClass,
            fullTextEntityManager, queryBuilder, crtsMap);

    if(key.hasOrders()){

        hibernateSearchBuilder.defineOrder(key, fullTextQuery);
    }

    hibernateSearchBuilder.definePaging(key, fullTextQuery);

    return fullTextQuery.list(); 

}
项目:spring-scaffy    文件:SessionHibernateSearchDao.java   
private <T> FullTextQuery createFullTextQuery(Class<T> typeClass,
        FullTextSession fullTextSession,
        QueryBuilder queryBuilder, Map<String, Query> crtsMap) {
    BooleanJunction<?> booleanJunction = hibernateSearchBuilder.createFinalBooleanJunction(
            queryBuilder, crtsMap);

    FullTextQuery fullTextQuery = null;

    if(booleanJunction == null){
        fullTextQuery =
        fullTextSession.createFullTextQuery(queryBuilder.all().createQuery(), typeClass);
    } else {

        fullTextQuery =
        fullTextSession.createFullTextQuery(
                booleanJunction.createQuery(), typeClass);
    }
    return fullTextQuery;
}
项目:spring-scaffy    文件:JPAHibernateSearchDao.java   
@SuppressWarnings("unchecked")
public <T> List<T> executeSearchQuery(
        RestSearchKey key,
        Class<T> typeClass,
        FullTextEntityManager fullTextEntityManager,
        QueryBuilder queryBuilder,
        Map<String, Query> crtsMap
        ) {

    FullTextQuery fullTextQuery = createFullTextQuery(typeClass,
            fullTextEntityManager, queryBuilder, crtsMap);

    if(key.hasOrders()){

        hibernateSearchBuilder.defineOrder(key, fullTextQuery);
    }

    hibernateSearchBuilder.definePaging(key, fullTextQuery);

    return fullTextQuery.getResultList(); 

}
项目:spring-scaffy    文件:JPAHibernateSearchDao.java   
private <T> FullTextQuery createFullTextQuery(Class<T> typeClass,
        FullTextEntityManager fullTextEntityManager,
        QueryBuilder queryBuilder, Map<String, Query> crtsMap) {
    BooleanJunction<?> booleanJunction = hibernateSearchBuilder.createFinalBooleanJunction(
            queryBuilder, crtsMap);

    FullTextQuery fullTextQuery = null;

    if(booleanJunction == null){
        fullTextQuery =
        fullTextEntityManager.createFullTextQuery(
                queryBuilder.all().createQuery(), typeClass);
    } else {

        fullTextQuery =
        fullTextEntityManager.createFullTextQuery(
                booleanJunction.createQuery(), typeClass);
    }
    return fullTextQuery;
}
项目:javaee-samples    文件:AuditService.java   
public List<AuditFlow> searchAuditFlowPhrase(String textSearch, int fromRownum, int maxRownums) {
    FullTextEntityManager fullTextEntityManager = getFullTextEntityManager(em);

    QueryBuilder qb = fullTextEntityManager.getSearchFactory()
            .buildQueryBuilder()
            .forEntity(AuditFlow.class)
            .get();

    Query luceneQuery = qb.phrase()
            .onField("error")
            .sentence(textSearch)
            .createQuery();

    return fullTextEntityManager.createFullTextQuery(luceneQuery, AuditFlow.class)
            .setFirstResult(fromRownum)
            .setMaxResults(maxRownums)
            .getResultList();
}
项目:omg_mongodb    文件:EShopBean.java   
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;
    }
项目:omg_mongodb    文件:EShopBean.java   
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;
    }
项目:omg_mongodb    文件:EShopBean.java   
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;
    }
项目:teiid    文件:LuceneSearch.java   
private static Query createEqualsQuery(Column column, Object value, boolean and,
            boolean not, BooleanJunction<BooleanJunction> junction, QueryBuilder queryBuilder) {
        String nis = column.getSourceName();
        return createEqualsQuery( nis, value, and, not, junction, queryBuilder);

//      Query queryKey = queryBuilder.keyword()
//              .onField(column.getNameInSource())
//              .matching(value).createQuery();
//
//      if (not) {
//          junction.must(queryKey).not();
//      } else if (and) {
//          junction.must(queryKey);
//      } else if (junction != null) {
//          junction.should(queryKey);
//      }
//      return queryKey;
    }
项目:amanda    文件:ArticleRepositoryImpl.java   
@Override
public Page<SearchResult<Article>> search(String query, Pageable pageable) {
    FullTextEntityManager manager = this.getFullTextEntityManager();

    QueryBuilder builder = manager.getSearchFactory().buildQueryBuilder()
            .forEntity(Article.class).get();

    Query luceneQuery = builder.keyword()
            .onFields("title", "keywords", "abstractContent", "category.name", "category.zhName", "mdBody")
            .matching(query)
            .createQuery();

    FullTextQuery fullTextQuery = manager.createFullTextQuery(luceneQuery, Article.class);
    // fullTextQuery.enableFullTextFilter("published").setParameter( "published", true );

    fullTextQuery.setProjection(FullTextQuery.THIS, FullTextQuery.SCORE);

    long total = fullTextQuery.getResultSize();

    fullTextQuery.setFirstResult(pageable.getOffset())
            .setMaxResults(pageable.getPageSize());

    @SuppressWarnings("unchecked")
    List<Object[]> results = fullTextQuery.getResultList();
    List<SearchResult<Article>> list = new ArrayList<>();
    results.forEach(o -> list.add(
            new SearchResult<>((Article) o[0], (Float)o[1])
    ));

    return new PageImpl<>(list, pageable, total);
}
项目:jdg-lab    文件:IndexedCacheBeerService.java   
public List<Beer> getBeerByIbuBetween(double low, double high){
    SearchManager searchManager = Search.getSearchManager(cache);
    QueryBuilder qb = searchManager.buildQueryBuilderForClass(Beer.class).get();
    Query query = qb.bool()
            .must( qb.range().onField("ibu").above(low).createQuery())
            .must( qb.range().onField("ibu").below(high).createQuery())
            .createQuery();
    List<Beer> result = (List<Beer>)(List)searchManager.getQuery(query, Beer.class).list();
    return result;
}
项目:jdg-lab    文件:IndexedCacheBeerService.java   
public List<Beer> getAllBeers(boolean desc) {
    SearchManager searchManager = Search.getSearchManager(cache);
    QueryBuilder qb = searchManager.buildQueryBuilderForClass(Beer.class).get();
    Query query = qb.all().createQuery();
    CacheQuery cq = searchManager.getQuery(query); //cq is a CacheQuery wrapper of a Lucene query
    if(desc){
        Sort sort = new Sort(new SortField("id", SortField.Type.LONG));
        cq.sort(sort);
    }
    List<Beer> result = (List<Beer>)(List)cq.list();
    return result;
}
项目:jdg-lab    文件:IndexedCacheBeerService.java   
public List<Beer> getBeerByFuzzyMatchDescription(String description){
    SearchManager searchManager = Search.getSearchManager(cache);
    QueryBuilder qb = searchManager.buildQueryBuilderForClass(Beer.class).get();
    Query query = qb.keyword()
            .fuzzy()
            .withPrefixLength(1)
            .onField("description")
            .matching(description)
            .createQuery();
    List<Beer> items = (List<Beer>)(List)searchManager.getQuery(query, Beer.class).list();
    return items;
}
项目:jdg-lab    文件:IndexedCacheBeerService.java   
public List<Beer> getBeerByWildcardDescription(String description){
    SearchManager searchManager = Search.getSearchManager(cache);
    QueryBuilder qb = searchManager.buildQueryBuilderForClass(Beer.class).get();
    Query query = qb.keyword()
            .wildcard()
            .onField("description")
            .matching(description + "*")
            .createQuery();
    List<Beer> items = (List<Beer>)(List)searchManager.getQuery(query, Beer.class).list();
    return items;
}
项目:jdg-lab    文件:CacheBeerService.java   
public List<Beer> getBeerByIbuBetween(double low, double high){

        SearchManager searchManager = Search.getSearchManager(cache);
        QueryBuilder qb = searchManager.buildQueryBuilderForClass(Beer.class).get();
        Query query = qb.bool()
                .must( qb.range().onField("ibu").above(low).createQuery())
                .must( qb.range().onField("ibu").below(high).createQuery())
                .createQuery();
        List<Beer> result = (List<Beer>)(List)searchManager.getQuery(query, Beer.class).list();
        return result;
    }
项目:jdg-lab    文件:CacheBeerService.java   
public List<Beer> getAllBeers(boolean desc) {
    QueryFactory queryFactory = Search.getQueryFactory(cache);
    org.infinispan.query.dsl.QueryBuilder infinispanQueryBuilder =
            queryFactory.from(Beer.class);

    if(desc){
        infinispanQueryBuilder.orderBy("id", SortOrder.DESC);
    }
    org.infinispan.query.dsl.Query infinispanQuery = infinispanQueryBuilder.build();
    return infinispanQuery.list();
}
项目:dwnewsbot    文件:DataManager.java   
public List <NewsItem> searchNewsItems (String query) {
    List <NewsItem> result = new ArrayList <NewsItem> ();
    EntityManager manager = emf.createEntityManager();

    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager);
    try {
        // manager.getTransaction().begin();
        QueryBuilder qb = fullTextEntityManager.getSearchFactory()
            .buildQueryBuilder().forEntity(NewsItem.class).get();
        org.apache.lucene.search.Query luceneQuery = qb
            .keyword()
            .onFields("title", "subtitle", "article")
            .matching(query)
            .createQuery();

        // wrap Lucene query in a javax.persistence.Query
        javax.persistence.Query jpaQuery =
            fullTextEntityManager.createFullTextQuery(luceneQuery, NewsItem.class);

        // execute search
        result = jpaQuery.getResultList();

        for (NewsItem item : result) {
            if (item.getImageUrl().isEmpty()) {
                item.setImageUrl(feeds.get(item.getTopic())[2]);
            }
        }
        // manager.getTransaction().commit();

    } catch (Exception e) {
        e.printStackTrace ();
    } finally {
        manager.close();
    }

    return result;
}
项目:mblog    文件:PostDaoImpl.java   
@Override
@SuppressWarnings("unchecked")
public List<Post> search(Paging paging, String q) throws Exception {
    FullTextSession fullTextSession = Search.getFullTextSession(super.session());
    SearchFactory sf = fullTextSession.getSearchFactory();
    QueryBuilder qb = sf.buildQueryBuilder().forEntity(PostPO.class).get();

    org.apache.lucene.search.Query luceneQuery  = qb.keyword().onFields("title","summary","tags").matching(q).createQuery();

    FullTextQuery query = fullTextSession.createFullTextQuery(luceneQuery);
    query.setFirstResult(paging.getFirstResult());
    query.setMaxResults(paging.getMaxResults());

    StandardAnalyzer standardAnalyzer = new StandardAnalyzer();
    SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<span style='color:red;'>", "</span>");
       QueryScorer queryScorer = new QueryScorer(luceneQuery);
       Highlighter highlighter = new Highlighter(formatter, queryScorer);

    List<PostPO> list = query.list();
    List<Post> rets = new ArrayList<>(list.size());

    for (PostPO po : list) {
        Post m = BeanMapUtils.copy(po, 0);

        // 处理高亮
        String title = highlighter.getBestFragment(standardAnalyzer, "title", m.getTitle());
        String summary = highlighter.getBestFragment(standardAnalyzer, "summary", m.getSummary());

        if (StringUtils.isNotEmpty(title)) {
            m.setTitle(title);
        }
        if (StringUtils.isNotEmpty(summary)) {
            m.setSummary(summary);
        }
        rets.add(m);
    }

    paging.setTotalCount(query.getResultSize());
    return rets;
}
项目:site    文件:PostRepositoryImpl.java   
@Override
@Transactional(readOnly = true)
public List<PostEntity> searchByKeyword(final String keyword) {
    final FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
    final QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(PostEntity.class).get();
    return fullTextEntityManager
            .createFullTextQuery(queryBuilder.simpleQueryString()
            .onFields("content")
            .withAndAsDefaultOperator()
            .matching(keyword)
            .createQuery(), PostEntity.class).getResultList();
}
项目:tweetarchive    文件:TweetRepositoryImpl.java   
@Override
@Transactional(readOnly = true)
public List<TweetEntity> searchByKeyword(final String keywords, final LocalDate from, final LocalDate to) {
    // Must be retrieved inside a transaction to take part of
    final FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);

    // Prepare a search query builder
    final QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(TweetEntity.class).get();

    // This is a boolean junction... I'll add at least a keyword query
    final BooleanJunction<BooleanJunction> outer = queryBuilder.bool();
    outer.must(
            queryBuilder
            .keyword()
            .onFields("content")
            .matching(keywords)
            .createQuery()
    );

    // And then 2 range queries if from and to are not null
    Optional.ofNullable(from)
            .map(f -> f.atStartOfDay(UTC)) // Must be a zoned date time to fit the field
            .map(f -> queryBuilder.range().onField("created_at").above(f).createQuery())
            .ifPresent(q -> outer.must(q));
    Optional.ofNullable(to)
            .map(f -> f.plusDays(1).atStartOfDay(UTC)) // Same here, but a day later
            .map(f -> queryBuilder.range().onField("created_at").below(f).excludeLimit().createQuery()) // which i exclude
            .ifPresent(q -> outer.must(q));
    return fullTextEntityManager.createFullTextQuery(outer.createQuery(), TweetEntity.class).getResultList();
}
项目:owsi-core-parent    文件:SortFieldUtil.java   
public static final Sort getSort(EntityManager entityManager, Class<?> entityClass, SortField... sortFields) {
    if (sortFields == null || sortFields.length == 0) {
        return null;
    } else {
        FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
        QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder()
                .forEntity(entityClass).get();
        SortContext context = queryBuilder.sort();
        SortFieldContext fieldContext = null;
        for (SortField sortField : sortFields) {
            if (fieldContext == null) {
                fieldContext = context.byField(sortField.getField());
            } else {
                fieldContext = fieldContext.andByField(sortField.getField());
            }
            if ( ! sortField.getReverse()) {
                fieldContext.asc();
            } else {
                fieldContext.desc();
            }
        }
        if (fieldContext != null) {
            return fieldContext.createSort();
        } else {
            return null;
        }
    }
}
项目:owsi-core-parent    文件:GenericLocalizedGenericListItemDaoImpl.java   
@Deprecated
protected final <E extends GE> List<E> searchAutocomplete(String searchPattern, Class<E> clazz,
        String[] fields, Locale locale, Integer limit, Integer offset) throws ServiceException {
    GenericLocalizedGenericListItemBinding<E, T> binding = new GenericLocalizedGenericListItemBinding<E, T>();
    String localizedLabelBindingPath = binding.label().getPath();

    QueryBuilder queryBuilder = Search.getFullTextEntityManager(getEntityManager()).getSearchFactory().buildQueryBuilder()
            .forEntity(clazz).get();

    Query luceneQuery = queryBuilder.keyword().onField(binding.enabled().getPath()).matching(true).createQuery();

    String[] actualFields = fields;
    if (actualFields == null || actualFields.length == 0) {
        actualFields = new String[] {
                localizedLabelBindingPath + "." + labelTextAutocompleteFieldName(locale),
                binding.code().getPath()
        };
    }

    return hibernateSearchService.search(clazz,
            actualFields,
            LuceneUtils.getAutocompleteQuery(searchPattern),
            luceneQuery,
            limit, offset,
            new Sort(new SortField(localizedLabelBindingPath + "." + labelTextSortFieldName(locale), SortField.Type.STRING))
    );
}
项目:u-qasar.platform    文件:AbstractService.java   
private <P extends T> Collection<Long> fullTextSearchForIds(Class<P> clazz, String... terms) {
    FullTextEntityManager ftem = Search.getFullTextEntityManager(em);
    QueryBuilder qb = ftem.getSearchFactory().buildQueryBuilder().
            forEntity(clazz).get();
    Query luceneQuery;
    WildcardContext wc = qb.keyword().wildcard();
    TermMatchingContext tmc = setFullTextSearchFields(wc, clazz);
    Set<Long> results = new HashSet<>();
    try {
        for (String term : terms) {
            luceneQuery = tmc.ignoreAnalyzer().ignoreFieldBridge().
                    matching(term.toLowerCase()).createQuery();
            FullTextQuery query = ftem.
                    createFullTextQuery(luceneQuery, clazz);
            query.setProjection("id");
            List<Object[]> idList = query.getResultList();
            for (Object[] id : idList) {
                if (id[0] instanceof Long) {
                    results.add((Long) id[0]);
                }
            }
        }
    } catch (Exception e) {
        // because of lucene stop words
        logger.warn(e.getMessage(), e);
    }
    return results;
}
项目:owsi-core-parent    文件:HibernateSearchLuceneQueryFactoryImpl.java   
@Override
public QueryBuilder getQueryBuilder(Class<?> clazz) {
    QueryBuilder queryBuilder = queryBuilderCache.get(clazz);
    if (queryBuilder == null) {
        queryBuilder = createQueryBuilder(fullTextEntityManager, clazz);
        queryBuilderCache.put(clazz, queryBuilder);
    }
    return queryBuilder;
}
项目:owsi-core-parent    文件:HibernateSearchLuceneQueryFactoryImpl.java   
@Override
public Query all(QueryBuilder builder, Query ... queries) {
    BooleanJunction<?> junction = null;
    for (Query query : queries) {
        if (query != null) {
            junction = junction != null ? junction : builder.bool();
            junction.must(query);
        }
    }
    return junction != null ? junction.createQuery() : null;
}
项目:owsi-core-parent    文件:HibernateSearchLuceneQueryFactoryImpl.java   
@Override
public Query any(QueryBuilder builder, Query ... queries) {
    BooleanJunction<?> junction = null;
    for (Query query : queries) {
        if (query != null) {
            junction = junction != null ? junction : builder.bool();
            junction.should(query);
        }
    }
    return junction != null ? junction.createQuery() : null;
}
项目:teiid    文件:LuceneSearch.java   
private static Query createLikeQuery(Column column, String value,
        BooleanJunction<BooleanJunction> junction, QueryBuilder queryBuilder) {
    Query queryKey = queryBuilder.phrase()
            .onField(column.getNameInSource()).sentence(value)
            .createQuery();
    junction.should(queryKey);
    return queryKey;
}
项目:owsi-core-parent    文件:HibernateSearchLuceneQueryFactoryImpl.java   
@Override
public <P> Query matchIfGiven(QueryBuilder builder, String fieldPath, P value) {
    if (value == null) {
        return null;
    }

    return builder.keyword()
            .onField(fieldPath)
            .matching(value)
            .createQuery();
}