Java Code Examples for org.elasticsearch.index.query.BoolQueryBuilder#should()

The following examples show how to use org.elasticsearch.index.query.BoolQueryBuilder#should() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: QueryHelper.java    From fess with Apache License 2.0 7 votes vote down vote up
protected QueryBuilder convertBooleanQuery(final QueryContext context, final BooleanQuery booleanQuery, final float boost) {
    final BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
    for (final BooleanClause clause : booleanQuery.clauses()) {
        final QueryBuilder queryBuilder = convertQuery(context, clause.getQuery(), boost);
        if (queryBuilder != null) {
            switch (clause.getOccur()) {
            case MUST:
                boolQuery.must(queryBuilder);
                break;
            case SHOULD:
                boolQuery.should(queryBuilder);
                break;
            case MUST_NOT:
                boolQuery.mustNot(queryBuilder);
                break;
            default:
                break;
            }
        }
    }
    if (boolQuery.hasClauses()) {
        return boolQuery;
    }
    return null;
}
 
Example 2
Source File: EsQueryBuilder.java    From es-service-parent with Apache License 2.0 7 votes vote down vote up
/**
 * 短语查询-支持带空格
 * 
 * @param boolQ
 * @param conditions
 * @param conditionType
 */
private void doMatchPhrase(BoolQueryBuilder boolQ, List<Condition> conditions,
        ConditionType conditionType) {
    String filed;
    QueryBuilder match;
    BoolQueryBuilder subBoolQ;
    for (Condition condition : conditions) {
        // 字段名为空则在_all上搜索
        filed = condition.getFiled();
        filed = StringUtils.isBlank(filed) ? "_all" : filed;
        if (condition.isSpaceSplit()) {
            subBoolQ = QueryBuilders.boolQuery();
            for (String word : KeyWordUtil.processKeyWord(condition.getValue())) {
                subBoolQ.should(QueryBuilders.matchPhraseQuery(filed, word));
            }
            match = subBoolQ;
        } else {
            match = QueryBuilders.matchPhraseQuery(filed, condition.getValue());
        }
        mergeBuilder(boolQ, match, conditionType);
    }
}
 
Example 3
Source File: EsQueryBuilder.java    From es-service-parent with Apache License 2.0 6 votes vote down vote up
/**
 * 前缀查询
 * 
 * @param boolQ
 * @param conditions
 * @param conditionType
 */
private void doPrefix(BoolQueryBuilder boolQ, List<Condition> conditions,
        ConditionType conditionType) {
    QueryBuilder prefix;
    BoolQueryBuilder subBoolQ;
    for (Condition condition : conditions) {
        if (condition.isSpaceSplit()) {
            subBoolQ = QueryBuilders.boolQuery();
            for (String word : KeyWordUtil.processKeyWord(condition.getValue())) {
                subBoolQ.should(QueryBuilders.prefixQuery(condition.getFiled(), word));
            }
            prefix = subBoolQ;
        } else {
            prefix = QueryBuilders.prefixQuery(condition.getFiled(), condition.getValue());
        }
        mergeBuilder(boolQ, prefix, conditionType);
    }
}
 
Example 4
Source File: EsQueryBuilder.java    From es-service-parent with Apache License 2.0 5 votes vote down vote up
/**
 * 合并查询
 * 
 * @param boolQ
 * @param subQ
 * @param conditionType
 */
private BoolQueryBuilder mergeBuilder(BoolQueryBuilder boolQ, QueryBuilder subQ,
        ConditionType conditionType) {
    // 如果子查询为空
    if (subQ instanceof BoolQueryBuilder && !((BoolQueryBuilder) subQ).hasClauses()) {
        return boolQ;
    }
    if (conditionType.equals(conditionType.AND)) {
        boolQ.must(subQ);
    } else if (conditionType.equals(conditionType.OR)) {
        boolQ.should(subQ);
    }
    return boolQ;
}
 
