use of org.graylog.plugins.views.search.SearchJob in project graylog2-server by Graylog2.
the class ElasticsearchBackendQueryStringDecoratorsTest method basicSearchJob.
@Nonnull
private SearchJob basicSearchJob(Query query, SearchType searchType) throws InvalidRangeParametersException {
final SearchJob searchJob = mock(SearchJob.class);
final Search search = mock(Search.class);
when(searchJob.getSearch()).thenReturn(search);
when(search.queries()).thenReturn(ImmutableSet.of(query));
when(query.effectiveTimeRange(any())).thenReturn(RelativeRange.create(300));
when(query.searchTypes()).thenReturn(ImmutableSet.of(searchType));
return searchJob;
}
use of org.graylog.plugins.views.search.SearchJob in project graylog2-server by Graylog2.
the class ESMessageList method doExtractResult.
@Override
public SearchType.Result doExtractResult(SearchJob job, Query query, MessageList searchType, org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchResponse result, Aggregations aggregations, ESGeneratedQueryContext queryContext) {
final List<ResultMessageSummary> messages = StreamSupport.stream(result.getHits().spliterator(), false).map(ESMessageList::resultMessageFromSearchHit).map((resultMessage) -> ResultMessageSummary.create(resultMessage.highlightRanges, resultMessage.getMessage().getFields(), resultMessage.getIndex())).collect(Collectors.toList());
final String undecoratedQueryString = query.query().queryString();
final String queryString = this.esQueryDecorators.decorate(undecoratedQueryString, job, query);
final DateTime from = query.effectiveTimeRange(searchType).getFrom();
final DateTime to = query.effectiveTimeRange(searchType).getTo();
final SearchResponse searchResponse = SearchResponse.create(undecoratedQueryString, queryString, Collections.emptySet(), messages, Collections.emptySet(), 0, result.getHits().getTotalHits().value, from, to);
final SearchResponse decoratedSearchResponse = decoratorProcessor.decorateSearchResponse(searchResponse, searchType.decorators());
final MessageList.Result.Builder resultBuilder = MessageList.Result.result(searchType.id()).messages(decoratedSearchResponse.messages()).effectiveTimerange(AbsoluteRange.create(from, to)).totalResults(decoratedSearchResponse.totalResults());
return searchType.name().map(resultBuilder::name).orElse(resultBuilder).build();
}
use of org.graylog.plugins.views.search.SearchJob in project graylog2-server by Graylog2.
the class ElasticsearchBackend method doRun.
@Override
public QueryResult doRun(SearchJob job, Query query, ESGeneratedQueryContext queryContext) {
if (query.searchTypes().isEmpty()) {
return QueryResult.builder().query(query).searchTypes(Collections.emptyMap()).errors(new HashSet<>(queryContext.errors())).build();
}
LOG.debug("Running query {} for job {}", query.id(), job.getId());
final HashMap<String, SearchType.Result> resultsMap = Maps.newHashMap();
final Set<String> affectedIndices = indexLookup.indexNamesForStreamsInTimeRange(query.usedStreamIds(), query.timerange());
final Map<String, SearchSourceBuilder> searchTypeQueries = queryContext.searchTypeQueries();
final List<String> searchTypeIds = new ArrayList<>(searchTypeQueries.keySet());
final List<SearchRequest> searches = searchTypeIds.stream().map(searchTypeId -> {
final Set<String> affectedIndicesForSearchType = query.searchTypes().stream().filter(s -> s.id().equalsIgnoreCase(searchTypeId)).findFirst().flatMap(searchType -> {
if (searchType.effectiveStreams().isEmpty() && !query.globalOverride().flatMap(GlobalOverride::timerange).isPresent() && !searchType.timerange().isPresent()) {
return Optional.empty();
}
final Set<String> usedStreamIds = searchType.effectiveStreams().isEmpty() ? query.usedStreamIds() : searchType.effectiveStreams();
return Optional.of(indexLookup.indexNamesForStreamsInTimeRange(usedStreamIds, query.effectiveTimeRange(searchType)));
}).orElse(affectedIndices);
Set<String> indices = affectedIndicesForSearchType.isEmpty() ? Collections.singleton("") : affectedIndicesForSearchType;
return new SearchRequest().source(searchTypeQueries.get(searchTypeId)).indices(indices.toArray(new String[0])).indicesOptions(IndicesOptions.fromOptions(false, false, true, false));
}).collect(Collectors.toList());
final List<MultiSearchResponse.Item> results = client.msearch(searches, "Unable to perform search query: ");
for (SearchType searchType : query.searchTypes()) {
final String searchTypeId = searchType.id();
final Provider<ESSearchTypeHandler<? extends SearchType>> handlerProvider = elasticsearchSearchTypeHandlers.get(searchType.type());
if (handlerProvider == null) {
LOG.error("Unknown search type '{}', cannot convert query result.", searchType.type());
// no need to add another error here, as the query generation code will have added the error about the missing handler already
continue;
}
if (isSearchTypeWithError(queryContext, searchTypeId)) {
LOG.error("Failed search type '{}', cannot convert query result, skipping.", searchType.type());
// no need to add another error here, as the query generation code will have added the error about the missing handler already
continue;
}
// we create a new instance because some search type handlers might need to track information between generating the query and
// processing its result, such as aggregations, which depend on the name and type
final ESSearchTypeHandler<? extends SearchType> handler = handlerProvider.get();
final int searchTypeIndex = searchTypeIds.indexOf(searchTypeId);
final MultiSearchResponse.Item multiSearchResponse = results.get(searchTypeIndex);
if (multiSearchResponse.isFailure()) {
ElasticsearchException e = new ElasticsearchException("Search type returned error: ", multiSearchResponse.getFailure());
queryContext.addError(SearchTypeErrorParser.parse(query, searchTypeId, e));
} else if (checkForFailedShards(multiSearchResponse).isPresent()) {
ElasticsearchException e = checkForFailedShards(multiSearchResponse).get();
queryContext.addError(SearchTypeErrorParser.parse(query, searchTypeId, e));
} else {
final SearchType.Result searchTypeResult = handler.extractResult(job, query, searchType, multiSearchResponse.getResponse(), queryContext);
if (searchTypeResult != null) {
resultsMap.put(searchTypeId, searchTypeResult);
}
}
}
LOG.debug("Query {} ran for job {}", query.id(), job.getId());
return QueryResult.builder().query(query).searchTypes(resultsMap).errors(new HashSet<>(queryContext.errors())).build();
}
use of org.graylog.plugins.views.search.SearchJob in project graylog2-server by Graylog2.
the class ElasticsearchBackendTest method generatesSearchForEmptySearchTypes.
@Test
public void generatesSearchForEmptySearchTypes() throws Exception {
final Query query = Query.builder().id("query1").query(ElasticsearchQueryString.of("")).timerange(RelativeRange.create(300)).build();
final Search search = Search.builder().queries(ImmutableSet.of(query)).build();
final SearchJob job = new SearchJob("deadbeef", search, "admin");
backend.generate(job, query, new SearchConfig(Period.ZERO));
}
use of org.graylog.plugins.views.search.SearchJob in project graylog2-server by Graylog2.
the class ElasticsearchBackendUsingCorrectIndicesTest method queryUsesOnlyIndicesIncludingTimerangeAndStream.
@Test
public void queryUsesOnlyIndicesIncludingTimerangeAndStream() throws Exception {
final String streamId = "streamId";
final Query query = dummyQuery(RelativeRange.create(600)).toBuilder().filter(StreamFilter.ofId(streamId)).build();
final Search search = dummySearch(query);
final SearchJob job = new SearchJob("job1", search, "admin");
final ESGeneratedQueryContext context = backend.generate(job, query, new SearchConfig(Period.ZERO));
when(indexLookup.indexNamesForStreamsInTimeRange(ImmutableSet.of("streamId"), RelativeRange.create(600))).thenReturn(ImmutableSet.of("index1", "index2"));
backend.doRun(job, query, context);
verify(jestClient, times(1)).execute(clientRequestCaptor.capture(), any());
final MultiSearch clientRequest = clientRequestCaptor.getValue();
assertThat(clientRequest).isNotNull();
assertThat(indicesOf(clientRequest).get(0)).isEqualTo("index1,index2");
}
Aggregations