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

项目: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);
}
项目: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   
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;
}
项目: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;
    }
项目:artifact-listener    文件:ProjectDaoImpl.java   
private FullTextQuery getSearchByNameQuery(String searchTerm) {
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(getEntityManager());

    QueryBuilder projectQueryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder()
            .forEntity(Project.class).get();

    BooleanJunction<?> booleanJunction = projectQueryBuilder.bool();
    if (StringUtils.hasText(searchTerm)) {
        booleanJunction.must(projectQueryBuilder
                .keyword()
                .fuzzy().withPrefixLength(1).withThreshold(0.8F)
                .onField(Binding.project().name().getPath())
                .matching(searchTerm)
                .createQuery());
    } else {
        booleanJunction.must(projectQueryBuilder.all().createQuery());
    }

    return fullTextEntityManager.createFullTextQuery(booleanJunction.createQuery(), Project.class);
}
项目:artifact-listener    文件:UserDaoImpl.java   
private FullTextQuery getSearchQuery(String searchTerm) {
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(getEntityManager());

    QueryBuilder userQueryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder()
            .forEntity(User.class).get();

    BooleanJunction<?> booleanJunction = userQueryBuilder.bool();

    if (StringUtils.hasText(searchTerm)) {
        booleanJunction.must(userQueryBuilder
                .keyword()
                .fuzzy().withPrefixLength(1).withThreshold(0.8F)
                .onField(Binding.user().userName().getPath())
                .andField(Binding.user().fullName().getPath())
                .matching(searchTerm)
                .createQuery());
    } else {
        booleanJunction.must(userQueryBuilder.all().createQuery());
    }

    return fullTextEntityManager.createFullTextQuery(booleanJunction.createQuery(), User.class);
}
项目:artifact-listener    文件:ArtifactDaoImpl.java   
@Override
public List<Artifact> searchAutocompleteWithoutProject(String searchPattern, Integer limit, Integer offset) throws ServiceException {
    String[] searchFields = new String[] {
            Binding.artifact().artifactId().getPath(),
            Binding.artifact().group().groupId().getPath()
    };

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

    Query notDeprecatedQuery = queryBuilder.keyword().onField(Binding.artifact().deprecationStatus().getPath()).matching(ArtifactDeprecationStatus.NORMAL).createQuery();
    Query withoutProjectQuery = queryBuilder.keyword().onField(Binding.artifact().project().getPath()).matching(null).createQuery();

    BooleanJunction<?> booleanJunction = queryBuilder.bool()
            .must(notDeprecatedQuery)
            .must(withoutProjectQuery);

    List<SortField> sortFields = ImmutableList.<SortField>builder()
            .add(new SortField(Binding.artifact().group().getPath() + '.' + ArtifactGroup.GROUP_ID_SORT_FIELD_NAME, SortField.Type.STRING))
            .add(new SortField(Artifact.ARTIFACT_ID_SORT_FIELD_NAME, SortField.Type.STRING))
            .build(); 
    Sort sort = new Sort(sortFields.toArray(new SortField[sortFields.size()]));
    return hibernateSearchService.searchAutocomplete(getObjectClass(), searchFields, searchPattern, booleanJunction.createQuery(), limit, offset, sort);
}
项目:spring-data-snowdrop    文件:LuceneQueryBuilder.java   
public Query all(Collection<Query> subQueries) {
    BooleanJunction<BooleanJunction> bool = queryBuilder.bool();
    for (Query subQuery : subQueries) {
        bool.must(subQuery);
    }
    return bool.createQuery();
}
项目:spring-data-snowdrop    文件:LuceneQueryBuilder.java   
public Query any(Collection<Query> subQueries) {
    BooleanJunction<BooleanJunction> bool = queryBuilder.bool();
    for (Query subQuery : subQueries) {
        bool.should(subQuery);
    }
    return bool.createQuery();
}
项目:spring-data-snowdrop    文件:LuceneQueryBuilder.java   
public Query in(String fieldName, Collection<?> values) {
    BooleanJunction<BooleanJunction> bool = queryBuilder.bool();
    for (Object value : values) {
        bool.should(equal(fieldName, value));
    }
    return bool.createQuery();
}
项目: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    文件:HistoryLogSearchQueryImpl.java   
@Override
public IHistoryLogSearchQuery differencesMandatoryFor(Set<HistoryEventType> mandatoryDifferencesEventTypes) {
    if (!mandatoryDifferencesEventTypes.isEmpty()) {
        List<HistoryEventType> allowedWithoutDifferenceEventTypes = EnumUtils.getEnumList(HistoryEventType.class);
        allowedWithoutDifferenceEventTypes.removeAll(mandatoryDifferencesEventTypes);
        BooleanJunction<?> junction = getDefaultQueryBuilder().bool();
        shouldIfNotNull(
                junction,
                matchOneIfGiven(Bindings.historyLog().eventType(), allowedWithoutDifferenceEventTypes),
                matchIfGiven(AbstractHistoryLog.HAS_DIFFERENCES, true)
        );
        must(junction.createQuery());
    }
    return this;
}
项目: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;
}
项目:owsi-core-parent    文件:HibernateSearchLuceneQueryFactoryImpl.java   
@Override
public <P> Query matchOneIfGiven(QueryBuilder builder, String fieldPath, Collection<? extends P> possibleValues) {
    if (possibleValues == null || possibleValues.isEmpty()) {
        return null;
    }
    BooleanJunction<?> subJunction = builder.bool();
    for (P possibleValue : possibleValues) {
        subJunction.should(builder.keyword()
                .onField(fieldPath)
                .matching(possibleValue)
                .createQuery());
    }
    return subJunction.createQuery();
}
项目:owsi-core-parent    文件:HibernateSearchLuceneQueryFactoryImpl.java   
@Override
public <P> Query matchAllIfGiven(QueryBuilder builder, String fieldPath, Collection<? extends P> values) {
    if (values == null || values.isEmpty()) {
        return null;
    }
    BooleanJunction<?> subJunction = builder.bool();
    for (P possibleValue : values) {
        subJunction.must(builder.keyword()
                .onField(fieldPath)
                .matching(possibleValue)
                .createQuery());
    }
    return subJunction.createQuery();
}
项目:owsi-core-parent    文件:AbstractHibernateSearchSearchQuery.java   
protected void mustIfNotNull(BooleanJunction<?> junction, Query ... queries) {
    for (Query query : queries) {
        if (query != null) {
            junction.must(query);
        }
    }
}
项目:owsi-core-parent    文件:AbstractHibernateSearchSearchQuery.java   
protected void shouldIfNotNull(BooleanJunction<?> junction, Query ... queries) {
    for (Query query : queries) {
        if (query != null) {
            junction.should(query);
        }
    }
}
项目:teiid    文件:LuceneSearch.java   
private static List<Object> performSearch(Condition where, String cacheName, ObjectConnection connection)
        throws TranslatorException {

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

    Class<?> type = connection.getType(cacheName);

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

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

    BooleanJunction<BooleanJunction> junction = queryBuilder.bool();
    boolean createdQueries = buildQueryFromWhereClause(where,
            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;
}
项目:teiid    文件:LuceneSearch.java   
public static boolean visit(In obj, BooleanJunction<BooleanJunction> junction, QueryBuilder queryBuilder) throws TranslatorException {
    LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Parsing IN criteria."); //$NON-NLS-1$

    Expression lhs = obj.getLeftExpression();

    Column mdIDElement = ((ColumnReference) lhs).getMetadataObject();

    List<Expression> rhsList = obj.getRightExpressions();
    boolean createdQuery = false;
    for (Expression expr : rhsList) {

        if (expr instanceof Literal) {
            Literal literal = (Literal) expr;

            // add these as OR queries
            createEqualsQuery(mdIDElement,
                    escapeReservedChars(literal.getValue()), false, false,
                    junction, queryBuilder);
            createdQuery = true;
        } else {
            String msg = ObjectPlugin.Util.getString(
                    "LuceneSearch.Unsupported_expression", //$NON-NLS-1$
                    new Object[] { expr, "IN" }); //$NON-NLS-1$
            throw new TranslatorException(msg);
        }
    }
    return createdQuery;
}
项目:teiid    文件:LuceneSearch.java   
public static boolean visit(Like obj, BooleanJunction<BooleanJunction> junction, QueryBuilder queryBuilder) throws TranslatorException {
    LogManager.logTrace(LogConstants.CTX_CONNECTOR,
            "Parsing LIKE criteria."); //$NON-NLS-1$

    Expression lhs = obj.getLeftExpression();
    Expression rhs = obj.getRightExpression();

    Column c = null;
    Expression literalExp = null;
    if (lhs instanceof ColumnReference) {
        c = ((ColumnReference) lhs).getMetadataObject();
        literalExp = rhs;
    } else {
        c = ((ColumnReference) rhs).getMetadataObject();
        literalExp = lhs;
    }

    String value = null;
    if (literalExp instanceof Literal) {

        value = (String) escapeReservedChars(((Literal) literalExp)
                .getValue());
        createLikeQuery(c, value.replaceAll("%", ""), junction, queryBuilder); // "*" //$NON-NLS-1$ //$NON-NLS-2$
    } else {
        final String msg = ObjectPlugin.Util.getString(
                "LuceneSearch.Unsupported_expression", //$NON-NLS-1$
                new Object[] { literalExp.toString(), "LIKE" }); //$NON-NLS-1$
        throw new TranslatorException(msg);
    }

    return true;
}
项目:teiid    文件:LuceneSearch.java   
private static Query createEqualsQuery(String nameInSource, Object value, boolean and,
        boolean not, BooleanJunction<BooleanJunction> junction, QueryBuilder queryBuilder) {
    Query queryKey = queryBuilder.keyword()
            .onField(nameInSource)
            .matching(value).createQuery();

    if (not) {
        junction.must(queryKey).not();
    } else if (and) {
        junction.must(queryKey);
    } else if (junction != null) {
        junction.should(queryKey);
    }
    return queryKey;
}
项目:teiid    文件:LuceneSearch.java   
private static Query createRangeAboveQuery(Column column, Object value,
        BooleanJunction<BooleanJunction> junction, QueryBuilder queryBuilder) {

    Query queryKey = queryBuilder.range()
            .onField(column.getNameInSource())
            .above(value).excludeLimit().createQuery();
    junction.must(queryKey);
    return queryKey;
}
项目:teiid    文件:LuceneSearch.java   
private static Query createRangeBelowQuery(Column column, Object value,
        BooleanJunction<BooleanJunction> junction, QueryBuilder queryBuilder) {

    Query queryKey = queryBuilder.range()
            .onField(column.getNameInSource())
            .below(value).excludeLimit().createQuery();
    junction.must(queryKey);
    return queryKey;
}
项目: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;
}
项目:lapetiterennes    文件:SearchAdherentRepository.java   
@SuppressWarnings("unchecked")
@Transactional
public Page<Adherent> findAdherentByName(String name, Pageable pageable) {
    final FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager(entityManager);

    // Create native Lucene query using the query DSL
    // alternatively you can write the Lucene query using the Lucene query parser
    // or the Lucene programmatic API. The Hibernate Search DSL is recommended though
    final QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Adherent.class).get();
    final Analyzer analyzer = fullTextEntityManager.getSearchFactory().getAnalyzer("nameAnalyzer");
    final BooleanJunction<?> query = qb.bool();

    tokenized(analyzer, name).forEach(term -> query.must(qb.keyword().wildcard().onField("fullName").matching('*' + term + '*').createQuery()));

    // wrap Lucene query in a javax.persistence.Query
    final FullTextQuery persistenceQuery = fullTextEntityManager.createFullTextQuery(query.createQuery(), Adherent.class);
    persistenceQuery.setFirstResult(pageable.getOffset());
    persistenceQuery.setMaxResults(pageable.getPageSize());

    // Apply a sort if needed
    if (pageable.getSort() != null) {
        final List<SortField> sortFields = new ArrayList<>();
        for (final Order sortOrder : pageable.getSort()) {
            sortFields.add(new SortField(sortOrder.getProperty(), SortField.Type.STRING, !sortOrder.isAscending()));
        }
        persistenceQuery.setSort(new Sort(sortFields.toArray(new SortField[sortFields.size()])));
    }

    // execute search
    final List<Adherent> result = persistenceQuery.getResultList();
    return new PageImpl<>(result, pageable, pageable.getOffset() + result.size() + 1);
}
项目:hapi-fhir    文件:FulltextSearchSvcImpl.java   
private void addTextSearch(QueryBuilder theQueryBuilder, BooleanJunction<?> theBoolean, List<List<? extends IQueryParameterType>> theTerms, String theFieldName, String theFieldNameEdgeNGram, String theFieldNameNGram) {
        if (theTerms == null) {
            return;
        }
        for (List<? extends IQueryParameterType> nextAnd : theTerms) {
            Set<String> terms = new HashSet<String>();
            for (IQueryParameterType nextOr : nextAnd) {
                StringParam nextOrString = (StringParam) nextOr;
                String nextValueTrimmed = StringUtils.defaultString(nextOrString.getValue()).trim();
                if (isNotBlank(nextValueTrimmed)) {
                    terms.add(nextValueTrimmed);
                }
            }
            if (terms.isEmpty() == false) {
                if (terms.size() == 1) {
                    //@formatter:off
                    Query textQuery = theQueryBuilder
                        .phrase()
                        .withSlop(2)
                        .onField(theFieldName).boostedTo(4.0f)
//                      .andField(theFieldNameEdgeNGram).boostedTo(2.0f)
//                      .andField(theFieldNameNGram).boostedTo(1.0f)
                        .sentence(terms.iterator().next().toLowerCase()).createQuery();
                    //@formatter:on

                    theBoolean.must(textQuery);
                } else {
                    String joinedTerms = StringUtils.join(terms, ' ');
                    theBoolean.must(theQueryBuilder.keyword().onField(theFieldName).matching(joinedTerms).createQuery());
                }
            }
        }
    }