Example 5
Source File: EkmKnowledgeTimesRepositoryImpl.java    From youkefu with Apache License 2.0 5 votes vote down vote up
@Override
public Page<EkmKnowledgeTimes> findByOrgi(String orgi, User user,
		List<String> ekmKnowledgeMasterid, Pageable pageable) {
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	BoolQueryBuilder bq = QueryBuilders.boolQuery();
	if(user.isSuperuser() != true){
		if(ekmKnowledgeMasterid.size() > 0){
			for(String id : ekmKnowledgeMasterid){
				bq.should(termQuery("kbid" ,id)) ;
			}
		}else{
			bq.must(termQuery("kbid" ,UKDataContext.UKEFU_SYSTEM_NO_DAT)) ;
		}
	}
	boolQueryBuilder.must(bq) ;
	boolQueryBuilder.must(QueryBuilders.termQuery("orgi", orgi)) ;
	//过滤掉已过期的知识
	QueryBuilder beginFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("begintime")).should(QueryBuilders.rangeQuery("begintime").to(new Date().getTime())) ;
	QueryBuilder endFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("endtime")).should(QueryBuilders.rangeQuery("endtime").from(new Date().getTime())) ;
	BoolQueryBuilder parentbq = QueryBuilders.boolQuery();
	parentbq.must(beginFilter) ;
	parentbq.must(endFilter) ;
	parentbq.must(QueryBuilders.termQuery("datastatus", false)) ;
	HasParentQueryBuilder hasParentQueryBuilder=QueryBuilders.hasParentQuery("uk_ekm_kb_master",parentbq);
	boolQueryBuilder.must(hasParentQueryBuilder) ;
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(new FieldSortBuilder("viewtimes").unmappedType("long").order(SortOrder.DESC));
	searchQueryBuilder.withPageable(pageable) ;
	Page<EkmKnowledgeTimes> knowledgeTimesList = null ;
	if(elasticsearchTemplate.indexExists(EkmKnowledgeTimes.class)){
		knowledgeTimesList = elasticsearchTemplate.queryForPage(searchQueryBuilder.build() , EkmKnowledgeTimes.class ) ;
    }
	
	return knowledgeTimesList;
}
 
Example 6
Source File: AST_Search.java    From elasticsearch-rest-command with The Unlicense 5 votes vote down vote up
private static QueryBuilder boostWrapMatchAllWithFunctionScore(QueryBuilder qb, String term, String boostFields){
	
	String[] fields = boostFields.split(",");
	BoolQueryBuilder query = QueryBuilders.boolQuery();
	for(String field : fields){
		query.should(QueryBuilders.matchQuery(field, term));
	}
	
	FunctionScoreQueryBuilder fsqb = QueryBuilders.functionScoreQuery(query).add(ScoreFunctionBuilders.weightFactorFunction(10));
	
	return QueryBuilders.boolQuery().should(qb).should(fsqb);
}
 
Example 7
Source File: QuickReplyRepositoryImpl.java    From youkefu with Apache License 2.0 5 votes vote down vote up
@Override
public List<QuickReply> findByOrgiAndCreater(String orgi ,String creater , String q) {

	List<QuickReply> pages  = null ;
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	boolQueryBuilder.must(termQuery("orgi" , orgi)) ;
	
	BoolQueryBuilder quickQueryBuilder = QueryBuilders.boolQuery();
	
	quickQueryBuilder.should(termQuery("type" , UKDataContext.QuickTypeEnum.PUB.toString())) ;
	
	BoolQueryBuilder priQueryBuilder = QueryBuilders.boolQuery();
	
	priQueryBuilder.must(termQuery("type" , UKDataContext.QuickTypeEnum.PRI.toString())) ;
	priQueryBuilder.must(termQuery("creater" , creater)) ;
	
	quickQueryBuilder.should(priQueryBuilder) ;
	
	boolQueryBuilder.must(quickQueryBuilder) ;
	
    if(!StringUtils.isBlank(q)){
    	boolQueryBuilder.must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
    }
    NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(new FieldSortBuilder("createtime").unmappedType("date").order(SortOrder.DESC));
    searchQueryBuilder.withHighlightFields(new HighlightBuilder.Field("title").fragmentSize(200)) ;
    SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(0, 10000)) ;
    if(elasticsearchTemplate.indexExists(QuickReply.class)){
    	pages = elasticsearchTemplate.queryForList(searchQuery, QuickReply.class);
    }
    return pages ; 
}
 
