Search in sources :

Example 81 with FilterExpression

use of com.yahoo.elide.core.filter.expression.FilterExpression in project elide by yahoo.

the class AsyncAPICancelRunnable method cancelAsyncAPI.

/**
 * This method cancels queries based on threshold.
 * @param type AsyncAPI Type Implementation.
 */
protected <T extends AsyncAPI> void cancelAsyncAPI(Class<T> type) {
    try {
        TransactionRegistry transactionRegistry = elide.getTransactionRegistry();
        Map<UUID, DataStoreTransaction> runningTransactionMap = transactionRegistry.getRunningTransactions();
        // Running transaction UUIDs
        Set<UUID> runningTransactionUUIDs = runningTransactionMap.keySet();
        // Construct filter expression
        PathElement statusPathElement = new PathElement(type, QueryStatus.class, "status");
        FilterExpression fltStatusExpression = new InPredicate(statusPathElement, QueryStatus.CANCELLED, QueryStatus.PROCESSING, QueryStatus.QUEUED);
        Iterable<T> asyncAPIIterable = asyncAPIDao.loadAsyncAPIByFilter(fltStatusExpression, type);
        // Active AsyncAPI UUIDs
        Set<UUID> asyncTransactionUUIDs = StreamSupport.stream(asyncAPIIterable.spliterator(), false).filter(query -> query.getStatus() == QueryStatus.CANCELLED || TimeUnit.SECONDS.convert(Math.abs(new Date(System.currentTimeMillis()).getTime() - query.getCreatedOn().getTime()), TimeUnit.MILLISECONDS) > maxRunTimeSeconds).map(query -> UUID.fromString(query.getRequestId())).collect(Collectors.toSet());
        // AsyncAPI UUIDs that have active transactions
        Set<UUID> queryUUIDsToCancel = Sets.intersection(runningTransactionUUIDs, asyncTransactionUUIDs);
        // AsyncAPI IDs that need to be cancelled
        Set<String> queryIDsToCancel = queryUUIDsToCancel.stream().map(uuid -> StreamSupport.stream(asyncAPIIterable.spliterator(), false).filter(query -> query.getRequestId().equals(uuid.toString())).map(T::getId).findFirst().orElseThrow(IllegalStateException::new)).collect(Collectors.toSet());
        // Cancel Transactions
        queryUUIDsToCancel.stream().forEach((uuid) -> {
            DataStoreTransaction runningTransaction = transactionRegistry.getRunningTransaction(uuid);
            if (runningTransaction != null) {
                JsonApiDocument jsonApiDoc = new JsonApiDocument();
                MultivaluedMap<String, String> queryParams = new MultivaluedHashMap<>();
                RequestScope scope = new RequestScope("", "query", NO_VERSION, jsonApiDoc, runningTransaction, null, queryParams, Collections.emptyMap(), uuid, elide.getElideSettings());
                runningTransaction.cancel(scope);
            }
        });
        // Change queryStatus for cancelled queries
        if (!queryIDsToCancel.isEmpty()) {
            PathElement idPathElement = new PathElement(type, String.class, "id");
            FilterExpression fltIdExpression = new InPredicate(idPathElement, queryIDsToCancel);
            asyncAPIDao.updateStatusAsyncAPIByFilter(fltIdExpression, QueryStatus.CANCEL_COMPLETE, type);
        }
    } catch (Exception e) {
        log.error("Exception in scheduled cancellation: {}", e.toString());
    }
}
Also used : TransactionRegistry(com.yahoo.elide.core.TransactionRegistry) JsonApiDocument(com.yahoo.elide.jsonapi.models.JsonApiDocument) Date(java.util.Date) AsyncAPIDAO(com.yahoo.elide.async.service.dao.AsyncAPIDAO) Map(java.util.Map) NO_VERSION(com.yahoo.elide.core.dictionary.EntityDictionary.NO_VERSION) StreamSupport(java.util.stream.StreamSupport) AsyncAPI(com.yahoo.elide.async.models.AsyncAPI) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) QueryStatus(com.yahoo.elide.async.models.QueryStatus) RequestScope(com.yahoo.elide.core.RequestScope) Elide(com.yahoo.elide.Elide) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) InPredicate(com.yahoo.elide.core.filter.predicates.InPredicate) AsyncQuery(com.yahoo.elide.async.models.AsyncQuery) Set(java.util.Set) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Sets(com.google.common.collect.Sets) TimeUnit(java.util.concurrent.TimeUnit) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Slf4j(lombok.extern.slf4j.Slf4j) Data(lombok.Data) AllArgsConstructor(lombok.AllArgsConstructor) PathElement(com.yahoo.elide.core.Path.PathElement) Collections(java.util.Collections) JsonApiDocument(com.yahoo.elide.jsonapi.models.JsonApiDocument) TransactionRegistry(com.yahoo.elide.core.TransactionRegistry) InPredicate(com.yahoo.elide.core.filter.predicates.InPredicate) RequestScope(com.yahoo.elide.core.RequestScope) Date(java.util.Date) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) PathElement(com.yahoo.elide.core.Path.PathElement) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) UUID(java.util.UUID) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression)