项目:hapi-fhir    文件:HapiTerminologySvcR4.java   
private void addDisplayFilterInexact(QueryBuilder qb, BooleanJunction<?> bool, ConceptSetFilterComponent nextFilter) {
    Query textQuery = qb
        .phrase()
        .withSlop(2)
        .onField("myDisplay").boostedTo(4.0f)
        .andField("myDisplayEdgeNGram").boostedTo(2.0f)
        // .andField("myDisplayNGram").boostedTo(1.0f)
        // .andField("myDisplayPhonetic").boostedTo(0.5f)
        .sentence(nextFilter.getValue().toLowerCase()).createQuery();
    bool.must(textQuery);
}
项目:hapi-fhir    文件:HapiTerminologySvcDstu3.java   
private void addDisplayFilterInexact(QueryBuilder qb, BooleanJunction<?> bool, ConceptSetFilterComponent nextFilter) {
    Query textQuery = qb
            .phrase()
            .withSlop(2)
            .onField("myDisplay").boostedTo(4.0f)
            .andField("myDisplayEdgeNGram").boostedTo(2.0f)
            // .andField("myDisplayNGram").boostedTo(1.0f)
            // .andField("myDisplayPhonetic").boostedTo(0.5f)
            .sentence(nextFilter.getValue().toLowerCase()).createQuery();
    bool.must(textQuery);
}
项目:jpasearch    文件:DefaultLuceneQueryBuilder.java   
@Override
public <T> Query build(FullTextEntityManager fullTextEntityManager, ObjectTermSelector<T> termSelector, Class<? extends T> type) {
    QueryBuilder builder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(type).get();

    BooleanJunction<?> context = builder.bool();
    boolean valid = false;
    if (termSelector.isNotEmpty()) {
        boolean hasTerms = false;
        BooleanJunction<?> termContext = builder.bool();
        for (Object selected : termSelector.getSelected()) {
            if ((selected != null) && isNotBlank(selected.toString())) {
                List<String> fields = termSelector.getPaths();
                BooleanJunction<?> valueContext = builder.bool();

                addFuzzyMatch(builder, selected, fields, termSelector.getSearchSimilarity(), valueContext);

                addKeywordMatch(builder, selected, fields, valueContext);

                if (termSelector.isOrMode()) {
                    termContext.should(valueContext.createQuery());
                } else {
                    termContext.must(valueContext.createQuery());
                }
                hasTerms = true;
            }
        }
        if (hasTerms) {
            context.must(termContext.createQuery());
            valid = true;
        }
    }
    return createQuery(builder, context, valid);
}
项目:jpasearch    文件:DefaultLuceneQueryBuilder.java   
private <T> void addFuzzyMatch(QueryBuilder builder, Object value, List<String> fields, Integer editDistance, BooleanJunction<?> valueContext) {
    if (editDistance != null) {
        valueContext.should(builder.keyword().fuzzy() //
                .withEditDistanceUpTo(editDistance) //
                .onFields(fields.toArray(new String[fields.size()])) //
                .matching(value).createQuery());
    }
}
项目:jpasearch    文件:DefaultLuceneQueryBuilder.java   
private Query createQuery(QueryBuilder builder, BooleanJunction<?> context, boolean valid) {
    try {
        if (valid) {
            return context.createQuery();
        } else {
            return builder.all().except(builder.all().createQuery()).createQuery();
        }
    } catch (Exception e) {
        throw propagate(e);
    }
}
项目:MLDS    文件:AffiliateSearchRepository.java   
private Query buildQuery(String q, Member homeMember, StandingState standingState, boolean standingStateNot) {
    QueryBuilder queryBuilder = getSearchFactory().buildQueryBuilder()
            .forEntity(Affiliate.class).get();

    //Odd issue with Camel case text not finding exact matches. Workaround using lowercase.
    Query textQuery = buildWildcardQueryForTokens(queryBuilder, q.toLowerCase());

    if (homeMember == null && standingState == null) {
        return textQuery;
    } else {
        BooleanJunction <MustJunction> building = queryBuilder
                .bool()
                .must(textQuery);

        if (homeMember != null) {
            Query homeMemberQuery = buildQueryMatchingHomeMember(queryBuilder, homeMember);
            building = building.must(homeMemberQuery);
        }
        if (standingState != null) {
            Query standingStateQuery = buildQueryMatchingStandingState(queryBuilder, standingState);
            MustJunction standingStateBuilding = building.must(standingStateQuery);
            if (standingStateNot) {
                // Caught up in .not() returning boolean rather than must...
                building = standingStateBuilding.not();
            } else {
                building = standingStateBuilding;
            }
        }
        return building.createQuery();
    }
}
项目:artifact-listener    文件:ArtifactDaoImpl.java   
private FullTextQuery getSearchByNameQuery(String searchTerm, ArtifactDeprecationStatus deprecation) {
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(getEntityManager());

    QueryBuilder artifactQueryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder()
            .forEntity(Artifact.class).get();

    BooleanJunction<?> booleanJunction = artifactQueryBuilder.bool();

    if (deprecation != null) {
        booleanJunction.must(artifactQueryBuilder
                .keyword()
                .onField(Binding.artifact().deprecationStatus().getPath())
                .matching(deprecation)
                .createQuery());
    }

    if (StringUtils.hasText(searchTerm)) {
        booleanJunction.must(artifactQueryBuilder
                .keyword()
                .fuzzy().withPrefixLength(1).withThreshold(0.8F)
                .onField(Binding.artifact().artifactId().getPath())
                .andField(Binding.artifact().group().groupId().getPath())
                .matching(searchTerm)
                .createQuery());
    } else {
        booleanJunction.must(artifactQueryBuilder.all().createQuery());
    }

    return fullTextEntityManager.createFullTextQuery(booleanJunction.createQuery(), Artifact.class);
}
项目:artifact-listener    文件:ArtifactDaoImpl.java   
private FullTextQuery getSearchRecommendedQuery(String searchTerm) throws ServiceException {
    if (!StringUtils.hasText(searchTerm)) {
        return null;
    }
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(getEntityManager());

    QueryBuilder artifactQueryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder()
            .forEntity(Artifact.class).get();

    BooleanJunction<?> booleanJunction = artifactQueryBuilder.bool();

    booleanJunction.must(artifactQueryBuilder
            .keyword()
            .onField(Binding.artifact().deprecationStatus().getPath())
            .matching(ArtifactDeprecationStatus.NORMAL)
            .createQuery());

    try {
        searchTerm = LuceneUtils.getSimilarityQuery(searchTerm, 2);
        String[] fields = new String[] {
                Binding.artifact().artifactId().getPath(),
                Binding.artifact().group().groupId().getPath()
        };
        Analyzer analyzer = Search.getFullTextEntityManager(getEntityManager()).getSearchFactory().getAnalyzer(Artifact.class);

        MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);
        parser.setDefaultOperator(MultiFieldQueryParser.AND_OPERATOR);

        BooleanQuery booleanQuery = new BooleanQuery();
        booleanQuery.add(parser.parse(searchTerm), BooleanClause.Occur.MUST);

        booleanJunction.must(booleanQuery);
    } catch (ParseException e) {
        throw new ServiceException(String.format("Error parsing request: %1$s", searchTerm), e);
    }

    return fullTextEntityManager.createFullTextQuery(booleanJunction.createQuery(), Artifact.class);
}
项目:owsi-core-parent    文件:ShowcaseTaskDaoImpl.java   
private FullTextQuery getSearchTaskQuery(TaskSearchQueryParameters searchParameters) {
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(getEntityManager());

    QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder()
            .forEntity(QueuedTaskHolder.class).get();

    BooleanJunction<?> booleanJunction = queryBuilder.bool().must(queryBuilder.all().createQuery());

    ShowcaseTaskQueueId queueId = searchParameters.getQueueId();
    if (queueId != null) {
        booleanJunction.must(queryBuilder.keyword()
                    .onField(CoreJpaMoreBindings.queuedTaskHolder().queueId().getPath())
                    .matching(queueId.getUniqueStringId())
                    .createQuery());
    }

    TaskTypeEnum type = searchParameters.getType();
    if (type != null) {
        booleanJunction.must(queryBuilder.keyword()
                    .onField(CoreJpaMoreBindings.queuedTaskHolder().taskType().getPath())
                    .matching(type.getTaskType())
                    .createQuery());
    }

    String name = searchParameters.getName();
    if (StringUtils.hasText(name)) {
        booleanJunction.must(queryBuilder.keyword()
                    .onField(CoreJpaMoreBindings.queuedTaskHolder().name().getPath())
                    .matching(name)
                    .createQuery());
    }

    TaskStatus status = searchParameters.getStatus();
    if (status != null) {
        booleanJunction.must(queryBuilder.keyword()
                    .onField(CoreJpaMoreBindings.queuedTaskHolder().status().getPath())
                    .matching(status)
                    .createQuery());
    }

    TaskResult result = searchParameters.getResult();
    if (result != null) {
        booleanJunction.must(queryBuilder.keyword()
                    .onField(CoreJpaMoreBindings.queuedTaskHolder().result().getPath())
                    .matching(result)
                    .createQuery());
    }

    Date dateMin = searchParameters.getDateMin();
    Date dateMax = searchParameters.getDateMax() != null ? DateUtils.addMilliseconds(DateUtils.addDays(searchParameters.getDateMax(), 1), -1) : null;
    if (dateMin != null && dateMax != null) {
        booleanJunction.must(queryBuilder.range()
                .onField(CoreJpaMoreBindings.queuedTaskHolder().startDate().getPath())
                .from(dateMin)
                .to(dateMax)
                .createQuery());
        booleanJunction.must(queryBuilder.range()
                .onField(CoreJpaMoreBindings.queuedTaskHolder().endDate().getPath())
                .from(dateMin)
                .to(dateMax)
                .createQuery());
    } else if (dateMin != null) {
        booleanJunction.must(queryBuilder.range()
                .onField(CoreJpaMoreBindings.queuedTaskHolder().startDate().getPath())
                .above(dateMin)
                .createQuery());
    } else if (dateMax != null) {
        booleanJunction.must(queryBuilder.range()
                .onField(CoreJpaMoreBindings.queuedTaskHolder().endDate().getPath())
                .below(dateMax)
                .createQuery());
    }

    return fullTextEntityManager.createFullTextQuery(booleanJunction.createQuery(), QueuedTaskHolder.class);
}
项目:spring-scaffy    文件:HibernateSearchBuilder.java   
public BooleanJunction<?> createFinalBooleanJunction(
        QueryBuilder queryBuilder, Map<String, Query> crtsMap) {

    Query[] queries = null;

    if(crtsMap != null)
        queries = crtsMap.values().toArray(new Query[]{});

    BooleanJunction<?> booleanJunction = null;

    if(queries != null){

        booleanJunction = queryBuilder.bool();

        for(Query query : queries)
            booleanJunction = booleanJunction.must(query);
    }

    return booleanJunction;
}
项目:hapi-fhir    文件:HapiTerminologySvcR4.java   
private void addDisplayFilterExact(QueryBuilder qb, BooleanJunction<?> bool, ConceptSetFilterComponent nextFilter) {
    bool.must(qb.phrase().onField("myDisplay").sentence(nextFilter.getValue()).createQuery());
}
项目:hapi-fhir    文件:HapiTerminologySvcDstu3.java   
private void addDisplayFilterExact(QueryBuilder qb, BooleanJunction<?> bool, ConceptSetFilterComponent nextFilter) {
    bool.must(qb.phrase().onField("myDisplay").sentence(nextFilter.getValue()).createQuery());
}
项目:jpasearch    文件:DefaultLuceneQueryBuilder.java   
@Override
public <T> Query build(FullTextEntityManager fullTextEntityManager, StringTermSelector<T> termSelector, Class<? extends T> type) {
    QueryBuilder builder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(type).get();

    BooleanJunction<?> context = builder.bool();
    boolean valid = false;
    if (termSelector.isNotEmpty()) {
        boolean hasTerms = false;
        BooleanJunction<?> termContext = builder.bool();
        for (String selected : termSelector.getSelected()) {
            if (isNotBlank(selected)) {
                String[] values = selected.split(PUNCTUATION);
                for (String value : values) {
                    if (isNotBlank(value) && (value.length() > 2)) {
                        List<String> fields = termSelector.getPaths();
                        BooleanJunction<?> valueContext = builder.bool();

                        addFuzzyMatch(builder, value, fields, termSelector.getSearchSimilarity(), valueContext);

                        addKeywordMatch(builder, value, fields, valueContext);

                        // wildcard search
                        // no #onFields on wildcardContext
                        WildcardContext wildcardContext = builder.keyword().wildcard();
                        TermMatchingContext termMatchingContext = null;
                        for (String field : fields) {
                            if (termMatchingContext != null) {
                                termMatchingContext = termMatchingContext.andField(field);
                            } else {
                                termMatchingContext = wildcardContext.onField(field);
                            }
                        }
                        valueContext.should(termMatchingContext. //
                                matching("*" + value + "*").createQuery());

                        if (termSelector.isOrMode()) {
                            termContext.should(valueContext.createQuery());
                        } else {
                            termContext.must(valueContext.createQuery());
                        }
                        hasTerms = true;
                    }
                }
            }
        }
        if (hasTerms) {
            context.must(termContext.createQuery());
            valid = true;
        }
    }
    return createQuery(builder, context, valid);
}