这和 $in / $nin 条件类似,只是 $contains / $not_contains 要求数据库中的字段是数组,而 $in / $nin 条件是数组。
作用类似,也是判断某个值是否包含在数组中。例如:
col.get(where={"tags": {"$contains": "a"}})
# 判断 tags 数组字段中是否包含 a 字符串这种方式,是处理“标签”这类多选字段的标准做法:
print("\n--- tags 包含 a 字符串 ---")
show(col.get(where={"tags": {"$contains": "a"}}))
print("\n--- tags 不包含 a 字符串 ---")
show(col.get(where={"tags": {"$not_contains": "a"}}))运行示例,输出:
--- tags 包含 a 字符串 ---
id=r1, document=退款流程 refund, metadata={'score': 0.9, 'year': 2020, 'cat': '售后', 'is_public': True, 'tags': ['a', 'b']}
id=r3, document=物流 logistics, metadata={'cat': '物流', 'year': 2024, 'tags': ['a', 'd'], 'score': 0.7, 'is_public': False}
--- tags 不包含 a 字符串 ---
id=r2, document=发票 invoice, metadata={'cat': '财务', 'year': 2022, 'tags': ['c'], 'score': 0.5, 'is_public': False}
id=r4, document=退货政策, metadata={'tags': ['b', 'd'], 'is_public': False, 'year': 2024, 'cat': '售后', 'score': 0.3}数值数组、布尔数组同样支持:
col.get(where={"scores": {"$contains": 5}})
col.get(where={"flags": {"$contains": True}})注意:$contains 只对数组字段有效。你想在字符串字段里做“包含”判断,那不是 metadata 过滤,得用 where_document 的 $contains。