How to beginner · 3 min read

Pinecone metadata filtering

Quick answer
Use Pinecone's filter parameter in the query method to apply metadata-based conditions for vector search. Filters support logical operators and nested conditions on metadata fields to refine search results efficiently.

PREREQUISITES

  • Python 3.8+
  • Pinecone API key
  • pip install pinecone-client

Setup

Install the Pinecone client and set your API key as an environment variable before running the code.

bash
pip install pinecone-client

Step by step

This example demonstrates how to initialize the Pinecone client, connect to an index, and perform a vector query with metadata filtering to return only vectors matching specific metadata criteria.

python
import os
import pinecone

# Initialize Pinecone client
pc = pinecone.Pinecone(api_key=os.environ["PINECONE_API_KEY"])

# Connect to your index
index = pc.Index("example-index")

# Example query vector (replace with your actual vector)
query_vector = [0.1, 0.2, 0.3, 0.4]

# Define metadata filter to match vectors where 'category' is 'books' and 'year' >= 2020
metadata_filter = {
    "$and": [
        {"category": {"$eq": "books"}},
        {"year": {"$gte": 2020}}
    ]
}

# Query with metadata filtering
response = index.query(
    vector=query_vector,
    top_k=5,
    filter=metadata_filter,
    include_metadata=True
)

# Print filtered results
for match in response.matches:
    print(f"ID: {match.id}, Score: {match.score}, Metadata: {match.metadata}")
output
ID: vector123, Score: 0.89, Metadata: {'category': 'books', 'year': 2021}
ID: vector456, Score: 0.85, Metadata: {'category': 'books', 'year': 2023}

Common variations

You can use different logical operators like $or, $not, and comparison operators such as $lt, $lte, $gt, and $ne in your metadata filters. Filters can be nested to create complex queries.

python
metadata_filter_or = {
    "$or": [
        {"category": {"$eq": "books"}},
        {"category": {"$eq": "electronics"}}
    ]
}

response_or = index.query(
    vector=query_vector,
    top_k=5,
    filter=metadata_filter_or,
    include_metadata=True
)

for match in response_or.matches:
    print(f"ID: {match.id}, Metadata: {match.metadata}")
output
ID: vector123, Metadata: {'category': 'books', 'year': 2021}
ID: vector789, Metadata: {'category': 'electronics', 'year': 2022}

Troubleshooting

  • If your filter returns no results, verify that the metadata fields and values exist exactly as specified in your index.
  • Ensure your index is up to date with the latest metadata for all vectors.
  • Check for syntax errors in your filter JSON structure.

Key Takeaways

  • Use the filter parameter in index.query() to apply metadata conditions.
  • Combine logical operators like $and and $or for complex filtering.
  • Always verify metadata keys and values match your filter criteria exactly.
  • Include include_metadata=True to retrieve metadata in query results.
Verified 2026-04
Verify ↗