Search in sources :

Example 16 with Sorting

use of com.yahoo.elide.core.request.Sorting in project elide by yahoo.

the class PersistentResource method getRelationUnchecked.

/**
 * Retrieve an unchecked set of relations.
 */
private Observable<PersistentResource> getRelationUnchecked(com.yahoo.elide.core.request.Relationship relationship) {
    String relationName = relationship.getName();
    FilterExpression filterExpression = relationship.getProjection().getFilterExpression();
    Pagination pagination = relationship.getProjection().getPagination();
    Sorting sorting = relationship.getProjection().getSorting();
    RelationshipType type = getRelationshipType(relationName);
    final Type<?> relationClass = dictionary.getParameterizedType(obj, relationName);
    if (relationClass == null) {
        throw new InvalidAttributeException(relationName, this.getTypeName());
    }
    // Invoke filterExpressionCheck and then merge with filterExpression.
    Optional<FilterExpression> permissionFilter = getPermissionFilterExpression(relationClass, requestScope, relationship.getProjection().getRequestedFields());
    Optional<FilterExpression> computedFilters = Optional.ofNullable(filterExpression);
    if (permissionFilter.isPresent() && filterExpression != null) {
        FilterExpression mergedExpression = new AndFilterExpression(filterExpression, permissionFilter.get());
        computedFilters = Optional.of(mergedExpression);
    } else if (permissionFilter.isPresent()) {
        computedFilters = permissionFilter;
    }
    com.yahoo.elide.core.request.Relationship modifiedRelationship = relationship.copyOf().projection(relationship.getProjection().copyOf().filterExpression(computedFilters.orElse(null)).sorting(sorting).pagination(pagination).build()).build();
    Observable<PersistentResource> resources;
    if (type.isToMany()) {
        DataStoreIterable val = transaction.getToManyRelation(transaction, obj, modifiedRelationship, requestScope);
        if (val == null) {
            return Observable.empty();
        }
        resources = Observable.fromIterable(new PersistentResourceSet(this, relationName, val, requestScope));
    } else {
        Object val = transaction.getToOneRelation(transaction, obj, modifiedRelationship, requestScope);
        if (val == null) {
            return Observable.empty();
        }
        resources = Observable.fromArray(new PersistentResource(val, this, relationName, requestScope.getUUIDFor(val), requestScope));
    }
    return resources;
}
Also used : InvalidAttributeException(com.yahoo.elide.core.exceptions.InvalidAttributeException) RelationshipType(com.yahoo.elide.core.dictionary.RelationshipType) DataStoreIterable(com.yahoo.elide.core.datastore.DataStoreIterable) Sorting(com.yahoo.elide.core.request.Sorting) Pagination(com.yahoo.elide.core.request.Pagination) AndFilterExpression(com.yahoo.elide.core.filter.expression.AndFilterExpression) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) AndFilterExpression(com.yahoo.elide.core.filter.expression.AndFilterExpression)

Example 17 with Sorting

use of com.yahoo.elide.core.request.Sorting in project elide by yahoo.

the class SearchDataTransaction method search.

/**
 * Perform the full-text search.
 * @param entityType The class to search
 * @param filterExpression The filter expression to apply
 * @param sorting Optional sorting
 * @param pagination Optional pagination
 * @return A list of records of type entityClass.
 */
