0Pricing
Vector Databases: Pinecone, Weaviate & pgvector · 课时

使用元数据进行筛选

利用元数据优化相似度搜索,为查询增加上下文约束。

使用元数据进行筛选 是 CoddyKit 上的免费 Vector Databases: Pinecone, Weaviate & pgvector 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Vector Databases: Pinecone, Weaviate & pgvector 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Vector Databases: Pinecone, Weaviate & pgvector 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Filter Your Vector Searches

Imagine searching for products, but only wanting "electronics" that are "under $50". This is where metadata filtering comes in handy!

Vector databases let you store extra information, called metadata, alongside your vectors. This lesson teaches you how to use this metadata to refine your similarity searches in Pinecone.

Understanding Metadata

Metadata is simply "data about data." In Pinecone, it's a set of key-value pairs attached to each vector.

  • Key: A string representing a property (e.g., "category", "price", "author").
  • Value: Can be a string, number, boolean, or even a list of strings/numbers.

It helps describe the item your vector represents.

Why Filter Searches?

Filtering is crucial for getting more precise and relevant search results.

  • Precision: Narrow down results to only what's relevant (e.g., "red shoes").
  • Context: Add specific conditions beyond just vector similarity (e.g., "articles published last year").
  • Efficiency: Reduce the number of vectors considered, potentially speeding up searches for large datasets.

Adding Metadata to Vectors

When you add (or "upsert") vectors into Pinecone, you can include a metadata dictionary. This makes the extra data searchable later.

You learned about upserting in a previous lesson. Here's a quick reminder of how metadata is attached:

from pinecone import Pinecone, Index
import os

# Assume Pinecone is initialized (replace with your actual setup)
# pc = Pinecone(api_key=os.environ.get("PINECONE_API_KEY"))
# index = pc.Index("my-index")

# Example vector with metadata
vectors_to_upsert = [
    {
        "id": "item1",
        "values": [0.1, 0.2, 0.3], # Placeholder vector
        "metadata": {"genre": "fiction", "year": 2023, "price": 19.99}
    },
    {
        "id": "item2",
        "values": [0.4, 0.5, 0.6],
        "metadata": {"genre": "non-fiction", "year": 2022, "price": 25.50}
    }
]

# index.upsert(vectors=vectors_to_upsert) # Uncomment to actually upsert
print("Metadata structure for upserting shown.")

Filtering with Exact Matches

The simplest way to filter is to look for exact matches on a metadata field. You specify the field name and its desired value.

For example, to find all items with "genre": "fiction", you'd use {"genre": "fiction"} in your query's filter parameter.

from pinecone import Pinecone, Index
import os

# Assume index is already set up and has data
# pc = Pinecone(api_key=os.environ.get("PINECONE_API_KEY"))
# index = pc.Index("my-index")

# Query for items where genre is exactly 'fiction'
query_vector = [0.1, 0.2, 0.3] # Your query embedding

# results = index.query(
#     vector=query_vector,
#     top_k=3,
#     filter={"genre": "fiction"}
# )

print("Querying with filter: {'genre': 'fiction'}")
# print(results) # Uncomment to see results

Filtering by Ranges

You can also filter by numerical ranges using special Pinecone operators. These are useful for values like prices, dates, or ratings.

  • $gt: greater than
  • $gte: greater than or equal to
  • $lt: less than
  • $lte: less than or equal to

For example, {"price": {"$lt": 20.0}} finds items cheaper than $20.

from pinecone import Pinecone, Index
import os

# Assume index with 'price' metadata
# pc = Pinecone(api_key=os.environ.get("PINECONE_API_KEY"))
# index = pc.Index("my-index")

query_vector = [0.1, 0.2, 0.3]

# Find items published after 2022
# results = index.query(
#     vector=query_vector,
#     top_k=5,
#     filter={"year": {"$gt": 2022}}
# )

print("Querying with filter: {'year': {'$gt': 2022}}")
# print(results) # Uncomment to see results

Filtering with Lists

Sometimes you need to filter based on whether a value is present (or not present) in a list of options. Pinecone provides $in and $nin operators for this.

  • $in: value is one of the specified options.
  • $nin: value is NOT one of the specified options.

Example: {"category": {"$in": ["electronics", "clothing"]}}

from pinecone import Pinecone, Index
import os

# Assume index with 'tag' metadata
# pc = Pinecone(api_key=os.environ.get("PINECONE_API_KEY"))
# index = pc.Index("my-index")

query_vector = [0.1, 0.2, 0.3]