Example 8
Source File: QueryHelper.java    From fess with Apache License 2.0 5 votes vote down vote up
protected QueryBuilder buildDefaultQueryBuilder(final DefaultQueryBuilderFunction builder) {
    final BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
    final FessConfig fessConfig = ComponentUtil.getFessConfig();
    final QueryBuilder titleQuery =
            builder.apply(fessConfig.getIndexFieldTitle(), fessConfig.getQueryBoostTitleAsDecimal().floatValue());
    boolQuery.should(titleQuery);
    final QueryBuilder contentQuery =
            builder.apply(fessConfig.getIndexFieldContent(), fessConfig.getQueryBoostContentAsDecimal().floatValue());
    boolQuery.should(contentQuery);
    getQueryLanguages().ifPresent(
            langs -> stream(langs).of(
                    stream -> stream.forEach(lang -> {
                        final QueryBuilder titleLangQuery =
                                builder.apply(fessConfig.getIndexFieldTitle() + "_" + lang, fessConfig
                                        .getQueryBoostTitleLangAsDecimal().floatValue());
                        boolQuery.should(titleLangQuery);
                        final QueryBuilder contentLangQuery =
                                builder.apply(fessConfig.getIndexFieldContent() + "_" + lang, fessConfig
                                        .getQueryBoostContentLangAsDecimal().floatValue());
                        boolQuery.should(contentLangQuery);
                    })));
    additionalDefaultList.stream().forEach(f -> {
        final QueryBuilder query = builder.apply(f.getFirst(), f.getSecond());
        boolQuery.should(query);
    });
    return boolQuery;
}
 
Example 9
Source File: ElasticsearchSearchVertexQuery.java    From vertexium with Apache License 2.0 5 votes vote down vote up
private QueryBuilder orFilters(List<QueryBuilder> filters) {
    if (filters.size() == 1) {
        return filters.get(0);
    } else {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        for (QueryBuilder filter : filters) {
            boolQuery.should(filter);
        }
        boolQuery.minimumShouldMatch(1);
        return boolQuery;
    }
}
 
Example 10
Source File: SlowOperQueryHandler.java    From uavstack with Apache License 2.0 5 votes vote down vote up
/**
 * 根据协议的报文体内容查询
 * 
 * @param data
 */
@SuppressWarnings("rawtypes")
private void queryByBodyContent(UAVHttpMessage data) {

    String appid = data.getRequest("appid");
    if (appid == null) {
        data.putResponse("rs", "ERR");
        data.putResponse("msg", "appid is required");
        return;
    }

    String[] types = buildTypes(data);
    String content = data.getRequest("content");
    if (types.length == 0) {
        types = typeMap.values().toArray(types);
    }
    BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
    queryBuilder.must(QueryBuilders.matchQuery("appid", appid));
    for (String type : types) {
        for (String field : typeBodyMap.get(type)) {
            queryBuilder.should(QueryBuilders.matchQuery(field, content));
        }
    }
    SortBuilder[] sorts = buildSort(data);

    queryToList(data, queryBuilder, null, sorts);
}
 
Example 11
Source File: EntCustomerRepositoryImpl.java    From youkefu with Apache License 2.0 5 votes vote down vote up
@Override
public Page<EntCustomer> findByCreaterAndSharesAndOrgi(String creater,
		String shares,String orgi, Date begin, Date end, boolean includeDeleteData,
		BoolQueryBuilder boolQueryBuilder , String q, Pageable page) {
	BoolQueryBuilder boolQueryBuilder1 = new BoolQueryBuilder();
	boolQueryBuilder1.should(termQuery("creater" , creater)) ;
	boolQueryBuilder1.should(termQuery("shares" , creater)) ;
	boolQueryBuilder1.should(termQuery("shares" , "all")) ;
	boolQueryBuilder.must(boolQueryBuilder1) ;
	boolQueryBuilder.must(termQuery("orgi" , orgi)) ;
	if(includeDeleteData){
		boolQueryBuilder.must(termQuery("datastatus" , true)) ;
	}else{
		boolQueryBuilder.must(termQuery("datastatus" , false)) ;
	}
	RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("createtime") ;
	if(begin!=null){
		rangeQuery.from(begin.getTime()) ;
	}
	if(end!=null){
		rangeQuery.to(end.getTime()) ;
	}else{
		rangeQuery.to(new Date().getTime()) ;
	}
	if(begin!=null || end!=null){
		boolQueryBuilder.must(rangeQuery) ;
	}
	if(!StringUtils.isBlank(q)){
    	boolQueryBuilder.must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
    }
	return processQuery(boolQueryBuilder , page);
}
 
