Java Code Examples for org.elasticsearch.index.query.QueryBuilders#rangeQuery()

The following examples show how to use org.elasticsearch.index.query.QueryBuilders#rangeQuery() . 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: BetweenAndQueryParser.java    From elasticsearch-sql with MIT License 6 votes vote down vote up
public AtomicQuery parse(ElasticsearchParser.BetweenAndContext betweenAndContext) {
    if(betweenAndContext.rangeClause()!=null){
        ElasticsearchParser.RangeClauseContext rangeClauseContext=betweenAndContext.rangeClause();
        String field=rangeClauseContext.field.getText();
        RangeQueryBuilder queryBuilder=QueryBuilders.rangeQuery(field);
        String leftValue = StringManager.removeStringSymbol(rangeClauseContext.left.getText());
        String rightValue = StringManager.removeStringSymbol(rangeClauseContext.right.getText());
        if(rangeClauseContext.LPAREN()!=null){
            queryBuilder.gt(leftValue);
        }else{
            queryBuilder.gte(leftValue);
        }
        if(rangeClauseContext.RPAREN()!=null){
            queryBuilder.lt(rightValue);
        }else{
            queryBuilder.lte(rightValue);
        }
        return new AtomicQuery(queryBuilder);
    }
    return parseCondition(betweenAndContext, SqlConditionOperator.BetweenAnd,
            new Object[]{betweenAndContext.left.getText(), betweenAndContext.right.getText()},
            (field, operator, params) -> QueryBuilders.rangeQuery(field).gte(StringManager.removeStringSymbol(params[0].toString())).lte(StringManager.removeStringSymbol(params[1].toString())));
}
 
Example 2
Source File: EsSearchRequest.java    From mall with Apache License 2.0 6 votes vote down vote up
/**
 * 添加价格区间的搜索
 *
 * @param boolQueryBuilder bool 查询
 */
public void addPriceRange(BoolQueryBuilder boolQueryBuilder) {
    if (Objects.isNull(this.priceRange) || !this.priceRange.isValidate()) {
        return;
    }

    RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("price");

    if (!StringUtils.isEmpty(this.priceRange.getMin())) {
        rangeQueryBuilder.from(this.priceRange.getMin().doubleValue());
    }


    if (!StringUtils.isEmpty(this.priceRange.getMax())) {
        rangeQueryBuilder.to(this.priceRange.getMax().doubleValue());
    }
    boolQueryBuilder.must(rangeQueryBuilder);
}
 
Example 3
Source File: ElasticSearchHelper.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
/**
 * This method returns RangeQueryBuilder with boosts if any provided
 *
 * @param name for the field
 * @param rangeOperation: keys and value related to range
 * @param boost for increasing the search parameters priority
 * @return RangeQueryBuilder
 */
private static RangeQueryBuilder createRangeQuery(
    String name, Map<String, Object> rangeOperation, Float boost) {

  RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(name + RAW_APPEND);
  for (Map.Entry<String, Object> it : rangeOperation.entrySet()) {
    switch (it.getKey()) {
      case LTE:
        rangeQueryBuilder.lte(it.getValue());
        break;
      case LT:
        rangeQueryBuilder.lt(it.getValue());
        break;
      case GTE:
        rangeQueryBuilder.gte(it.getValue());
        break;
      case GT:
        rangeQueryBuilder.gt(it.getValue());
        break;
    }
  }
  if (isNotNull(boost)) {
    return rangeQueryBuilder.boost(boost);
  }
  return rangeQueryBuilder;
}
 
Example 4
Source File: EsEventPersistence.java    From logsniffer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected SearchRequestBuilder adaptRequestBuilder(final Client esClient,
		final SearchRequestBuilder requestBuilder) {
	QueryBuilder filter = null;
	if (from != null || to != null) {
		final RangeQueryBuilder occRange = QueryBuilders.rangeQuery(Event.FIELD_TIMESTAMP);
		if (from != null) {
			occRange.gte(from.getTime());
		}
		if (to != null) {
			occRange.lte(to.getTime());
		}
		filter = occRange;
	}
	if (filter != null) {
		requestBuilder.setQuery(filter);
	}
	return requestBuilder;
}
 