Example 82 with FilterExpression

use of com.yahoo.elide.core.filter.expression.FilterExpression in project elide by yahoo.

the class InMemoryStoreTransaction method fetchData.

private DataStoreIterable<Object> fetchData(DataFetcher fetcher, EntityProjection projection, boolean filterInMemory, RequestScope scope) {
    Optional<FilterExpression> filterExpression = Optional.ofNullable(projection.getFilterExpression());
    Pair<Optional<FilterExpression>, Optional<FilterExpression>> expressionSplit = splitFilterExpression(scope, projection, filterInMemory);
    Optional<FilterExpression> dataStoreFilter = expressionSplit.getLeft();
    Optional<FilterExpression> inMemoryFilter = expressionSplit.getRight();
    Optional<Sorting> dataStoreSorting = getDataStoreSorting(scope, projection, filterInMemory);
    boolean sortingInMemory = dataStoreSorting.isEmpty() && projection.getSorting() != null;
    Optional<Pagination> dataStorePagination = inMemoryFilter.isPresent() || sortingInMemory ? Optional.empty() : Optional.ofNullable(projection.getPagination());
    DataStoreIterable<Object> loadedRecords = fetcher.fetch(dataStoreFilter, dataStoreSorting, dataStorePagination, scope);
    if (loadedRecords == null) {
        return new DataStoreIterableBuilder().build();
    }
    if (inMemoryFilter.isPresent() || (loadedRecords.needsInMemoryFilter() && projection.getFilterExpression() != null)) {
        loadedRecords = filterLoadedData(loadedRecords, filterExpression, scope);
    }
    return sortAndPaginateLoadedData(loadedRecords, sortingInMemory, projection.getSorting(), projection.getPagination(), scope);
}
Also used : Pagination(com.yahoo.elide.core.request.Pagination) Optional(java.util.Optional) DataStoreIterableBuilder(com.yahoo.elide.core.datastore.DataStoreIterableBuilder) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) Sorting(com.yahoo.elide.core.request.Sorting)

Example 83 with FilterExpression

use of com.yahoo.elide.core.filter.expression.FilterExpression in project elide by yahoo.

the class EntityProjectionTranslatorTest method testWherePromotion.

@Test
public void testWherePromotion() throws ParseException {
    FilterExpression originalFilter = filterParser.parseFilterExpression("overallRating==Good,lowScore[foo:bar]<45", playerStatsType, false);
    EntityProjection projection = basicProjection.copyOf().filterExpression(originalFilter).build();
    EntityProjectionTranslator translator = new EntityProjectionTranslator(engine, playerStatsTable, projection, scope, true);
    Query query = translator.getQuery();
    SplitFilterExpressionVisitor visitor = new SplitFilterExpressionVisitor(playerStatsTable);
    FilterConstraints constraints = originalFilter.accept(visitor);
    FilterExpression whereFilter = constraints.getWhereExpression();
    FilterExpression havingFilter = constraints.getHavingExpression();
    assertEquals(whereFilter, query.getWhereFilter());
    assertEquals(havingFilter, query.getHavingFilter());
}
Also used : EntityProjection(com.yahoo.elide.core.request.EntityProjection) Query(com.yahoo.elide.datastores.aggregation.query.Query) SplitFilterExpressionVisitor(com.yahoo.elide.datastores.aggregation.filter.visitor.SplitFilterExpressionVisitor) FilterConstraints(com.yahoo.elide.datastores.aggregation.filter.visitor.FilterConstraints) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) SQLUnitTest(com.yahoo.elide.datastores.aggregation.framework.SQLUnitTest) Test(org.junit.jupiter.api.Test)

