Weaviate Java SDK:带offset分页的nearText向量搜索如何获结果总数及判断下一页?
在Weaviate Java SDK的Offset分页向量搜索中获取总命中数及判断下一页
你可以通过在同一个GraphQL查询中同时执行get(获取分页结果)和aggregate(统计总命中数)操作,一次性拿到分页数据和总数量,无需分开发起请求。
实现思路
- 构建相同的
nearText过滤条件,同时用于get和aggregate查询 - 在
get中指定limit和offset获取当前页数据 - 在
aggregate中统计符合条件的总条目数 - 通过总条目数与当前
offset+limit的比较,判断是否存在有效下一页:总命中数 > (offset + limit)
示例代码
import io.weaviate.client.WeaviateClient; import io.weaviate.client.base.Result; import io.weaviate.client.v1.graphql.model.GraphQLResponse; import io.weaviate.client.v1.graphql.query.argument.NearTextArgument; import io.weaviate.client.v1.graphql.query.fields.AggregateFields; import io.weaviate.client.v1.graphql.query.fields.GetFields; public class WeaviatePaginationExample { public static void main(String[] args) { WeaviateClient weaviateClient = new WeaviateClient("http://localhost:8080"); // 替换为你的Weaviate服务地址 // 构建nearText过滤参数 NearTextArgument nearTextArgument = weaviateClient.graphQL().arguments().nearTextArgBuilder() .concepts(new String[]{"basketball"}) .certainty(0.6f) .build(); int limit = 25; int offset = 50; // 示例:第3页(每页25条) // 构建包含get和aggregate的复合查询 Result<GraphQLResponse> result = weaviateClient.graphQL().query() .withGet(weaviateClient.graphQL().get() .withClassName("YourClassName") // 替换为你的Weaviate类名 .withNearText(nearTextArgument) .withFields(new GetFields.Builder() .addField("id") .addField("title") // 替换为你需要返回的字段 .build()) .withLimit(limit) .withOffset(offset)) .withAggregate(weaviateClient.graphQL().aggregate() .withClassName("YourClassName") // 与get使用相同的类名 .withNearText(nearTextArgument) .withFields(new AggregateFields.Builder() .count() // 统计总命中数 .build())) .run(); if (result.isSuccess()) { // 解析分页数据 Object pageData = result.getResult().getData().get("Get").get("YourClassName"); System.out.println("当前页数据: " + pageData); // 解析总命中数 Integer totalHits = (Integer) result.getResult().getData().get("Aggregate").get("YourClassName").get(0).get("meta").get("count"); System.out.println("总命中数: " + totalHits); // 判断是否存在下一页 boolean hasNextPage = totalHits > (offset + limit); System.out.println("是否有下一页: " + hasNextPage); } else { System.err.println("查询失败: " + result.getError()); } } }
注意事项
get和aggregate必须使用相同的类名和相同的过滤条件(这里是nearText),才能保证统计的总命中数和分页结果匹配- 替换代码中的
YourClassName为你实际使用的Weaviate类名,以及调整withFields中的字段为你需要返回的属性
内容的提问来源于stack exchange,提问作者junbetterway
相关产品推荐
相关产品推荐

