當前位置: 首頁>>代碼示例>>Java>>正文


Java SearchRequestBuilder.addAggregation方法代碼示例

本文整理匯總了Java中org.elasticsearch.action.search.SearchRequestBuilder.addAggregation方法的典型用法代碼示例。如果您正苦於以下問題:Java SearchRequestBuilder.addAggregation方法的具體用法?Java SearchRequestBuilder.addAggregation怎麽用?Java SearchRequestBuilder.addAggregation使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.elasticsearch.action.search.SearchRequestBuilder的用法示例。


在下文中一共展示了SearchRequestBuilder.addAggregation方法的8個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: selectMatchAll

import org.elasticsearch.action.search.SearchRequestBuilder; //導入方法依賴的package包/類
public String selectMatchAll(String indexs,String types,String field,String value){
	try {
		if(client==null){
			init();
		}
		SearchRequestBuilder request = client.prepareSearch(indexs.split(",")).setTypes(types.split(","));
		request.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
		request.setQuery(QueryBuilders.matchQuery(field, value));
		request.highlighter(new HighlightBuilder().field(field));
		request.addAggregation(AggregationBuilders.terms("data").field(field+".keyword"));
		request.setExplain(false);
		SearchResponse response = request.get();
		return response.toString();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
}
 
開發者ID:dev-share,項目名稱:css-elasticsearch,代碼行數:20,代碼來源:ElasticsearchTransportFactory.java

示例2: selectTermAll

import org.elasticsearch.action.search.SearchRequestBuilder; //導入方法依賴的package包/類
public String selectTermAll(String indexs,String types,String field,String value){
	try {
		if(client==null){
			init();
		}
		SearchRequestBuilder request = client.prepareSearch(indexs.split(",")).setTypes(types.split(","));
		request.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
		request.setQuery(QueryBuilders.termQuery(field, value));
		request.highlighter(new HighlightBuilder().field(field));
		request.addAggregation(AggregationBuilders.terms("data").field(field+".keyword"));
		request.setExplain(false);
		SearchResponse response = request.get();
		return response.toString();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
}
 
開發者ID:dev-share,項目名稱:css-elasticsearch,代碼行數:20,代碼來源:ElasticsearchExtendTransportFactory.java

示例3: explanFields

import org.elasticsearch.action.search.SearchRequestBuilder; //導入方法依賴的package包/類
private void explanFields(SearchRequestBuilder request, List<Field> fields, AggregationBuilder groupByAgg) throws SqlParseException {
    for (Field field : fields) {
        if (field instanceof MethodField) {

            if (field.getName().equals("script")) {
                request.addStoredField(field.getAlias());
                DefaultQueryAction defaultQueryAction = new DefaultQueryAction(client, select);
                defaultQueryAction.intialize(request);
                List<Field> tempFields = Lists.newArrayList(field);
                defaultQueryAction.setFields(tempFields);
                continue;
            }

            AggregationBuilder makeAgg = aggMaker.makeFieldAgg((MethodField) field, groupByAgg);
            if (groupByAgg != null) {
                groupByAgg.subAggregation(makeAgg);
            } else {
                request.addAggregation(makeAgg);
            }
        } else if (field instanceof Field) {
            request.addStoredField(field.getName());
        } else {
            throw new SqlParseException("it did not support this field method " + field);
        }
    }
}
 
開發者ID:mazhou,項目名稱:es-sql,代碼行數:27,代碼來源:AggregationQueryAction.java

示例4: buildQuery

import org.elasticsearch.action.search.SearchRequestBuilder; //導入方法依賴的package包/類
private SearchRequestBuilder buildQuery(EnumSet<ElasticsearchDocumentType> elementType, boolean includeAggregations) {
    if (QUERY_LOGGER.isTraceEnabled()) {
        QUERY_LOGGER.trace("searching for: " + toString());
    }
    List<QueryBuilder> filters = getFilters(elementType);
    QueryBuilder query = createQuery(getParameters());
    query = scoringStrategy.updateQuery(query);

    QueryBuilder filterBuilder = getFilterBuilder(filters);
    String[] indicesToQuery = getIndexSelectionStrategy().getIndicesToQuery(this, elementType);
    if (QUERY_LOGGER.isTraceEnabled()) {
        QUERY_LOGGER.trace("indicesToQuery: %s", Joiner.on(", ").join(indicesToQuery));
    }
    SearchRequestBuilder searchRequestBuilder = getClient()
            .prepareSearch(indicesToQuery)
            .setTypes(Elasticsearch5SearchIndex.ELEMENT_TYPE)
            .setQuery(QueryBuilders.boolQuery().must(query).filter(filterBuilder))
            .storedFields(
                    Elasticsearch5SearchIndex.ELEMENT_TYPE_FIELD_NAME,
                    Elasticsearch5SearchIndex.EXTENDED_DATA_ELEMENT_ID_FIELD_NAME,
                    Elasticsearch5SearchIndex.EXTENDED_DATA_TABLE_NAME_FIELD_NAME,
                    Elasticsearch5SearchIndex.EXTENDED_DATA_TABLE_ROW_ID_FIELD_NAME
            );
    if (includeAggregations) {
        List<AggregationBuilder> aggs = getElasticsearchAggregations(getAggregations());
        for (AggregationBuilder aggregationBuilder : aggs) {
            searchRequestBuilder.addAggregation(aggregationBuilder);
        }
    }

    applySort(searchRequestBuilder);

    return searchRequestBuilder;
}
 
開發者ID:mware-solutions,項目名稱:memory-graph,代碼行數:35,代碼來源:ElasticsearchSearchQueryBase.java

示例5: addAggregations

import org.elasticsearch.action.search.SearchRequestBuilder; //導入方法依賴的package包/類
private static void addAggregations(
    SearchRequestBuilder searchRequestBuilder,
    List<Map<String, String>> facets) {
  long startTime = System.currentTimeMillis();
  ProjectLogger.log("ElasticSearchUtil addAggregations method started at ==" +startTime, LoggerEnum.PERF_LOG);
  Map<String, String> map = facets.get(0);
  for (Map.Entry<String, String> entry : map.entrySet()) {

    String key = entry.getKey();
    String value = entry.getValue();
    if (JsonKey.DATE_HISTOGRAM.equalsIgnoreCase(value)) {
      searchRequestBuilder
          .addAggregation(AggregationBuilders
              .dateHistogram(key)
              .field(key + RAW_APPEND)
              .dateHistogramInterval(DateHistogramInterval.days(1)));

    } else if (null == value) {
      searchRequestBuilder
          .addAggregation(AggregationBuilders.terms(key).field(key + RAW_APPEND));

    }

  }
  long stopTime = System.currentTimeMillis();
  long elapsedTime = stopTime - startTime;
  ProjectLogger.log("ElasticSearchUtil addAggregations method end at ==" +stopTime+" ,Total time elapsed = "+elapsedTime, LoggerEnum.PERF_LOG);
}
 
開發者ID:project-sunbird,項目名稱:sunbird-utils,代碼行數:29,代碼來源:ElasticSearchUtil.java

示例6: getVertexPropertyCountByValue

import org.elasticsearch.action.search.SearchRequestBuilder; //導入方法依賴的package包/類
@Override
public Map<Object, Long> getVertexPropertyCountByValue(Graph graph, String propertyName, Authorizations authorizations) {
    TermQueryBuilder elementTypeFilterBuilder = new TermQueryBuilder(ELEMENT_TYPE_FIELD_NAME, ElasticsearchDocumentType.VERTEX.getKey());
    BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()
            .must(QueryBuilders.matchAllQuery())
            .filter(elementTypeFilterBuilder);
    SearchRequestBuilder q = getClient().prepareSearch(getIndexNamesAsArray(graph))
            .setQuery(queryBuilder)
            .setSize(0);

    for (String p : getAllMatchingPropertyNames(graph, propertyName, authorizations)) {
        String countAggName = "count-" + p;
        PropertyDefinition propertyDefinition = getPropertyDefinition(graph, p);
        p = p.replace(".", FIELDNAME_DOT_REPLACEMENT);
        if (propertyDefinition != null && propertyDefinition.getTextIndexHints().contains(TextIndexHint.EXACT_MATCH)) {
            p = p + EXACT_MATCH_PROPERTY_NAME_SUFFIX;
        }

        TermsAggregationBuilder countAgg = AggregationBuilders
                .terms(countAggName)
                .field(p)
                .size(500000);
        q = q.addAggregation(countAgg);
    }

    if (ElasticsearchSearchQueryBase.QUERY_LOGGER.isTraceEnabled()) {
        ElasticsearchSearchQueryBase.QUERY_LOGGER.trace("query: %s", q);
    }
    SearchResponse response = getClient().search(q.request()).actionGet();
    Map<Object, Long> results = new HashMap<>();
    for (Aggregation agg : response.getAggregations().asList()) {
        Terms propertyCountResults = (Terms) agg;
        for (Terms.Bucket propertyCountResult : propertyCountResults.getBuckets()) {
            String mapKey = ((String) propertyCountResult.getKey()).toLowerCase();
            Long previousValue = results.get(mapKey);
            if (previousValue == null) {
                previousValue = 0L;
            }
            results.put(mapKey, previousValue + propertyCountResult.getDocCount());
        }
    }
    return results;
}
 
開發者ID:mware-solutions,項目名稱:memory-graph,代碼行數:44,代碼來源:Elasticsearch5SearchIndex.java

示例7: populateBuffer

import org.elasticsearch.action.search.SearchRequestBuilder; //導入方法依賴的package包/類
/** run a query on ES to populate the internal buffer **/
protected void populateBuffer() {

    Date now = new Date();

    LOG.info("{} Populating buffer with nextFetchDate <= {}", logIdprefix,
            now);

    QueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(
            "nextFetchDate").lte(now);

    SearchRequestBuilder srb = client.prepareSearch(indexName)
            .setTypes(docType).setSearchType(SearchType.QUERY_THEN_FETCH)
            .setQuery(rangeQueryBuilder).setFrom(0).setSize(0)
            .setExplain(false);

    TermsBuilder aggregations = AggregationBuilders.terms("partition")
            .field(partitionField).size(maxBucketNum);

    TopHitsBuilder tophits = AggregationBuilders.topHits("docs")
            .setSize(maxURLsPerBucket).setExplain(false);
    // sort within a bucket
    if (StringUtils.isNotBlank(bucketSortField)) {
        FieldSortBuilder sorter = SortBuilders.fieldSort(bucketSortField)
                .order(SortOrder.ASC);
        tophits.addSort(sorter);
    }

    aggregations.subAggregation(tophits);

    // sort between buckets
    if (StringUtils.isNotBlank(totalSortField)) {
        MinBuilder minBuilder = AggregationBuilders.min("top_hit").field(
                totalSortField);
        aggregations.subAggregation(minBuilder);
        aggregations.order(Terms.Order.aggregation("top_hit", true));
    }

    srb.addAggregation(aggregations);

    // https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-preference.html
    // _shards:2,3
    if (shardID != -1) {
        srb.setPreference("_shards:" + shardID);
    }

    // dump query to log
    LOG.debug("{} ES query {}", logIdprefix, srb.toString());

    timeStartESQuery = System.currentTimeMillis();
    isInESQuery.set(true);
    srb.execute(this);
}
 
開發者ID:eorliac,項目名稱:patent-crawler,代碼行數:54,代碼來源:AggregationSpout.java

示例8: buildSearchRequest

import org.elasticsearch.action.search.SearchRequestBuilder; //導入方法依賴的package包/類
private SearchRequestBuilder buildSearchRequest (EsQueryDo esQueryObj) throws  EsException {
    if (Check.NuNStrStrict(esClientFactory.getIndexs(esQueryObj.getIndexName()))) {
        throw new EsException("沒有指定要搜索的索引名稱(indexName)");
    }
    for (ThreadPoolStats.Stats stats : esClientFactory.getClient().threadPool().stats()) {
        logger.info(JSON.toJSONString(stats));
    }
    //加載要搜索索引
    SearchRequestBuilder searchRequestBuilder = esClientFactory.getClient().prepareSearch(esClientFactory.getIndexs(esQueryObj.getIndexName()));
    //由spring從配置加載要搜索的index的類型
    searchRequestBuilder.setTypes(esQueryObj.getTypeName());
    //由spring從配置加載要搜索的類型
    searchRequestBuilder.setSearchType(SearchType.fromId(esQueryObj.getSearchType()));
    //查詢可以為null
    searchRequestBuilder.setQuery(esQueryObj.getQueryBuilder());

    if (!Check.NuNCollection(esQueryObj.getSortBuilders())) {
        for (SortBuilder sortBuilder : esQueryObj.getSortBuilders()) {
            searchRequestBuilder.addSort(sortBuilder);
        }
    }
    if (!Check.NuNCollection(esQueryObj.getAggregationBuilders())) {
        for (AbstractAggregationBuilder aggregationBuilder : esQueryObj.getAggregationBuilders()) {
            searchRequestBuilder.addAggregation(aggregationBuilder);
        }

    }
    //設置高亮域
   if (esQueryObj.isHighLigth()) {
        if (!Check.NuNObject(esQueryObj.highLigthFields())) {
            for (String hlFieldName : esQueryObj.highLigthFields()) {
                searchRequestBuilder.addHighlightedField(hlFieldName).setHighlighterPreTags(esQueryObj.getHighLigthPreTag())
                        .setHighlighterPostTags(esQueryObj.getHighLigthPostTag());
            }
        }
    }
    //分頁
    searchRequestBuilder.setFrom(esQueryObj.getFromIndex()).setSize(esQueryObj.getSize());
    searchRequestBuilder.setExplain(esQueryObj.isExplain());
    return searchRequestBuilder;
}
 
開發者ID:AsuraTeam,項目名稱:asura,代碼行數:42,代碼來源:EsQuery.java


注:本文中的org.elasticsearch.action.search.SearchRequestBuilder.addAggregation方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。