Example 12
Source File: EntCustomerRepositoryImpl.java    From youkefu with Apache License 2.0 5 votes vote down vote up
@Override
public Page<EntCustomer> findByCreaterAndSharesAndOrgi(String creater,String shares,String orgi, Date begin, Date end, boolean includeDeleteData,String q, Pageable page) {
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	BoolQueryBuilder boolQueryBuilder1 = new BoolQueryBuilder();
	boolQueryBuilder1.should(termQuery("creater" , creater)) ;
	boolQueryBuilder1.should(termQuery("shares" , creater)) ;
	boolQueryBuilder1.should(termQuery("shares" , "all")) ;
	boolQueryBuilder.must(boolQueryBuilder1) ;
	boolQueryBuilder.must(termQuery("orgi" , orgi)) ;
	if(includeDeleteData){
		boolQueryBuilder.must(termQuery("datastatus" , true)) ;
	}else{
		boolQueryBuilder.must(termQuery("datastatus" , false)) ;
	}
	RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("createtime") ;
	if(begin!=null){
		rangeQuery.from(dateFromate.format(begin)) ;
	}
	if(end!=null){
		rangeQuery.to(dateFromate.format(end)) ;
	}else{
		rangeQuery.to(dateFromate.format(new Date())) ;
	}
	if(begin!=null || end!=null){
		boolQueryBuilder.must(rangeQuery) ;
	}
	if(!StringUtils.isBlank(q)){
    	boolQueryBuilder.must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
    }
	return processQuery(boolQueryBuilder , page);
}
 
Example 13
Source File: LessThanTimeOrNeverDownloadedCriteriaAppender.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Method will add this query to {@param query}
 *
 * {
 *   "filter": {
 *     "bool": {
 *       "should": [
 *         {
 *           "bool": {
 *             "must": {
 *               "range": {
 *                 "lastDownloaded": {
 *                   "from": null,
 *                   "to": "now-{@param value}s",
 *                   "include_lower": true,
 *                   "include_upper": true
 *                 }
 *               }
 *             }
 *           }
 *         },
 *         {
 *           "bool": {
 *             "filter": {
 *               "range": {
 *                 "lastBlobUpdated": {
 *                   "from": null,
 *                   "to": "now-{@param value}s",
 *                   "include_lower": true,
 *                   "include_upper": true
 *                 }
 *               }
 *             },
 *             "must_not": {
 *               "exists": {
 *                 "field": "lastDownloaded"
 *               }
 *             }
 *           }
 *         }
 *       ]
 *     }
 *   }
 * }
 */
public void append(final BoolQueryBuilder query, final String value) {
  BoolQueryBuilder neverDownloadDownloadBuilder = QueryBuilders.boolQuery();
  neverDownloadDownloadBuilder.mustNot(existsQuery(field));
  neverDownloadDownloadBuilder.filter(
      rangeQuery(LAST_BLOB_UPDATED_KEY)
          .lte(format(NOW_MINUS_SECONDS, value))
  );

  RangeQueryBuilder lastDownloadRangeBuilder = rangeQuery(field)
      .lte(format(NOW_MINUS_SECONDS, value));

  BoolQueryBuilder lastDownloadShouldBuilder = QueryBuilders.boolQuery();
  lastDownloadShouldBuilder.must(lastDownloadRangeBuilder);

  BoolQueryBuilder filterBuilder = QueryBuilders.boolQuery();
  filterBuilder.should(lastDownloadShouldBuilder);
  filterBuilder.should(neverDownloadDownloadBuilder);

  query.filter(filterBuilder);
}
 
Example 14
Source File: SearchServiceImpl.java    From dk-fitting with Apache License 2.0 4 votes vote down vote up
/**
 *多条件或查询(相当于sql里的or,age=32 or gender=m,也可以单个条件查询age=32.)
 * @param hostIp ES集群的IP
 * @param port ES集群的端口号
 * @param clusterName ES集群名称
 * @param indexName 索引
 * @param typeName 类型
 * @param filed 字段  比如:age,gender
 * @param filedName 查询内容  比如:32,m
 * @param start 记录偏移
 * @param size 记录偏移
 * @return
 * @throws TException
 */
