public static void writeOrder(Terms.Order order, StreamOutput out) throws IOException {
if (order instanceof Aggregation) {
out.writeByte(order.id());
Aggregation aggregationOrder = (Aggregation) order;
out.writeBoolean(((MultiBucketsAggregation.Bucket.SubAggregationComparator) aggregationOrder.comparator).asc());
OrderPath path = ((Aggregation) order).path();
if (out.getVersion().onOrAfter(Version.V_1_1_0)) {
out.writeString(path.toString());
} else {
// prev versions only supported sorting on a single level -> a single token;
OrderPath.Token token = path.lastToken();
out.writeString(token.name);
boolean hasValueName = token.key != null;
out.writeBoolean(hasValueName);
if (hasValueName) {
out.writeString(token.key);