org.graylog2.search.SearchQuery Maven / Gradle / Ivy
/**
* This file is part of Graylog.
*
* Graylog is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Graylog is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Graylog. If not, see .
*/
package org.graylog2.search;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import org.mongojack.DBQuery;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
public class SearchQuery {
private final Multimap queryMap;
private final Set disallowedKeys;
private final String queryString;
public SearchQuery(String queryString) {
this(queryString, HashMultimap.create(), Collections.emptySet());
}
public SearchQuery(String queryString, Multimap queryMap, Set disallowedKeys) {
this.queryString = queryString;
this.queryMap = queryMap;
this.disallowedKeys = disallowedKeys;
}
public Multimap getQueryMap() {
return queryMap;
}
public DBQuery.Query toDBQuery() {
if (queryMap.isEmpty()) {
return DBQuery.empty();
}
final List dbQueries = new ArrayList<>();
for (Map.Entry> entry : queryMap.asMap().entrySet()) {
final List queries = new ArrayList<>();
final List include = selectValues(entry.getValue(), value -> !value.isNegate());
final List exclude = selectValues(entry.getValue(), SearchQueryParser.FieldValue::isNegate);
if (!include.isEmpty()) {
queries.add(DBQuery.or(toQuery(entry.getKey(), include)));
}
if (!exclude.isEmpty()) {
queries.add(DBQuery.nor(toQuery(entry.getKey(), exclude)));
}
dbQueries.add(DBQuery.and(queries.toArray(new DBQuery.Query[0])));
}
return DBQuery.and(dbQueries.toArray(new DBQuery.Query[0]));
}
private DBQuery.Query[] toQuery(String field, List values) {
return values.stream()
.map(value -> value.getOperator().buildQuery(field, value.getValue()))
.collect(Collectors.toList())
.toArray(new DBQuery.Query[0]);
}
private List selectValues(Collection values,
Function callback) {
return values.stream()
.filter(callback::apply)
.collect(Collectors.toList());
}
public String getQueryString() {
return queryString;
}
public Set getDisallowedKeys() {
return disallowedKeys;
}
public boolean hasDisallowedKeys() {
return !disallowedKeys.isEmpty();
}
}