@Override
public Map<String, String> ShouldSearch(String hostIp, int port, String clusterName, String indexName, String typeName, String filed, String filedName, int start, int size) throws TException {
    Client client=null;
    try {
        client = ESUtils.getClient( hostIp, port, clusterName );
    } catch (Exception e) {
        e.printStackTrace();
    }
    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    //String field="age,gender";
    //String Type="32,m";
    int start2 = (Integer)start == null ? 0 : start;
    int size2 = (Integer)size == null ? 10 : size;
    if (filed.contains( "," )||filedName.contains( "," )){
        String[] split = filed.split( "," );
        String[] split1= filedName.split( "," );
        for (int i = 0; i <split.length ; i++) {
            boolQueryBuilder.should( QueryBuilders.termsQuery( split[i], split1[i]) );
        }
    }else {
        boolQueryBuilder.should( QueryBuilders.termsQuery( filed, filedName ) );
    }
    String[] index;
    if (indexName.contains( "," )){
        index = indexName.split( "," );
    }else {
        index = new String[]{indexName};
    }
    String[] type;
    if (typeName.contains( "," )){
        type = typeName.split( "," );
    }else {
        type = new String[]{typeName};
    }
    SearchResponse response = client.prepareSearch( index ).setTypes( type )
            .setQuery( boolQueryBuilder ).setFrom( start2 ).setSize( size2 ).get();
    SearchHit[] hits1 = response.getHits().getHits();
    Map<String,String> map=new LinkedHashMap<>(  );
    long totalHits =0;
    for (SearchHit searchHit:
            hits1) {
        String s = JSON.toJSONString( searchHit.getSource(), SerializerFeature.PrettyFormat );
        totalHits++;
        map.put(  String.valueOf(totalHits ),s );
    }
    long totalHits1 = response.getHits().totalHits;
    map.put( "count",String.valueOf( totalHits1 ) );

    return map;
}
 
Example 15
Source File: InvokeChainQueryHandler.java    From uavstack with Apache License 2.0 4 votes vote down vote up
/**
 * parseSearchCondition
 * 
 * 如果用空格分开多个关键字,则默认为或的关系
 * 
 * 如果某些关键字是以+连接,代表与关系
 * 
 * 注意这里只支持或优先的操作
 * 
 * 举例: <kwd1>+<kwd2> <kwd3> <kwd4>
 * 
 * 则代表的是意思是(kwd1 and kwd2 同时存在)或kwd3存在或kwd4存在
 * 
 * @param queryBuilder
 * @param content
 */
private void parseSearchCondition(BoolQueryBuilder queryBuilder, String content, String field) {

    if (content == null) {
        return;
    }
    
    boolean hasCompandSearch = (content.indexOf("+") > -1) ? true : false;

    if (hasCompandSearch == false) {
        if (content.indexOf("*") == -1) {
            queryBuilder.must(QueryBuilders.matchQuery(field, content));
        }
        else {
            queryBuilder.must(QueryBuilders.wildcardQuery(field+".keyword", content));
        }
    }
    else {

        BoolQueryBuilder orQueryBuilder = QueryBuilders.boolQuery();

        String[] orKwds = content.split(" ");

        for (String orKwd : orKwds) {

            /**
             * 如果没有与关系,就检查是否有*
             */
            if (orKwd.indexOf("+") == -1) {
                if (orKwd.indexOf("*") == -1) {
                    orQueryBuilder.should(QueryBuilders.matchQuery(field, orKwd));
                }
                else {
                    orQueryBuilder.should(QueryBuilders.wildcardQuery(field+".keyword", orKwd));
                }
            }
            else {
                /**
                 * 或关系,检查是否有*
                 */
                String[] andKwds = orKwd.split("\\+");

                BoolQueryBuilder andQueryBuilder = QueryBuilders.boolQuery();

                for (String andKwd : andKwds) {
                    if (andKwd.indexOf("*") == -1) {
                        andQueryBuilder.must(QueryBuilders.matchQuery(field, andKwd));
                    }
                    else {
                        andQueryBuilder.must(QueryBuilders.wildcardQuery(field+".keyword", andKwd));
                    }
                }

                orQueryBuilder.should(andQueryBuilder);
            }

        }

        queryBuilder.must(orQueryBuilder);
    }
}
 
