메타데이터로 필터링하기
메타데이터를 활용해 유사도 검색을 세분화하고 질의에 컨텍스트 제약 조건을 추가합니다.
메타데이터로 필터링하기은(는) CoddyKit의 무료 Vector Databases: Pinecone, Weaviate & pgvector 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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 resultsFiltering 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 resultsFiltering 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 resultsCombining 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 resultsUsing $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 resultsAdvanced 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 resultsTest 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
$orfor complex logic.
Next, we'll explore how to organize your data even further using Pinecone's namespaces.
자주 묻는 질문
“메타데이터로 필터링하기” 강의는 무료인가요?
네 — “메타데이터로 필터링하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Vector Databases: Pinecone, Weaviate & pgvector 강의 전체를 잠금 해제할 수 있습니다. Vector Databases: Pinecone, Weaviate & pgvector 강의에는 총 4개의 강의가 포함되어 있습니다.
“메타데이터로 필터링하기”에서 뭘 배우나요?
메타데이터를 활용해 유사도 검색을 세분화하고 질의에 컨텍스트 제약 조건을 추가합니다. 브라우저에서 직접 실행하는 실습 코드로 Vector Databases: Pinecone, Weaviate & pgvector을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Vector Databases: Pinecone, Weaviate & pgvector을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Vector Databases: Pinecone, Weaviate & pgvector은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“메타데이터로 필터링하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Vector Databases: Pinecone, Weaviate & pgvector 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Vector Databases: Pinecone, Weaviate & pgvector 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.