use of org.elasticsearch.action.search.SearchRequest in project elasticsearch by elastic.
the class ParentTaskAssigningClientTests method testSetsParentId.
public void testSetsParentId() {
TaskId[] parentTaskId = new TaskId[] { new TaskId(randomAsciiOfLength(3), randomLong()) };
// This mock will do nothing but verify that parentTaskId is set on all requests sent to it.
NoOpClient mock = new NoOpClient(getTestName()) {
@Override
protected <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void doExecute(Action<Request, Response, RequestBuilder> action, Request request, ActionListener<Response> listener) {
assertEquals(parentTaskId[0], request.getParentTask());
super.doExecute(action, request, listener);
}
};
try (ParentTaskAssigningClient client = new ParentTaskAssigningClient(mock, parentTaskId[0])) {
// All of these should have the parentTaskId set
client.bulk(new BulkRequest());
client.search(new SearchRequest());
client.clearScroll(new ClearScrollRequest());
// Now lets verify that unwrapped calls don't have the parentTaskId set
parentTaskId[0] = TaskId.EMPTY_TASK_ID;
client.unwrap().bulk(new BulkRequest());
client.unwrap().search(new SearchRequest());
client.unwrap().clearScroll(new ClearScrollRequest());
}
}
use of org.elasticsearch.action.search.SearchRequest in project graylog2-server by Graylog2.
the class Indices method indexRangeStatsOfIndex.
/**
* Calculate min and max message timestamps in the given index.
*
* @param index Name of the index to query.
* @return the timestamp stats in the given index, or {@code null} if they couldn't be calculated.
* @see org.elasticsearch.search.aggregations.metrics.stats.Stats
*/
public IndexRangeStats indexRangeStatsOfIndex(String index) {
final FilterAggregationBuilder builder = AggregationBuilders.filter("agg").filter(QueryBuilders.existsQuery("timestamp")).subAggregation(AggregationBuilders.min("ts_min").field("timestamp")).subAggregation(AggregationBuilders.max("ts_max").field("timestamp")).subAggregation(AggregationBuilders.terms("streams").field("streams"));
final SearchRequestBuilder srb = c.prepareSearch().setIndices(index).setSearchType(SearchType.QUERY_THEN_FETCH).setSize(0).addAggregation(builder);
final SearchResponse response;
try {
final SearchRequest request = srb.request();
if (LOG.isDebugEnabled()) {
LOG.debug("Index range query: _search/{}: {}", index, XContentHelper.convertToJson(request.source(), false));
}
response = c.search(request).actionGet();
} catch (IndexClosedException e) {
throw e;
} catch (org.elasticsearch.index.IndexNotFoundException e) {
LOG.error("Error while calculating timestamp stats in index <" + index + ">", e);
throw e;
} catch (ElasticsearchException e) {
LOG.error("Error while calculating timestamp stats in index <" + index + ">", e);
throw new org.elasticsearch.index.IndexNotFoundException("Index " + index + " not found", e);
} catch (IOException e) {
// the index range aggregation query on DEBUG (via XContentHelper)
throw new RuntimeException(e);
}
final Filter f = response.getAggregations().get("agg");
if (f.getDocCount() == 0L) {
LOG.debug("No documents with attribute \"timestamp\" found in index <{}>", index);
return IndexRangeStats.EMPTY;
}
final Min minAgg = f.getAggregations().get("ts_min");
final DateTime min = new DateTime((long) minAgg.getValue(), DateTimeZone.UTC);
final Max maxAgg = f.getAggregations().get("ts_max");
final DateTime max = new DateTime((long) maxAgg.getValue(), DateTimeZone.UTC);
// make sure we return an empty list, so we can differentiate between old indices that don't have this information
// and newer ones that simply have no streams.
ImmutableList.Builder<String> streamIds = ImmutableList.builder();
final Terms streams = f.getAggregations().get("streams");
if (!streams.getBuckets().isEmpty()) {
streamIds.addAll(streams.getBuckets().stream().map(Terms.Bucket::getKeyAsString).collect(toSet()));
}
return IndexRangeStats.create(min, max, streamIds.build());
}
use of org.elasticsearch.action.search.SearchRequest in project graylog2-server by Graylog2.
the class Searches method fieldHistogram.
public HistogramResult fieldHistogram(String query, String field, DateHistogramInterval interval, String filter, TimeRange range, boolean includeCardinality) throws FieldTypeException {
final DateHistogramBuilder dateHistogramBuilder = AggregationBuilders.dateHistogram(AGG_HISTOGRAM).field("timestamp").subAggregation(AggregationBuilders.stats(AGG_STATS).field(field)).interval(interval.toESInterval());
if (includeCardinality) {
dateHistogramBuilder.subAggregation(AggregationBuilders.cardinality(AGG_CARDINALITY).field(field));
}
FilterAggregationBuilder builder = AggregationBuilders.filter(AGG_FILTER).subAggregation(dateHistogramBuilder).filter(standardAggregationFilters(range, filter));
QueryStringQueryBuilder qs = queryStringQuery(query);
qs.allowLeadingWildcard(configuration.isAllowLeadingWildcardSearches());
SearchRequestBuilder srb = c.prepareSearch();
final Set<String> affectedIndices = determineAffectedIndices(range, filter);
srb.setIndices(affectedIndices.toArray(new String[affectedIndices.size()]));
srb.setQuery(qs);
srb.addAggregation(builder);
SearchResponse r;
final SearchRequest request = srb.request();
try {
r = c.search(request).actionGet();
} catch (org.elasticsearch.action.search.SearchPhaseExecutionException e) {
throw new FieldTypeException(e);
}
checkForFailedShards(r);
recordEsMetrics(r, range);
final Filter f = r.getAggregations().get(AGG_FILTER);
return new FieldHistogramResult(f.getAggregations().get(AGG_HISTOGRAM), query, request.source(), interval, r.getTook());
}
use of org.elasticsearch.action.search.SearchRequest in project graylog2-server by Graylog2.
the class Searches method termsStats.
public TermsStatsResult termsStats(String keyField, String valueField, TermsStatsOrder order, int size, String query, String filter, TimeRange range) {
if (size == 0) {
size = 50;
}
SearchRequestBuilder srb;
if (filter == null) {
srb = standardSearchRequest(query, determineAffectedIndices(range, filter), range);
} else {
srb = filteredSearchRequest(query, filter, determineAffectedIndices(range, filter), range);
}
Terms.Order termsOrder;
switch(order) {
case COUNT:
termsOrder = Terms.Order.count(true);
break;
case REVERSE_COUNT:
termsOrder = Terms.Order.count(false);
break;
case TERM:
termsOrder = Terms.Order.term(true);
break;
case REVERSE_TERM:
termsOrder = Terms.Order.term(false);
break;
case MIN:
termsOrder = Terms.Order.aggregation(AGG_STATS, "min", true);
break;
case REVERSE_MIN:
termsOrder = Terms.Order.aggregation(AGG_STATS, "min", false);
break;
case MAX:
termsOrder = Terms.Order.aggregation(AGG_STATS, "max", true);
break;
case REVERSE_MAX:
termsOrder = Terms.Order.aggregation(AGG_STATS, "max", false);
break;
case MEAN:
termsOrder = Terms.Order.aggregation(AGG_STATS, "avg", true);
break;
case REVERSE_MEAN:
termsOrder = Terms.Order.aggregation(AGG_STATS, "avg", false);
break;
case TOTAL:
termsOrder = Terms.Order.aggregation(AGG_STATS, "sum", true);
break;
case REVERSE_TOTAL:
termsOrder = Terms.Order.aggregation(AGG_STATS, "sum", false);
break;
default:
termsOrder = Terms.Order.count(true);
}
FilterAggregationBuilder builder = AggregationBuilders.filter(AGG_FILTER).subAggregation(AggregationBuilders.terms(AGG_TERMS_STATS).field(keyField).subAggregation(AggregationBuilders.stats(AGG_STATS).field(valueField)).order(termsOrder).size(size)).filter(standardAggregationFilters(range, filter));
srb.addAggregation(builder);
final SearchRequest request = srb.request();
SearchResponse r = c.search(request).actionGet();
recordEsMetrics(r, range);
final Filter f = r.getAggregations().get(AGG_FILTER);
return new TermsStatsResult(f.getAggregations().get(AGG_TERMS_STATS), query, request.source(), r.getTook());
}
use of org.elasticsearch.action.search.SearchRequest in project graylog2-server by Graylog2.
the class Searches method fieldStats.
public FieldStatsResult fieldStats(String field, String query, String filter, TimeRange range, boolean includeCardinality, boolean includeStats, boolean includeCount) throws FieldTypeException {
SearchRequestBuilder srb;
final Set<String> indices = indicesContainingField(determineAffectedIndices(range, filter), field);
if (filter == null) {
srb = standardSearchRequest(query, indices, range);
} else {
srb = filteredSearchRequest(query, filter, indices, range);
}
FilterAggregationBuilder builder = AggregationBuilders.filter(AGG_FILTER).filter(standardAggregationFilters(range, filter));
if (includeCount) {
builder.subAggregation(AggregationBuilders.count(AGG_VALUE_COUNT).field(field));
}
if (includeStats) {
builder.subAggregation(AggregationBuilders.extendedStats(AGG_EXTENDED_STATS).field(field));
}
if (includeCardinality) {
builder.subAggregation(AggregationBuilders.cardinality(AGG_CARDINALITY).field(field));
}
srb.addAggregation(builder);
SearchResponse r;
final SearchRequest request;
try {
request = srb.request();
r = c.search(request).actionGet();
} catch (org.elasticsearch.action.search.SearchPhaseExecutionException e) {
throw new FieldTypeException(e);
}
checkForFailedShards(r);
recordEsMetrics(r, range);
final Filter f = r.getAggregations().get(AGG_FILTER);
return new FieldStatsResult(f.getAggregations().get(AGG_VALUE_COUNT), f.getAggregations().get(AGG_EXTENDED_STATS), f.getAggregations().get(AGG_CARDINALITY), r.getHits(), query, request.source(), r.getTook());
}
Aggregations