Example 16
Source File: ElasticsearchDataStructure.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private QueryBuilder getQueryBuilder(Resource subject, IRI predicate, Value object, boolean inferred,
		Resource[] contexts) {

	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

	if (subject != null) {
		boolQueryBuilder.must(QueryBuilders.termQuery("subject", subject.stringValue()));
		if (subject instanceof IRI) {
			boolQueryBuilder.must(QueryBuilders.termQuery("subject_IRI", true));
		} else {
			boolQueryBuilder.must(QueryBuilders.termQuery("subject_BNode", true));
		}
	}

	if (predicate != null) {
		boolQueryBuilder.must(QueryBuilders.termQuery("predicate", predicate.stringValue()));
	}

	if (object != null) {
		boolQueryBuilder.must(QueryBuilders.termQuery("object_Hash", object.stringValue().hashCode()));
		if (object instanceof IRI) {
			boolQueryBuilder.must(QueryBuilders.termQuery("object_IRI", true));
		} else if (object instanceof BNode) {
			boolQueryBuilder.must(QueryBuilders.termQuery("object_BNode", true));
		} else {
			boolQueryBuilder.must(
					QueryBuilders.termQuery("object_Datatype", ((Literal) object).getDatatype().stringValue()));
			if (((Literal) object).getLanguage().isPresent()) {
				boolQueryBuilder
						.must(QueryBuilders.termQuery("object_Lang", ((Literal) object).getLanguage().get()));
			}
		}
	}

	if (contexts != null && contexts.length > 0) {

		BoolQueryBuilder contextQueryBuilder = new BoolQueryBuilder();

		for (Resource context : contexts) {

			if (context == null) {

				contextQueryBuilder.should(new BoolQueryBuilder().mustNot(QueryBuilders.existsQuery("context")));

			} else if (context instanceof IRI) {

				contextQueryBuilder.should(
						new BoolQueryBuilder()
								.must(QueryBuilders.termQuery("context", context.stringValue()))
								.must(QueryBuilders.termQuery("context_IRI", true)));

			} else { // BNode
				contextQueryBuilder.should(
						new BoolQueryBuilder()
								.must(QueryBuilders.termQuery("context", context.stringValue()))
								.must(QueryBuilders.termQuery("context_BNode", true)));
			}

		}

		boolQueryBuilder.must(contextQueryBuilder);

	}

	boolQueryBuilder.must(QueryBuilders.termQuery("inferred", inferred));

	return QueryBuilders.constantScoreQuery(boolQueryBuilder);
}
 
Example 17
Source File: ElasticsearchQueryBuilder.java    From presto with Apache License 2.0 4 votes vote down vote up
private static QueryBuilder buildTermQuery(BoolQueryBuilder queryBuilder, ConnectorSession session, String columnName, Domain domain, Type type)
{
    for (Range range : domain.getValues().getRanges().getOrderedRanges()) {
        BoolQueryBuilder rangeQueryBuilder = new BoolQueryBuilder();
        Set<Object> valuesToInclude = new HashSet<>();
        checkState(!range.isAll(), "Invalid range for column: " + columnName);
        if (range.isSingleValue()) {
            valuesToInclude.add(range.getLow().getValue());
        }
        else {
            if (!range.getLow().isLowerUnbounded()) {
                switch (range.getLow().getBound()) {
                    case ABOVE:
                        rangeQueryBuilder.filter(new RangeQueryBuilder(columnName).gt(getValue(session, type, range.getLow().getValue())));
                        break;
                    case EXACTLY:
                        rangeQueryBuilder.filter(new RangeQueryBuilder(columnName).gte(getValue(session, type, range.getLow().getValue())));
                        break;
                    case BELOW:
                        throw new IllegalArgumentException("Low marker should never use BELOW bound");
                    default:
                        throw new AssertionError("Unhandled bound: " + range.getLow().getBound());
                }
            }
            if (!range.getHigh().isUpperUnbounded()) {
                switch (range.getHigh().getBound()) {
                    case EXACTLY:
                        rangeQueryBuilder.filter(new RangeQueryBuilder(columnName).lte(getValue(session, type, range.getHigh().getValue())));
                        break;
                    case BELOW:
                        rangeQueryBuilder.filter(new RangeQueryBuilder(columnName).lt(getValue(session, type, range.getHigh().getValue())));
                        break;
                    case ABOVE:
                        throw new IllegalArgumentException("High marker should never use ABOVE bound");
                    default:
                        throw new AssertionError("Unhandled bound: " + range.getHigh().getBound());
                }
            }
        }

        if (valuesToInclude.size() == 1) {
            rangeQueryBuilder.filter(new TermQueryBuilder(columnName, getValue(session, type, getOnlyElement(valuesToInclude))));
        }
        queryBuilder.should(rangeQueryBuilder);
    }
    return queryBuilder;
}
 