# Find items belonging to 'fiction' OR 'poetry'
# results = index.query(
#     vector=query_vector,
#     top_k=5,
#     filter={"genre": {"$in": ["fiction", "poetry"]}}
# )

print("Querying with filter: {'genre': {'$in': ['fiction', 'poetry']}}")
# print(results) # Uncomment to see results

Combining Filter Conditions

You can combine multiple filter conditions to create complex queries. By default, multiple conditions at the same level are treated as an AND operation.

For explicit OR operations, you use the $or operator. For example, to find items with category="books" AND price < 20:

from pinecone import Pinecone, Index
import os

# Assume index with 'category' and 'price' metadata
# pc = Pinecone(api_key=os.environ.get("PINECONE_API_KEY"))
# index = pc.Index("my-index")

query_vector = [0.1, 0.2, 0.3]

# Find books cheaper than $20 (AND operation)
# results = index.query(
#     vector=query_vector,
#     top_k=5,
#     filter={"category": "books", "price": {"$lt": 20.0}}
# )

print("Querying with filter: {'category': 'books', 'price': {'$lt': 20.0}}")
# print(results) # Uncomment to see results

Using $or for Flexible Filters

To perform an OR search, you use the $or operator. This operator takes a list of filter conditions, and if any of them are true, the item is included.

Example: Find items where category="electronics" OR category="home goods":

from pinecone import Pinecone, Index
import os

# Assume index with 'category' metadata
# pc = Pinecone(api_key=os.environ.get("PINECONE_API_KEY"))
# index = pc.Index("my-index")

query_vector = [0.1, 0.2, 0.3]

# Find items where category is 'electronics' OR 'home goods'
# results = index.query(
#     vector=query_vector,
#     top_k=5,
#     filter={
#         "$or": [
#             {"category": "electronics"},
#             {"category": "home goods"}
#         ]
#     }
# )

print("Querying with $or filter...")
# print(results) # Uncomment to see results

Advanced Combined Filters

You can combine $and (implicit or explicit) and $or operators for very powerful and specific filtering. This allows you to build complex search logic.

For example, to find items that are "fiction" AND ("published after 2020" OR "price under $15"):

from pinecone import Pinecone, Index
import os

# Assume index with 'genre', 'year', 'price' metadata
# pc = Pinecone(api_key=os.environ.get("PINECONE_API_KEY"))
# index = pc.Index("my-index")

query_vector = [0.1, 0.2, 0.3]

# Complex filter: fiction AND (year > 2020 OR price < 15)
# results = index.query(
#     vector=query_vector,
#     top_k=5,
#     filter={
#         "genre": "fiction",
#         "$or": [
#             {"year": {"$gt": 2020}},
#             {"price": {"$lt": 15.0}}
#         ]
#     }
# )

print("Querying with complex AND/OR filter...")
# print(results) # Uncomment to see results

Test Your Filtering Knowledge

Which Pinecone filter would you use to find items that are either in the "books" category or have a "rating" of at least 4.5?

Recap: Mastering Metadata Filters

Great job! You've learned how to use metadata to significantly enhance your similarity searches in Pinecone.

  • Metadata: Key-value pairs stored with your vectors.
  • Filter Types: Equality, range ($gt, $lt, etc.), and list ($in, $nin).
  • Combining Filters: Use implicit AND or explicit $or for complex logic.

Next, we'll explore how to organize your data even further using Pinecone's namespaces.

常见问题解答

「使用元数据进行筛选」课时是免费的吗?

是的 — 「使用元数据进行筛选」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Vector Databases: Pinecone, Weaviate & pgvector 课程的其余内容,请升级到 CoddyKit PRO。 Vector Databases: Pinecone, Weaviate & pgvector 课程共包含 4 节课。

「使用元数据进行筛选」这节课中我会学到什么?

利用元数据优化相似度搜索,为查询增加上下文约束。 你通过在浏览器中直接运行的动手代码来练习 Vector Databases: Pinecone, Weaviate & pgvector,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Vector Databases: Pinecone, Weaviate & pgvector 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Vector Databases: Pinecone, Weaviate & pgvector 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「使用元数据进行筛选」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Vector Databases: Pinecone, Weaviate & pgvector 课中编写并运行代码吗?

能。每节 Vector Databases: Pinecone, Weaviate & pgvector 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用元数据进行筛选
  2. 管理命名空间
  3. 实时更新与删除
  4. 使用稀疏向量与稠密向量进行混合搜索
← 返回 Vector Databases: Pinecone, Weaviate & pgvector