private <T> List<T> search(Type<?> entityType, FilterExpression filterExpression, Optional<Sorting> sorting, Optional<Pagination> pagination) {
    Query query;
    Class<?> entityClass = null;
    if (entityType != null) {
        Preconditions.checkState(entityType instanceof ClassType);
        entityClass = ((ClassType) entityType).getCls();
    }
    try {
        query = filterExpression.accept(new FilterExpressionToLuceneQuery(em, entityClass));
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e.getMessage());
    }
    FullTextQuery fullTextQuery = em.createFullTextQuery(query, entityClass);
    if (mustSort(sorting)) {
        fullTextQuery = fullTextQuery.setSort(buildSort(sorting.get(), entityType));
    }
    if (pagination.isPresent()) {
        fullTextQuery = fullTextQuery.setMaxResults(pagination.get().getLimit());
        fullTextQuery = fullTextQuery.setFirstResult(pagination.get().getOffset());
    }
    List<T[]> results = fullTextQuery.setProjection(ProjectionConstants.THIS).getResultList();
    if (pagination.filter(Pagination::returnPageTotals).isPresent()) {
        pagination.get().setPageTotals((long) fullTextQuery.getResultSize());
    }
    if (results.isEmpty()) {
        return Collections.emptyList();
    }
    return results.stream().map(result -> result[0]).collect(Collectors.toList());
}
Also used : PredicateExtractionVisitor(com.yahoo.elide.core.filter.expression.PredicateExtractionVisitor) Query(org.apache.lucene.search.Query) FilterPredicate(com.yahoo.elide.core.filter.predicates.FilterPredicate) Arrays(java.util.Arrays) Path(com.yahoo.elide.core.Path) DataStoreIterableBuilder(com.yahoo.elide.core.datastore.DataStoreIterableBuilder) ProjectionConstants(org.hibernate.search.engine.ProjectionConstants) SortableField(org.hibernate.search.annotations.SortableField) FullTextQuery(org.hibernate.search.jpa.FullTextQuery) Index(org.hibernate.search.annotations.Index) ClassType(com.yahoo.elide.core.type.ClassType) Fields(org.hibernate.search.annotations.Fields) ArrayList(java.util.ArrayList) Map(java.util.Map) DataStoreIterable(com.yahoo.elide.core.datastore.DataStoreIterable) TransactionWrapper(com.yahoo.elide.core.datastore.wrapped.TransactionWrapper) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) RequestScope(com.yahoo.elide.core.RequestScope) FullTextEntityManager(org.hibernate.search.jpa.FullTextEntityManager) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) HttpStatusException(com.yahoo.elide.core.exceptions.HttpStatusException) Sorting(com.yahoo.elide.core.request.Sorting) Sort(org.apache.lucene.search.Sort) Collection(java.util.Collection) Field(org.hibernate.search.annotations.Field) EntityProjection(com.yahoo.elide.core.request.EntityProjection) Collectors(java.util.stream.Collectors) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary) SortFieldContext(org.hibernate.search.query.dsl.sort.SortFieldContext) List(java.util.List) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) Pagination(com.yahoo.elide.core.request.Pagination) InvalidValueException(com.yahoo.elide.core.exceptions.InvalidValueException) Type(com.yahoo.elide.core.type.Type) Operator(com.yahoo.elide.core.filter.Operator) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) Comparator(java.util.Comparator) Collections(java.util.Collections) QueryBuilder(org.hibernate.search.query.dsl.QueryBuilder) Query(org.apache.lucene.search.Query) FullTextQuery(org.hibernate.search.jpa.FullTextQuery) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) ClassType(com.yahoo.elide.core.type.ClassType) FullTextQuery(org.hibernate.search.jpa.FullTextQuery)

Example 18 with Sorting

use of com.yahoo.elide.core.request.Sorting in project elide by yahoo.

the class SearchDataTransaction method buildSort.

/**
 * Builds a lucene Sort object from and Elide Sorting object.
 * @param sorting Elide sorting object
 * @param entityType The entity being sorted.
 * @return A lucene Sort object
 */
private Sort buildSort(Sorting sorting, Type<?> entityType) {
    Class<?> entityClass = null;
    if (entityType != null) {
        Preconditions.checkState(entityType instanceof ClassType);
        entityClass = ((ClassType) entityType).getCls();
    }
    QueryBuilder builder = em.getSearchFactory().buildQueryBuilder().forEntity(entityClass).get();
    SortFieldContext context = null;
    for (Map.Entry<Path, Sorting.SortOrder> entry : sorting.getSortingPaths().entrySet()) {
        String fieldName = entry.getKey().lastElement().get().getFieldName();
        SortableField sortableField = dictionary.getAttributeOrRelationAnnotation(entityType, SortableField.class, fieldName);
        fieldName = sortableField.forField().isEmpty() ? fieldName : sortableField.forField();
        if (context == null) {
            context = builder.sort().byField(fieldName);
        } else {
            context.andByField(fieldName);
        }
        Sorting.SortOrder order = entry.getValue();
        if (order == Sorting.SortOrder.asc) {
            context = context.asc();
        } else {
            context = context.desc();
        }
    }
    if (context == null) {
        throw new IllegalStateException("Invalid Sort rules");
    }
    return context.createSort();
}
Also used : Path(com.yahoo.elide.core.Path) SortableField(org.hibernate.search.annotations.SortableField) QueryBuilder(org.hibernate.search.query.dsl.QueryBuilder) ClassType(com.yahoo.elide.core.type.ClassType) Sorting(com.yahoo.elide.core.request.Sorting) SortFieldContext(org.hibernate.search.query.dsl.sort.SortFieldContext) Map(java.util.Map)

