实际项目中,过滤条件通常会有多个,条件之间的关系可能包含逻辑与和逻辑或。在 Chroma 中,使用 $and 表示逻辑与关系,即同时满足所有条件。使用 $or 表示逻辑或,多个条件中满足任意一个或多个即可。
语法如下:
col.get(where={"$and": [
{"cat": "售后"}, # 条件1
{"year": {"$gte": 2024}} # 条件2
]})
col.get(where={"$or": [
{"cat": "售后"}, # 条件1
{"year": {"$gte": 2024}} # 条件2
]})$and 要求“条件 1”和“条件 2”同时满足,$or 要求“条件 1”和“条件 2”满足一个即可。
示例:
print("\n--- cat='售后' 且 year>=2024 ---")
show(col.get(where={"$and": [{"cat": "售后"}, {"year": {"$gte": 2024}}]}))
print("\n--- cat='财务' 或 year=2020 ---")
show(col.get(where={"$or": [{"cat": "财务"}, {"year": 2020}]}))运行代码,输出:
--- cat='售后' 且 year>=2024 ---
id=r4, document=退货政策, metadata={'score': 0.3, 'cat': '售后', 'is_public': False, 'tags': ['b', 'd'], 'year': 2024}
--- cat='财务' 或 year=2020 ---
id=r1, document=退款流程 refund, metadata={'cat': '售后', 'is_public': True, 'score': 0.9, 'year': 2020, 'tags': ['a', 'b']}
id=r2, document=发票 invoice, metadata={'tags': ['c'], 'cat': '财务', 'score': 0.5, 'is_public': False, 'year': 2022}它们还支持任意嵌套:
print("\n--- (cat='财务' 或 cat='物流') 且 year>=2024 ---")
res = col.get(where={
"$and": [
{"$or": [{"cat": "财务"}, {"cat": "物流"}]},
{"year": {"$gte": 2024}},
]
})
show(res)运行,输出如下:
--- (cat='财务' 或 cat='物流') 且 year>=2024 ---
id=r3, document=物流 logistics, metadata={'score': 0.7, 'tags': ['a', 'd'], 'cat': '物流', 'is_public': False, 'year': 2024}如果你将多个条件写成这样:
res = col.get(where={"cat": "售后", "year": 2024})
show(res)Chroma 会报错:
ValueError: Expected where to have exactly one operator, got {'cat': '售后', 'year': 2024} in get.
Chroma 要求顶层必须是单个操作符($and / $or),不能并行写多个 metadata 条件。
如果 $and 、 $or 内部只有一个元素,像这样:
res = col.get(where={"$and":[{"cat": "售后"}]})
show(res)Chroma 会报错:
ValueError: Expected where value for $and or $or to be a list with at least two where expressions, got [{'cat': '售后'}] in get.
注意:$and / $or 里面的列表不能只放 1 条条件,Chroma 校验要求至少 2 条表达式。