Files
mem0/docs/core-concepts/memory-operations/search.mdx
T

215 lines
6.3 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: Search Memory
description: Retrieve relevant memories from Mem0 using powerful semantic and filtered search capabilities.
icon: "magnifying-glass"
iconType: "solid"
---
# How Mem0 Searches Memory
Mem0’s search operation lets agents ask natural-language questions and get back the memories that matter most. It’s the bridge between everything you’ve stored and the next response your agent writes.
<Info>
**Why it matters**
- Retrieves the right facts without rebuilding prompts from scratch.
- Supports both managed Platform and OSS so you can test locally and deploy at scale.
- Keeps results relevant with filters, rerankers, and thresholds.
</Info>
## Key terms
- **Query** – Natural-language question or statement you pass to `search`.
- **Filters** – JSON logic (AND/OR, comparison operators) that narrows results by user, categories, dates, etc.
- **top_k / threshold** – Controls how many memories return and the minimum similarity score.
- **Rerank** – Optional second pass that boosts precision when a reranker is configured.
## Architecture
<Frame caption="Architecture diagram illustrating the memory search process.">
<img src="../../images/search_architecture.png" />
</Frame>
<Steps>
<Step title="Query processing">
Mem0 cleans and enriches your natural-language query so the downstream embedding search is accurate.
</Step>
<Step title="Vector search">
Embeddings locate the closest memories using cosine similarity across your scoped dataset.
</Step>
<Step title="Filtering & reranking">
Logical filters narrow candidates; rerankers or thresholds fine-tune ordering.
</Step>
<Step title="Results delivery">
Formatted memories (with metadata and timestamps) return to your agent or calling service.
</Step>
</Steps>
This pipeline runs the same way for the hosted Platform API and the OSS SDK.
---
## Search with Mem0 Platform
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
query = "What do you know about me?"
filters = {
"OR": [
{"user_id": "alice"},
{"agent_id": {"in": ["travel-assistant", "customer-support"]}}
]
}
results = client.search(query, filters=filters)
```
```javascript JavaScript
import { MemoryClient } from "mem0ai";
const client = new MemoryClient({apiKey: "your-api-key"});
const query = "I'm craving some pizza. Any recommendations?";
const filters = {
AND: [
{ user_id: "alice" }
]
};
const results = await client.search(query, {
filters
});
```
</CodeGroup>
---
## Search with Mem0 Open Source
<CodeGroup>
```python Python
from mem0 import Memory
m = Memory()
# Simple search
related_memories = m.search("Should I drink coffee or tea?", user_id="alice")
# Search with filters
memories = m.search(
"food preferences",
user_id="alice",
filters={"categories": {"contains": "diet"}}
)
```
```javascript JavaScript
import { Memory } from 'mem0ai/oss';
const memory = new Memory();
// Simple search
const relatedMemories = memory.search("Should I drink coffee or tea?", { userId: "alice" });
// Search with filters (if supported)
const memories = memory.search("food preferences", {
userId: "alice",
filters: { categories: { contains: "diet" } }
});
```
</CodeGroup>
---
<Info icon="check">
Expect an array of memory documents. Platform responses include vectors, metadata, and timestamps; OSS returns your stored schema.
</Info>
## Filter patterns
Filters help narrow down search results. Common use cases:
**Filter by Session Context:**
```python
# Get memories from a specific agent session
m.search("query", user_id="alice", agent_id="chatbot", run_id="session-123")
```
**Filter by Date Range:**
```python
# Platform only - date filtering
client.search("recent memories", filters={
"AND": [
{"user_id": "alice"},
{"created_at": {"gte": "2024-07-01"}}
]
})
```
**Filter by Categories:**
```python
# Platform only - category filtering
client.search("preferences", filters={
"AND": [
{"user_id": "alice"},
{"categories": {"contains": "food"}}
]
})
```
---
## Tips for better search
- **Use natural language**: Mem0 understands intent, so describe what you're looking for naturally
- **Scope with session IDs**: Always provide at least `user_id` to scope search to relevant memories
- **Combine filters**: Use AND/OR logic to create precise queries (Platform)
- **Consider wildcard filters**: Use wildcard filters (e.g., `run_id: "*"`) for broader matches
- **Tune parameters**: Adjust `top_k` for result count, `threshold` for relevance cutoff
- **Enable reranking**: Use `rerank=True` (default) when you have a reranker configured
### More Details
For the full list of filter logic, comparison operators, and optional search parameters, see the
[Search Memory API Reference](/api-reference/memory/search-memories).
## Managed vs OSS differences
| Capability | Mem0 Platform | Mem0 OSS |
| --- | --- | --- |
| Filters | Logical operators (`AND`, `OR`, comparisons) with field-level access | Basic field filters, extend via Python hooks |
| Reranking | Toggle `rerank=True` with managed reranker catalog | Requires configuring local or third-party rerankers |
| Thresholds | Request-level configuration (`threshold`, `top_k`) | Controlled via SDK parameters |
| Response metadata | Includes confidence scores, timestamps, dashboard visibility | Determined by your storage backend |
## Put it into practice
- Revisit the <Link href="/core-concepts/memory-operations/add">Add Memory</Link> guide to ensure you capture the context you expect to retrieve.
- Configure rerankers and filters in <Link href="/platform/features/advanced-retrieval">Advanced Retrieval</Link> for higher precision.
## See it live
- <Link href="/cookbooks/operations/support-inbox">Support Inbox with Mem0</Link> demonstrates scoped search with rerankers.
- <Link href="/cookbooks/integrations/tavily-search">Tavily Search with Mem0</Link> shows hybrid search in action.
{/* DEBUG: verify CTA targets */}
<CardGroup cols={2}>
<Card
title="Tune Update Concepts"
description="Learn how to adjust memories after search results come back."
icon="pencil"
href="/core-concepts/memory-operations/update"
/>
<Card
title="Build Hybrid Search"
description="Follow the cookbook to combine Mem0 with external search."
icon="rocket"
href="/cookbooks/integrations/tavily-search"
/>
</CardGroup>