Example 84 with FilterExpression

use of com.yahoo.elide.core.filter.expression.FilterExpression in project elide by yahoo.

the class EntityProjectionTranslatorTest method testHavingClauseMetricsMissingFromProjection.

@Test
public void testHavingClauseMetricsMissingFromProjection() throws ParseException {
    FilterExpression filter = filterParser.parseFilterExpression("lowScore>45", playerStatsType, false);
    EntityProjection projection = EntityProjection.builder().type(PlayerStats.class).filterExpression(filter).attribute(Attribute.builder().type(long.class).name("highScore").build()).attribute(Attribute.builder().type(String.class).name("overallRating").build()).build();
    EntityProjectionTranslator translator = new EntityProjectionTranslator(engine, playerStatsTable, projection, scope, true);
    Query query = translator.getQuery();
    List<String> metricNames = query.getMetricProjections().stream().map(MetricProjection::getName).collect(Collectors.toList());
    assertEquals(metricNames, Arrays.asList("highScore", "lowScore"));
}
Also used : EntityProjection(com.yahoo.elide.core.request.EntityProjection) Query(com.yahoo.elide.datastores.aggregation.query.Query) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) SQLUnitTest(com.yahoo.elide.datastores.aggregation.framework.SQLUnitTest) Test(org.junit.jupiter.api.Test)

Example 85 with FilterExpression

use of com.yahoo.elide.core.filter.expression.FilterExpression in project elide by yahoo.

the class SubqueryFilterSplitter method splitFilter.

public static SplitFilter splitFilter(MetaDataStore metaDataStore, FilterExpression expression) {
    if (expression == null) {
        return SplitFilter.builder().build();
    }
    FilterExpressionNormalizationVisitor normalizer = new FilterExpressionNormalizationVisitor();
    FilterExpression normalizedExpression = expression.accept(normalizer);
    return normalizedExpression.accept(new SubqueryFilterSplitter(metaDataStore));
}
Also used : FilterExpressionNormalizationVisitor(com.yahoo.elide.core.filter.visitors.FilterExpressionNormalizationVisitor) NotFilterExpression(com.yahoo.elide.core.filter.expression.NotFilterExpression) OrFilterExpression(com.yahoo.elide.core.filter.expression.OrFilterExpression) AndFilterExpression(com.yahoo.elide.core.filter.expression.AndFilterExpression) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression)

Aggregations

FilterExpression (com.yahoo.elide.core.filter.expression.FilterExpression)214 Test (org.junit.jupiter.api.Test)161 OrFilterExpression (com.yahoo.elide.core.filter.expression.OrFilterExpression)91 AndFilterExpression (com.yahoo.elide.core.filter.expression.AndFilterExpression)72 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)49 FilterPredicate (com.yahoo.elide.core.filter.predicates.FilterPredicate)46 Path (com.yahoo.elide.core.Path)44 Query (com.yahoo.elide.datastores.aggregation.query.Query)42 Argument (com.yahoo.elide.core.request.Argument)39 SQLUnitTest (com.yahoo.elide.datastores.aggregation.framework.SQLUnitTest)39 DataStoreTransaction (com.yahoo.elide.core.datastore.DataStoreTransaction)34 SQLTable (com.yahoo.elide.datastores.aggregation.queryengines.sql.metadata.SQLTable)34 HashMap (java.util.HashMap)29 Book (example.Book)28 NotFilterExpression (com.yahoo.elide.core.filter.expression.NotFilterExpression)24 EntityProjection (com.yahoo.elide.core.request.EntityProjection)22 Date (java.util.Date)21 EntityDictionary (com.yahoo.elide.core.dictionary.EntityDictionary)20 Day (com.yahoo.elide.datastores.aggregation.timegrains.Day)19 HashSet (java.util.HashSet)18