@Override public Optional<List<BulletError>> initialize() { Optional<List<BulletError>> errors = super.initialize(); if (errors.isPresent()) { return errors; } if (fields == null || fields.isEmpty()) { return Optional.of(Collections.singletonList(ORDERBY_REQUIRES_FIELDS_ERROR)); } if (fields.stream().anyMatch(sortItem -> sortItem.getField() == null || sortItem.getField().isEmpty())) { return Optional.of(Collections.singletonList(ORDERBY_REQUIRES_NON_EMPTY_FIELDS_ERROR)); } return Optional.empty(); }
@Override public Clip execute(Clip clip) { List<BulletRecord> records = clip.getRecords(); records.sort((a, b) -> { for (OrderBy.SortItem sortItem : orderBy.getFields()) { TypedObject typedObjectA = extractTypedObject(sortItem.getField(), a); TypedObject typedObjectB = extractTypedObject(sortItem.getField(), b); try { int compareValue = typedObjectA.compareTo(typedObjectB); if (compareValue != 0) { return (sortItem.getDirection() == OrderBy.Direction.ASC ? 1 : -1) * compareValue; } } catch (RuntimeException e) { // Ignore the exception and skip this field. log.error("Unable to compare field " + sortItem.getField()); log.error("Skip it due to: " + e); } } return 0; }); return clip; }
/** * Extract an OrderBy PostAggregation. * * @return A PostAggregation based on an OrderBy node */ public PostAggregation extractOrderBy() { List<com.yahoo.bullet.parsing.OrderBy.SortItem> fields = node.getSortItems().stream().map(sortItem -> new com.yahoo.bullet.parsing.OrderBy.SortItem( sortItem.getSortKey().toFormatlessString(), sortItem.getOrdering() == SortItem.Ordering.DESCENDING ? Direction.DESC : Direction.ASC) ).collect(Collectors.toList()); com.yahoo.bullet.parsing.OrderBy orderBy = new com.yahoo.bullet.parsing.OrderBy(); orderBy.setType(PostAggregation.Type.ORDER_BY); orderBy.setFields(fields); return orderBy; } }