Example 5
Source File: ContactsRepositoryImpl.java    From youkefu with Apache License 2.0 5 votes vote down vote up
@Override
public Page<Contacts> 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 6
Source File: ContactsRepositoryImpl.java    From youkefu with Apache License 2.0 5 votes vote down vote up
@Override
public Page<Contacts> 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(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 7
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 8
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 9
Source File: BaseQueryClauseRangeGenerator.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
QueryBuilder mapQueryRule(QueryRule queryRule, EntityType entityType) {
  List<Attribute> attributePath = getAttributePathExpanded(queryRule.getField(), entityType);
  Attribute attr = attributePath.get(attributePath.size() - 1);
  validateNumericalQueryField(attr);

  String fieldName = getQueryFieldName(attributePath);

  Object queryValue = getQueryValue(attr, queryRule.getValue());
  if (queryValue == null) {
    throw new MolgenisQueryException(QUERY_VALUE_CANNOT_BE_NULL_MSG);
  }

  RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(fieldName);
  switch (getOperator()) {
    case GREATER:
      rangeQueryBuilder.gt(queryValue);
      break;
    case GREATER_EQUAL:
      rangeQueryBuilder.gte(queryValue);
      break;
    case LESS:
      rangeQueryBuilder.lt(queryValue);
      break;
    case LESS_EQUAL:
      rangeQueryBuilder.lte(queryValue);
      break;
    default:
      throw new UnexpectedEnumException(getOperator());
  }
  return QueryBuilders.constantScoreQuery(
      nestedQueryBuilder(entityType, attributePath, rangeQueryBuilder));
}
 
Example 10
Source File: QueryHelper.java    From fess with Apache License 2.0 5 votes vote down vote up
protected QueryBuilder convertTermRangeQuery(final QueryContext context, final TermRangeQuery termRangeQuery, final float boost) {
    final String field = getSearchField(context, termRangeQuery.getField());
    if (isSearchField(field)) {
        context.addFieldLog(field, termRangeQuery.toString(field));
        final RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery(field);
        final BytesRef min = termRangeQuery.getLowerTerm();
        if (min != null) {
            if (termRangeQuery.includesLower()) {
                rangeQuery.gte(min.utf8ToString());
            } else {
                rangeQuery.gt(min.utf8ToString());
            }
        }
        final BytesRef max = termRangeQuery.getUpperTerm();
        if (max != null) {
            if (termRangeQuery.includesUpper()) {
                rangeQuery.lte(max.utf8ToString());
            } else {
                rangeQuery.lt(max.utf8ToString());
            }
        }
        rangeQuery.boost(boost);
        return rangeQuery;
    } else {
        final String origQuery = termRangeQuery.toString();
        context.addFieldLog(Constants.DEFAULT_FIELD, origQuery);
        context.addHighlightedQuery(origQuery);
        return buildDefaultQueryBuilder((f, b) -> QueryBuilders.matchPhraseQuery(f, origQuery).boost(b));
    }
}
 
Example 11
Source File: ElasticSearchService.java    From SpringMVC-Project with MIT License 4 votes vote down vote up
/**
     * 查询文章数据
     */
    public List<Article> queryArticle(String keyword, String category) throws IOException {
        BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //数据偏移量,下标从0开始,取前5个
        sourceBuilder.from(0);
        sourceBuilder.size(5);
        //指定返回结果的字段,第一个参数为包含的字段,第二个参数为排除的字段
        sourceBuilder.fetchSource(new String[]{"title"}, new String[]{});

        //分词匹配查询

        //且条件组合,必须满足每一项,计算相关性得分
        boolBuilder.must(QueryBuilders.matchQuery("title", keyword));
//        boolBuilder.must(QueryBuilders.matchQuery("content", keyword));

        //且条件组合,必须满足每一项,不计算相关性得分
//        boolBuilder.filter(QueryBuilders.matchQuery("title", keyword));
//        boolBuilder.filter(QueryBuilders.matchQuery("content", keyword));

        //或条件组合,满足任意一项即可
//        boolBuilder.should(QueryBuilders.matchQuery("title", keyword));
//        boolBuilder.should(QueryBuilders.matchQuery("content", keyword));

        //非条件组合,不满足每一项
//        boolBuilder.mustNot(QueryBuilders.matchQuery("title", keyword));
//        boolBuilder.mustNot(QueryBuilders.matchQuery("content", keyword));

        if (StringUtils.isNotBlank(category)) {
            //不分词匹配查询
            boolBuilder.must(QueryBuilders.matchPhraseQuery("category", category));

            //只匹配分词,如字段值为"Quick Foxes",则只有"Quick"和"Foxes"可以匹配到值,"Quick Foxes"则不行
//            boolBuilder.must(QueryBuilders.termQuery("category", category));
        }

        //范围条件
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime");
        rangeQueryBuilder.gte("2018-12-31T00:00:00Z");
        rangeQueryBuilder.lte("2018-12-31T23:59:59Z");
        boolBuilder.must(rangeQueryBuilder);

        sourceBuilder.query(boolBuilder);
        SearchRequest searchRequest = new SearchRequest();
        //指定索引名称,如果未指定,则会查询所有
        searchRequest.indices(BLOG_INDEX);
        searchRequest.types(ARTICLE_TYPE);
        searchRequest.source(sourceBuilder);

        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        logger.info("查询数据 | {} | {} | {}", keyword, category, JSON.toJSONString(searchResponse));

        List<Article> articleList = Lists.newArrayList();
        SearchHit[] searchHits = searchResponse.getHits().getHits();
        for (SearchHit searchHit : searchHits) {
            Article article = new Article();
            article.setId(Long.valueOf(searchHit.getId()));
            article.setTitle((String) searchHit.getSourceAsMap().get("title"));

            articleList.add(article);
        }

        return articleList;
    }
 
Example 12
Source File: ThreadAnalysisQueryHandler.java    From uavstack with Apache License 2.0 4 votes vote down vote up
private QueryBuilder buildQuery(UAVHttpMessage data) {

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

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

        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();

        // time
        queryBuilder.must(QueryBuilders.rangeQuery("time").gte(startTime).lte(endTime));
        // user
        String user = data.getRequest("user");
        if (user != null) {
            queryBuilder.must(QueryBuilders.termQuery("user", user));
        }
        // pname,已做分词
        String pname = data.getRequest("pname");
        if (pname != null) {
            queryBuilder.must(QueryBuilders.matchQuery("pname", pname));
        }
        // ipport
        String ipport = data.getRequest("ipport");
        if (ipport != null) {
            queryBuilder.must(QueryBuilders.termQuery("ipport", ipport));
        }
        // pid
        String pid = data.getRequest("pid");
        if (pid != null) {
            queryBuilder.must(QueryBuilders.termQuery("pid", pid));
        }
        // appgroup
        String appgroup = data.getRequest("appgroup");
        if (appgroup != null) {
            queryBuilder.must(QueryBuilders.termQuery("appgroup", appgroup));
        }
        // tid
        String tid = data.getRequest("tid");
        if (tid != null) {
            queryBuilder.must(QueryBuilders.termQuery("tid", tid));
        }
        // state
        String state = data.getRequest("state");
        if (state != null) {
            queryBuilder.must(QueryBuilders.termQuery("state", state));
        }
        // timeadd
        String timeadd = data.getRequest("timeadd");
        if (timeadd != null) {
            queryBuilder.must(QueryBuilders.termQuery("timeadd", timeadd));
        }
        final double PRECISION = 0.0000001F;
        // percpu
        double spercpu = DataConvertHelper.toDouble(data.getRequest("spercpu"), -1.0F);
        double epercpu = DataConvertHelper.toDouble(data.getRequest("epercpu"), -1.0F);
        RangeQueryBuilder percpu = QueryBuilders.rangeQuery("percpu");
        if (spercpu + 1.0F > PRECISION) {
            percpu.gte(spercpu);
        }
        if (epercpu + 1.0F > PRECISION) {
            percpu.lte(epercpu);
        }
        if (epercpu < spercpu) {
            data.putResponse("rs", "ERR");
            data.putResponse("msg", "The percpu Range Error: spercpu=" + spercpu + ",epercpu=" + epercpu);
            return null;
        }
        queryBuilder.must(percpu);
        // permem
        double spermem = DataConvertHelper.toDouble(data.getRequest("spermem"), -1.0F);
        double epermem = DataConvertHelper.toDouble(data.getRequest("epermem"), -1.0F);
        RangeQueryBuilder permem = QueryBuilders.rangeQuery("permem");
        if (spermem + 1.0F > PRECISION) {
            permem.gte(spermem);
        }
        if (epermem + 1.0F > PRECISION) {
            permem.lte(epermem);
        }
        if (epermem < spermem) {
            data.putResponse("rs", "ERR");
            data.putResponse("msg", "The permem Range Error: spercpu=" + spermem + ",epercpu=" + epermem);
            return null;
        }
        queryBuilder.must(permem);
        // info,已做分词
        String info = data.getRequest("info");
        if (info != null) {
            queryBuilder.must(QueryBuilders.matchQuery("info", info));
        }

        return queryBuilder;
    }
 
Example 13
Source File: TraceQueryEs7DAO.java    From skywalking with Apache License 2.0 4 votes vote down vote up
@Override
public TraceBrief queryBasicTraces(long startSecondTB,
                                   long endSecondTB,
                                   long minDuration,
                                   long maxDuration,
                                   String endpointName,
                                   String serviceId,
                                   String serviceInstanceId,
                                   String endpointId,
                                   String traceId,
                                   int limit,
                                   int from,
                                   TraceState traceState,
                                   QueryOrder queryOrder) throws IOException {
    SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();

    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    sourceBuilder.query(boolQueryBuilder);
    List<QueryBuilder> mustQueryList = boolQueryBuilder.must();

    if (startSecondTB != 0 && endSecondTB != 0) {
        mustQueryList.add(QueryBuilders.rangeQuery(SegmentRecord.TIME_BUCKET).gte(startSecondTB).lte(endSecondTB));
    }

    if (minDuration != 0 || maxDuration != 0) {
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(SegmentRecord.LATENCY);
        if (minDuration != 0) {
            rangeQueryBuilder.gte(minDuration);
        }
        if (maxDuration != 0) {
            rangeQueryBuilder.lte(maxDuration);
        }
        boolQueryBuilder.must().add(rangeQueryBuilder);
    }
    if (!Strings.isNullOrEmpty(endpointName)) {
        String matchCName = MatchCNameBuilder.INSTANCE.build(SegmentRecord.ENDPOINT_NAME);
        mustQueryList.add(QueryBuilders.matchPhraseQuery(matchCName, endpointName));
    }
    if (StringUtil.isNotEmpty(serviceId)) {
        boolQueryBuilder.must().add(QueryBuilders.termQuery(SegmentRecord.SERVICE_ID, serviceId));
    }
    if (StringUtil.isNotEmpty(serviceInstanceId)) {
        boolQueryBuilder.must().add(QueryBuilders.termQuery(SegmentRecord.SERVICE_INSTANCE_ID, serviceInstanceId));
    }
    if (!Strings.isNullOrEmpty(endpointId)) {
        boolQueryBuilder.must().add(QueryBuilders.termQuery(SegmentRecord.ENDPOINT_ID, endpointId));
    }
    if (!Strings.isNullOrEmpty(traceId)) {
        boolQueryBuilder.must().add(QueryBuilders.termQuery(SegmentRecord.TRACE_ID, traceId));
    }
    switch (traceState) {
        case ERROR:
            mustQueryList.add(QueryBuilders.matchQuery(SegmentRecord.IS_ERROR, BooleanUtils.TRUE));
            break;
        case SUCCESS:
            mustQueryList.add(QueryBuilders.matchQuery(SegmentRecord.IS_ERROR, BooleanUtils.FALSE));
            break;
    }
    switch (queryOrder) {
        case BY_START_TIME:
            sourceBuilder.sort(SegmentRecord.START_TIME, SortOrder.DESC);
            break;
        case BY_DURATION:
            sourceBuilder.sort(SegmentRecord.LATENCY, SortOrder.DESC);
            break;
    }
    sourceBuilder.size(limit);
    sourceBuilder.from(from);

    SearchResponse response = getClient().search(SegmentRecord.INDEX_NAME, sourceBuilder);

    TraceBrief traceBrief = new TraceBrief();
    traceBrief.setTotal((int) response.getHits().getTotalHits().value);

    for (SearchHit searchHit : response.getHits().getHits()) {
        BasicTrace basicTrace = new BasicTrace();

        basicTrace.setSegmentId((String) searchHit.getSourceAsMap().get(SegmentRecord.SEGMENT_ID));
        basicTrace.setStart(String.valueOf(searchHit.getSourceAsMap().get(SegmentRecord.START_TIME)));
        basicTrace.getEndpointNames().add((String) searchHit.getSourceAsMap().get(SegmentRecord.ENDPOINT_NAME));
        basicTrace.setDuration(((Number) searchHit.getSourceAsMap().get(SegmentRecord.LATENCY)).intValue());
        basicTrace.setError(BooleanUtils.valueToBoolean(((Number) searchHit.getSourceAsMap()
                                                                           .get(
                                                                               SegmentRecord.IS_ERROR)).intValue()));
        basicTrace.getTraceIds().add((String) searchHit.getSourceAsMap().get(SegmentRecord.TRACE_ID));
        traceBrief.getTraces().add(basicTrace);
    }

    return traceBrief;
}
 
Example 14
Source File: TraceQueryEsDAO.java    From skywalking with Apache License 2.0 4 votes vote down vote up
@Override
public TraceBrief queryBasicTraces(long startSecondTB,
                                   long endSecondTB,
                                   long minDuration,
                                   long maxDuration,
                                   String endpointName,
                                   String serviceId,
                                   String serviceInstanceId,
                                   String endpointId,
                                   String traceId,
                                   int limit,
                                   int from,
                                   TraceState traceState,
                                   QueryOrder queryOrder) throws IOException {
    SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();

    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    sourceBuilder.query(boolQueryBuilder);
    List<QueryBuilder> mustQueryList = boolQueryBuilder.must();

    if (startSecondTB != 0 && endSecondTB != 0) {
        mustQueryList.add(QueryBuilders.rangeQuery(SegmentRecord.TIME_BUCKET).gte(startSecondTB).lte(endSecondTB));
    }

    if (minDuration != 0 || maxDuration != 0) {
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(SegmentRecord.LATENCY);
        if (minDuration != 0) {
            rangeQueryBuilder.gte(minDuration);
        }
        if (maxDuration != 0) {
            rangeQueryBuilder.lte(maxDuration);
        }
        boolQueryBuilder.must().add(rangeQueryBuilder);
    }
    if (!Strings.isNullOrEmpty(endpointName)) {
        String matchCName = MatchCNameBuilder.INSTANCE.build(SegmentRecord.ENDPOINT_NAME);
        mustQueryList.add(QueryBuilders.matchPhraseQuery(matchCName, endpointName));
    }
    if (StringUtil.isNotEmpty(serviceId)) {
        boolQueryBuilder.must().add(QueryBuilders.termQuery(SegmentRecord.SERVICE_ID, serviceId));
    }
    if (StringUtil.isNotEmpty(serviceInstanceId)) {
        boolQueryBuilder.must().add(QueryBuilders.termQuery(SegmentRecord.SERVICE_INSTANCE_ID, serviceInstanceId));
    }
    if (!Strings.isNullOrEmpty(endpointId)) {
        boolQueryBuilder.must().add(QueryBuilders.termQuery(SegmentRecord.ENDPOINT_ID, endpointId));
    }
    if (!Strings.isNullOrEmpty(traceId)) {
        boolQueryBuilder.must().add(QueryBuilders.termQuery(SegmentRecord.TRACE_ID, traceId));
    }
    switch (traceState) {
        case ERROR:
            mustQueryList.add(QueryBuilders.matchQuery(SegmentRecord.IS_ERROR, BooleanUtils.TRUE));
            break;
        case SUCCESS:
            mustQueryList.add(QueryBuilders.matchQuery(SegmentRecord.IS_ERROR, BooleanUtils.FALSE));
            break;
    }
    switch (queryOrder) {
        case BY_START_TIME:
            sourceBuilder.sort(SegmentRecord.START_TIME, SortOrder.DESC);
            break;
        case BY_DURATION:
            sourceBuilder.sort(SegmentRecord.LATENCY, SortOrder.DESC);
            break;
    }
    sourceBuilder.size(limit);
    sourceBuilder.from(from);

    SearchResponse response = getClient().search(SegmentRecord.INDEX_NAME, sourceBuilder);

    TraceBrief traceBrief = new TraceBrief();
    traceBrief.setTotal((int) response.getHits().totalHits);

    for (SearchHit searchHit : response.getHits().getHits()) {
        BasicTrace basicTrace = new BasicTrace();

        basicTrace.setSegmentId((String) searchHit.getSourceAsMap().get(SegmentRecord.SEGMENT_ID));
        basicTrace.setStart(String.valueOf(searchHit.getSourceAsMap().get(SegmentRecord.START_TIME)));
        basicTrace.getEndpointNames().add((String) searchHit.getSourceAsMap().get(SegmentRecord.ENDPOINT_NAME));
        basicTrace.setDuration(((Number) searchHit.getSourceAsMap().get(SegmentRecord.LATENCY)).intValue());
        basicTrace.setError(BooleanUtils.valueToBoolean(((Number) searchHit.getSourceAsMap()
                                                                           .get(
                                                                               SegmentRecord.IS_ERROR)).intValue()));
        basicTrace.getTraceIds().add((String) searchHit.getSourceAsMap().get(SegmentRecord.TRACE_ID));
        traceBrief.getTraces().add(basicTrace);
    }

    return traceBrief;
}