You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Weaviate向量数据库如何实现过滤结果的分页查询?

查询过滤功能可用

Weaviate的查询过滤功能可正常使用,例如官方教程中的示例:

response = (
    client.query
    .get("JeopardyQuestion", ["question", "answer", "round"])
    .with_where({
        "path": ["round"],
        "operator": "Equal",
        "valueText": "Double Jeopardy!"
    })
    .with_limit(20)
    .do()
)
分页出现问题?

但仅获取前20条结果无法满足全功能语义搜索的需求,我们需要分页来依次获取后续的20条结果。Weaviate使用查询游标实现分页,需传入记录的UUID:

response = (
    client.query
    .get("JeopardyQuestion", ["question", "answer", "round"])
    .with_where({
        "path": ["round"],
        "operator": "Equal",
        "valueText": "Double Jeopardy!"
    })
    .with_after("6726aaa8-818b-49dc-8fea-9bc646ddfed6")   # <-- ID游标分页
    .with_limit(20)
    .do()
)

但该代码会抛出错误:

where cannot be set with after and limit parameters

该错误来自Weaviate的游标验证逻辑,且with_after()的文档明确说明其“需要设置limit,但不能与任何其他过滤器或搜索结合使用”。

因此无法直接组合过滤器、游标和limit参数。以下是实现过滤查询分页的正确方式:


正确实现方式:使用偏移分页

当需要结合过滤条件分页时,应使用偏移分页,通过with_offset()方法指定跳过的结果数量,以此获取后续页面的数据。

示例代码:

# 获取第一页(前20条)
first_page = (
    client.query
    .get("JeopardyQuestion", ["question", "answer", "round"])
    .with_where({
        "path": ["round"],
        "operator": "Equal",
        "valueText": "Double Jeopardy!"
    })
    .with_limit(20)
    .do()
)

# 获取第二页(第21-40条)
second_page = (
    client.query
    .get("JeopardyQuestion", ["question", "answer", "round"])
    .with_where({
        "path": ["round"],
        "operator": "Equal",
        "valueText": "Double Jeopardy!"
    })
    .with_limit(20)
    .with_offset(20)  # 跳过前20条,直接取后续结果
    .do()
)

# 后续页面只需递增偏移量即可,比如第三页偏移40,以此类推

注意事项

  • 偏移分页在偏移量较大时(如超过1000)可能出现性能瓶颈,因为Weaviate需要先扫描并跳过前面所有结果。
  • 若使用较新版本的Weaviate,可确认官方文档是否已取消with_after()与with_where()的组合限制,部分版本可能已优化此逻辑。

内容的提问来源于stack exchange,提问作者kdbanman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 22:47:41