|
| 1 | +package io.weaviate.client6.v1.api.collections.pagination; |
| 2 | + |
| 3 | +import java.util.Iterator; |
| 4 | +import java.util.Spliterator; |
| 5 | +import java.util.Spliterators; |
| 6 | +import java.util.function.Function; |
| 7 | +import java.util.stream.Stream; |
| 8 | +import java.util.stream.StreamSupport; |
| 9 | + |
| 10 | +import io.weaviate.client6.v1.api.collections.WeaviateObject; |
| 11 | +import io.weaviate.client6.v1.api.collections.query.QueryMetadata; |
| 12 | +import io.weaviate.client6.v1.api.collections.query.WeaviateQueryClient; |
| 13 | +import io.weaviate.client6.v1.internal.ObjectBuilder; |
| 14 | + |
| 15 | +public class Paginator<T> implements Iterable<WeaviateObject<T, Object, QueryMetadata>> { |
| 16 | + private static final int DEFAULT_PAGE_SIZE = 100; |
| 17 | + |
| 18 | + private final WeaviateQueryClient<T> query; |
| 19 | + private final int pageSize; |
| 20 | + private final String cursor; |
| 21 | + |
| 22 | + @Override |
| 23 | + public Iterator<WeaviateObject<T, Object, QueryMetadata>> iterator() { |
| 24 | + return Spliterators.iterator(spliterator()); |
| 25 | + } |
| 26 | + |
| 27 | + public Stream<WeaviateObject<T, Object, QueryMetadata>> stream() { |
| 28 | + return StreamSupport.stream(spliterator(), false); |
| 29 | + } |
| 30 | + |
| 31 | + public Spliterator<WeaviateObject<T, Object, QueryMetadata>> spliterator() { |
| 32 | + return new CursorSpliterator<T>(cursor, pageSize, |
| 33 | + (after, limit) -> query.fetchObjects(q -> q.after(after).limit(limit)).objects()); |
| 34 | + } |
| 35 | + |
| 36 | + public static <T> Paginator<T> of(WeaviateQueryClient<T> query) { |
| 37 | + return of(query, ObjectBuilder.identity()); |
| 38 | + } |
| 39 | + |
| 40 | + public static <T> Paginator<T> of(WeaviateQueryClient<T> query, |
| 41 | + Function<Builder<T>, ObjectBuilder<Paginator<T>>> fn) { |
| 42 | + return fn.apply(new Builder<>(query)).build(); |
| 43 | + } |
| 44 | + |
| 45 | + Paginator(Builder<T> builder) { |
| 46 | + this.query = builder.query; |
| 47 | + this.cursor = builder.cursor; |
| 48 | + this.pageSize = builder.pageSize; |
| 49 | + } |
| 50 | + |
| 51 | + public static class Builder<T> implements ObjectBuilder<Paginator<T>> { |
| 52 | + private final WeaviateQueryClient<T> query; |
| 53 | + |
| 54 | + int pageSize = DEFAULT_PAGE_SIZE; |
| 55 | + String cursor; |
| 56 | + |
| 57 | + public Builder(WeaviateQueryClient<T> query) { |
| 58 | + this.query = query; |
| 59 | + } |
| 60 | + |
| 61 | + public Builder<T> pageSize(int pageSize) { |
| 62 | + this.pageSize = pageSize; |
| 63 | + return this; |
| 64 | + } |
| 65 | + |
| 66 | + public Builder<T> resumeFrom(String uuid) { |
| 67 | + this.cursor = uuid; |
| 68 | + return this; |
| 69 | + } |
| 70 | + |
| 71 | + @Override |
| 72 | + public Paginator<T> build() { |
| 73 | + return new Paginator<>(this); |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | +} |
0 commit comments