Chroma 教程

$and / $or 逻辑与/或

🎉摘要:本文详细介绍了 Chroma 中过滤条件的逻辑与($and)和逻辑或($or)的使用方法,包括语法、示例、嵌套用法以及常见错误提示,帮助开发者正确使用多个条件进行数据查询。

实际项目中,过滤条件通常会有多个,条件之间的关系可能包含逻辑与和逻辑或。在 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 条表达式。  

  

说说我的看法
全部评论()
没有评论
关于
本网站专注于 Java、数据库(MySQL、Oracle)、Linux、软件架构及大数据等多领域技术知识分享。涵盖丰富的原创与精选技术文章,助力技术传播与交流。无论是技术新手渴望入门,还是资深开发者寻求进阶,这里都能为您提供深度见解与实用经验,让复杂编码变得轻松易懂,携手共赴技术提升新高度。如有侵权,请来信告知:hxstrive@outlook.com
其他应用
公众号