Example 18
Source File: InvokeChainQueryHandler.java    From uavstack with Apache License 2.0 4 votes vote down vote up
/**
 * 从应用维度对调用链进行查询
 * 
 * @param data
 */
@SuppressWarnings("rawtypes")
private void queryByApp(UAVHttpMessage data) {

    long startTime = DataConvertHelper.toLong(data.getRequest("stime"), -1);
    long endTime = DataConvertHelper.toLong(data.getRequest("etime"), -1);

    if (startTime == -1 || endTime == -1 || endTime < startTime) {
        data.putResponse("rs", "ERR");
        data.putResponse("msg", "The Time Range Error: startTime=" + startTime + ",endTime=" + endTime);
        return;
    }

    BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();

    queryBuilder.must(QueryBuilders.rangeQuery("stime").gte(startTime).lte(endTime));

    String ipport = data.getRequest("ipport");

    if (ipport != null) {
        queryBuilder.must(QueryBuilders.matchQuery("ipport", ipport));
    }

    String appid = data.getRequest("appid");
    if (appid != null) {
        queryBuilder.must(QueryBuilders.matchQuery("appid", appid));
    }

    String appuuid = data.getRequest("appuuid");
    if (appuuid != null) {
        queryBuilder.must(QueryBuilders.termQuery("appuuid", appuuid));
    }

    String appgroup = data.getRequest("appgroup");
    if (appgroup != null) {
        queryBuilder.must(QueryBuilders.matchQuery("appgroup", appgroup));
    }

    String eptype = data.getRequest("eptype");
    if (eptype != null) {

        BoolQueryBuilder typeQuery = QueryBuilders.boolQuery();

        String[] types = eptype.split(",");

        for (String type : types) {
            typeQuery.should(QueryBuilders.matchQuery("eptype", type));
        }

        queryBuilder.must(typeQuery);
    }

    String cls = data.getRequest("class");

    if (cls != null) {
        parseSearchCondition(queryBuilder, cls, "class");
    }

    String method = data.getRequest("method");

    if (method != null) {
        parseSearchCondition(queryBuilder, method, "method");
    }

    String url = data.getRequest("url");

    if (url != null) {
        parseSearchCondition(queryBuilder, url, "url");
    }
    
    String state = data.getRequest("state");

    if (state != null) {
        parseSearchCondition(queryBuilder, state, "state");
    }

    SortBuilder[] sorts = buildSort(data);

    this.queryToList(data, queryBuilder, null, sorts);
}
 