Example 19 with Sorting

use of com.yahoo.elide.core.request.Sorting in project elide by yahoo.

the class DataStoreLoadTest method testSortingDescending.

@Test
public void testSortingDescending() throws Exception {
    DataStoreTransaction testTransaction = searchStore.beginReadTransaction();
    Map<String, Sorting.SortOrder> sortRules = new HashMap<>();
    sortRules.put("name", Sorting.SortOrder.desc);
    sortRules.put("modifiedDate", Sorting.SortOrder.asc);
    Sorting sorting = new SortingImpl(sortRules, Item.class, dictionary);
    FilterExpression filter = filterParser.parseFilterExpression("name==cymbal*", ClassType.of(Item.class), false);
    Iterable<Object> loaded = testTransaction.loadObjects(EntityProjection.builder().type(Item.class).filterExpression(filter).sorting(sorting).build(), mockScope);
    assertListMatches(loaded, Lists.newArrayList(2L, 5L, 4L));
    verify(wrappedTransaction, never()).loadObjects(any(), any());
}
Also used : Item(com.yahoo.elide.datastores.search.models.Item) HashMap(java.util.HashMap) SortingImpl(com.yahoo.elide.core.sort.SortingImpl) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) Sorting(com.yahoo.elide.core.request.Sorting) Test(org.junit.jupiter.api.Test)

Example 20 with Sorting

use of com.yahoo.elide.core.request.Sorting in project elide by yahoo.

the class DataStoreLoadTest method testPaginationPageOne.

@Test
public void testPaginationPageOne() throws Exception {
    DataStoreTransaction testTransaction = searchStore.beginReadTransaction();
    Map<String, Sorting.SortOrder> sortRules = new HashMap<>();
    sortRules.put("name", Sorting.SortOrder.desc);
    sortRules.put("modifiedDate", Sorting.SortOrder.asc);
    Sorting sorting = new SortingImpl(sortRules, Item.class, dictionary);
    PaginationImpl pagination = new PaginationImpl(Item.class, 0, 1, PaginationImpl.DEFAULT_PAGE_LIMIT, PaginationImpl.MAX_PAGE_LIMIT, true, false);
    FilterExpression filter = filterParser.parseFilterExpression("name==cymbal*", ClassType.of(Item.class), false);
    Iterable<Object> loaded = testTransaction.loadObjects(EntityProjection.builder().type(Item.class).filterExpression(filter).sorting(sorting).pagination(pagination).build(), mockScope);
    assertListMatches(loaded, Lists.newArrayList(2L));
    assertEquals(pagination.getPageTotals(), 3);
    verify(wrappedTransaction, never()).loadObjects(any(), any());
}
Also used : Item(com.yahoo.elide.datastores.search.models.Item) PaginationImpl(com.yahoo.elide.core.pagination.PaginationImpl) HashMap(java.util.HashMap) SortingImpl(com.yahoo.elide.core.sort.SortingImpl) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) Sorting(com.yahoo.elide.core.request.Sorting) Test(org.junit.jupiter.api.Test)

Aggregations

Sorting (com.yahoo.elide.core.request.Sorting)22 Test (org.junit.jupiter.api.Test)13 FilterExpression (com.yahoo.elide.core.filter.expression.FilterExpression)12 EntityProjection (com.yahoo.elide.core.request.EntityProjection)11 DataStoreIterable (com.yahoo.elide.core.datastore.DataStoreIterable)10 SortingImpl (com.yahoo.elide.core.sort.SortingImpl)10 HashMap (java.util.HashMap)10 DataStoreTransaction (com.yahoo.elide.core.datastore.DataStoreTransaction)9 Path (com.yahoo.elide.core.Path)8 DataStoreIterableBuilder (com.yahoo.elide.core.datastore.DataStoreIterableBuilder)8 Collection (java.util.Collection)7 EntityDictionary (com.yahoo.elide.core.dictionary.EntityDictionary)6 ClassType (com.yahoo.elide.core.type.ClassType)6 Map (java.util.Map)6 RequestScope (com.yahoo.elide.core.RequestScope)5 InPredicate (com.yahoo.elide.core.filter.predicates.InPredicate)5 PaginationImpl (com.yahoo.elide.core.pagination.PaginationImpl)5 Pagination (com.yahoo.elide.core.request.Pagination)5 Book (example.Book)5 Editor (example.Editor)5