Chroma 教程

数组字段:$contains / $not_contains

🎉摘要:本文介绍数据库查询中的$contains和$not_contains操作符,用于判断数组字段是否包含特定值。与$in/$nin条件类似但方向相反,适用于标签等多选字段。示例展示了字符串、数值和布尔数组的查询用法,并提醒$contains仅对数组字段有效,字符串包含需使用where_document的$contains。

这和 $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。

  

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