Example 19
Source File: CustomSearchRepositoryImpl.java    From klask-io with GNU General Public License v3.0 4 votes vote down vote up
/**
     * construct a SearchRequestBuilder from scratch
     *
     * @param pageable
     * @param nativeSearchQuery
     * @param version
     * @param project
     * @return
     */
    private SearchRequestBuilder constructRequestBuilder(NativeSearchQuery nativeSearchQuery, Pageable pageable, List<String> version, List<String> project, List<String> extension) {
        //SearchRequestBuilder searchRequestBuilder = Queries.constructSearchRequestBuilder(query, pageable, 3, elasticsearchTemplate.getClient());

        BoolQueryBuilder ensembleVersion = QueryBuilders.boolQuery();
        BoolQueryBuilder ensembleProjet = QueryBuilders.boolQuery();
        BoolQueryBuilder ensembleExtension = QueryBuilders.boolQuery();
        BoolQueryBuilder filter = QueryBuilders.boolQuery();

        if (version != null && !version.isEmpty()) {
            ensembleVersion = ensembleVersion.should(QueryBuilders.termsQuery("version.raw", version));
            filter = filter.must(ensembleVersion);
        }
        if (project != null && !project.isEmpty()) {
            ensembleProjet = ensembleProjet.should(QueryBuilders.termsQuery("project.raw", project));
            filter = filter.must(ensembleProjet);
        }
        if (extension != null && !extension.isEmpty()) {
            ensembleExtension = ensembleExtension.should(QueryBuilders.termsQuery("extension.raw", extension));
            filter = filter.must(ensembleExtension);
        }


//        if (StringUtils.isNotEmpty(query)) {
        SearchRequestBuilder searchRequestBuilder = elasticsearchTemplate.getClient().prepareSearch(Constants.INDEX_NAME)
            .setTypes(Constants.TYPE_NAME)
            .setQuery(nativeSearchQuery.getQuery())
            .setHighlighterEncoder("html")//permet d'échapper tous les caractères html pour une sortie correcte sur le frontend
            .setHighlighterFragmentSize(100)
            .setHighlighterNumOfFragments(3)
            .setHighlighterPreTags("<mark>")
            .setHighlighterPostTags("</mark>")
            .addHighlightedField("content")//on souhaite la coloration Highligh sur le contenu et le path à l'affichage
            .addHighlightedField("path")
            .setHighlighterBoundaryChars(new char[]{'\n'})
            .setHighlighterBoundaryMaxScan(200)
            .setHighlighterType("fvh")
            .setTrackScores(true)
            .setPostFilter(filter);

        //add the sort order to searchRequestBuilder
        addPagingAndSortingToSearchRequest(pageable, searchRequestBuilder);


        return searchRequestBuilder;
    }
 
Example 20
Source File: NewLogQueryHandler.java    From uavstack with Apache License 2.0 4 votes vote down vote up
/**
 * parseSearchCondition
 * 
 * 如果用空格分开多个关键字,则默认为或的关系
 * 
 * 如果某些关键字是以+连接,代表与关系
 * 
 * 注意这里只支持或优先的操作
 * 
 * 举例: <kwd1>+<kwd2> <kwd3> <kwd4>
 * 
 * 则代表的是意思是(kwd1 and kwd2 同时存在)或kwd3存在或kwd4存在
 * 
 * @param queryBuilder
 * @param content
 */
private void parseSearchCondition(BoolQueryBuilder queryBuilder, UAVHttpMessage data) {

    String content = data.getRequest("ctn");

    if (content == null) {
        return;
    }
    // 如果查询内容使用""包裹,则使用matchphrase
    if (content.startsWith("\"") && content.endsWith("\"")) {
        // 去除两端的""
        content = content.substring(1, content.length() - 1);
        queryBuilder.must(QueryBuilders.matchPhraseQuery("content", content));
        return;
    }

    boolean hasCompandSearch = (content.indexOf("+") > -1) ? true : false;

    if (hasCompandSearch == false) {
        if (content.indexOf("*") == -1) {
            queryBuilder.must(QueryBuilders.matchQuery("content", content));
        }
        else {
            queryBuilder.must(QueryBuilders.wildcardQuery("content.asstring", content));
        }
    }
    else {

        BoolQueryBuilder orQueryBuilder = QueryBuilders.boolQuery();

        String[] orKwds = content.split(" ");

        for (String orKwd : orKwds) {

            /**
             * 如果没有与关系,就检查是否有*
             */
            if (orKwd.indexOf("+") == -1) {
                if (orKwd.indexOf("*") == -1) {
                    orQueryBuilder.should(QueryBuilders.matchQuery("content", orKwd));
                }
                else {
                    orQueryBuilder.should(QueryBuilders.wildcardQuery("content.asstring", orKwd));
                }
            }
            else {
                /**
                 * 或关系,检查是否有*
                 */
                String[] andKwds = orKwd.split("\\+");

                BoolQueryBuilder andQueryBuilder = QueryBuilders.boolQuery();

                for (String andKwd : andKwds) {
                    if (andKwd.indexOf("*") == -1) {
                        andQueryBuilder.must(QueryBuilders.matchQuery("content", andKwd));
                    }
                    else {
                        andQueryBuilder.must(QueryBuilders.wildcardQuery("content.asstring", andKwd));
                    }
                }

                orQueryBuilder.should(andQueryBuilder);
            }

        }

        queryBuilder.must(orQueryBuilder);
    }
}