Searching Memories with Mem0 search() Operation

Searching Memories with Mem0 search() Operation

Effective memory retrieval is key to building AI applications that provide contextually relevant responses. Mem0's search() operation is your gateway to accessing stored memories intelligently. In this guide, we'll explore how to use client.search() effectively, from basic queries to advanced filtering techniques.

Basic Search Operations

The syntax of the search operation is:

client.search(
    query,              # Required: What you're searching for
    user_id=None,       # Optional: Specific user's memories
    agent_id=None,      # Optional: Specific agent's memories
    limit=10,           # Optional: Maximum number of results
    output_format="v1.0" # Optional: Format version (defaults to "v1.0")
)

Simple Search Example

# Basic search for a user's memorie
memories = client.search(
    query="What are Jordan's dietary preferences?",
    user_id="jordan",
)

Understanding Output Formats

Mem0 supports two output formats for search results:

V1.0 (Default) Output Structure

[
    {
        "id": "9d432f8e-c522-4bfe-a8d3-45678c83d5b6",
        "memory": "Follows a keto diet. Cannot eat gluten.",
        "input": [
            {
                "role": "user",
                "content": "Hi! Just wanted to let you know I follow a strict keto diet and I have celiac disease, so I can't eat anything with gluten."
            },
            {
                "role": "assistant",
                "content": "Thank you for letting me know, Jordan! I'll make sure to recommend only keto-friendly and gluten-free recipes and ingredients."
            }
        ],
        "user_id": "jordan",
        "hash": "8dd5e2366f93d2dab811ed8639bcd65b",
        "metadata": null,
        "created_at": "2024-03-15T14:22:45.123456-07:00",
        "updated_at": "2024-03-15T14:22:45.123486-07:00"
    },
    {
        "id": "7c321e9d-b433-4cfe-b9d2-34567b72d4c5",
        "memory": "Prefers spicy food. Favorite cuisine is Thai.",
        "input": [
            {
                "role": "user",
                "content": "I love spicy food! Thai cuisine is my absolute favorite."
            },
            {
                "role": "assistant",
                "content": "I'll remember your love for spicy food and Thai cuisine, Jordan. I can help you find keto-friendly Thai recipes that pack some heat!"
            }
        ],
        "user_id": "jordan",
        "hash": "7cc4d1244d73c1cab700dc7638bde64a",
        "metadata": null,
        "created_at": "2024-03-15T14:25:12.345678-07:00",
        "updated_at": "2024-03-15T14:25:12.345698-07:00"
    }
]

v1.0 returns a list of memory dictionaries.

V1.1 Enhanced Output

{
    "results": [
        {
            "id": "7f165f7e-b411-4afe-b7e5-35789b72c4a5",
            "memory": "Vegetarian. Allergic to nuts.",
            "input": [
                {
                    "role": "user",
                    "content": "Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts."
                },
                {
                    "role": "assistant",
                    "content": "Hello Alex! I've noted that you're a vegetarian and have a nut allergy. I'll keep this in mind for any food-related recommendations or discussions."
                }
            ],
            "user_id": "alex",
            "hash": "9ee7e1455e84d1dab700ed8749aed75a",
            "metadata": null,
            "created_at": "2024-07-20T01:30:36.275141-07:00",
            "updated_at": "2024-07-20T01:30:36.275172-07:00"
        }
    ]
}

The main structural difference is that v1.1 adds a wrapper dict with a "results" key, while v1.0 returns the list directly. The individual memory objects inside maintain the same structure in both formats. This wrapper in v1.1 could be useful if you need to add additional metadata about the search results in the future while maintaining backwards compatibility.

Advanced Search Features

Mem0's v2 search API provides powerful filtering capabilities that allow you to precisely target the memories you need. These advanced features help you narrow down search results based on multiple criteria, time ranges, and complex logical conditions.

1. Using Version 2 Filters

Version 2 filters enable you to combine multiple search conditions using logical operators. This is particularly useful when you need to find memories that match several specific criteria simultaneously. In this example, we're searching for memories that belong to a specific user AND were created by either the travel assistant or customer support agent:

query = "What are Sarah's music preferences?"

filters = {
   "AND": [
       {
           "user_id": "sarah"
       },
       {
           "agent_id": {
               "in": [
                   "music-assistant",
                   "entertainment-bot"
               ]
           }
       }
   ]
}

results = client.search(
   query=query,
   version="v2",
   filters=filters
)

# Example response:
[
   {
       "id": "4d893f6e-c433-4efe-b8d3-89012c83d5b6",
       "memory": "Prefers jazz and classical music. Pianist.",
       "input": [
           {
               "role": "user",
               "content": "I mainly listen to jazz and classical. I play piano too, so I especially love piano concertos."
           },
           {
               "role": "assistant",
               "content": "I'll remember your preference for jazz and classical music, particularly piano concertos. This will help me make more relevant music recommendations."
           }
       ],
       "user_id": "sarah",
       "agent_id": "music-assistant",
       "hash": "4aa3b1233c62b1bab600cb6527abc432",
       "created_at": "2024-03-15T08:15:30.123456-07:00",
       "updated_at": "2024-03-15T08:15:30.123486-07:00"
   }
]

2. Date-Based Filtering

When you need to search for memories within specific time periods, date-based filtering allows you to set date ranges using "gte" (greater than or equal to) and "lte" (less than or equal to) operators. This is valuable for analyzing historical data or focusing on recent interactions:

# Search within a date range
filters = {
    "AND": [
        {
            "created_at": {
                "gte": "2024-03-01",
                "lte": "2024-03-31"
            }
        },
        {
            "user_id": "sarah"
        }
    ]
}

results = client.search(
    query="What are Sarah's concert preferences?",
    version="v2",
    filters=filters
)

# Example response:
[
    {
        "id": "7c321e9d-b433-4cfe-b9d2-34567b72d4c5",
        "memory": "Prefers orchestra seats, center section. Attends evening concerts only.",
        "input": [
            {
                "role": "user",
                "content": "When booking concert tickets, I always want orchestra seats in the center. I can only attend evening shows after 7pm."
            },
            {
                "role": "assistant",
                "content": "I've noted your preference for center orchestra seats and evening concerts after 7pm for future ticket bookings."
            }
        ],
        "user_id": "sarah",
        "hash": "7cc4d1244d73c1cab700dc7638bde64a",
        "created_at": "2024-03-15T14:25:12.345678-07:00",
        "updated_at": "2024-03-15T14:25:12.345698-07:00"
    }
]

These advanced search filters give you greater control over memory retrieval, allowing you to build more sophisticated and context-aware AI applications.

Conclusion

The client.search() operation is a powerful tool for retrieving relevant memories from your Mem0 instance. By understanding its features and following best practices, you can build AI applications that effectively use past interactions to provide more personalized and context-aware responses. Remember to use appropriate output formats for your needs and leverage v2 filters for complex queries.

View Mem0's documentation to learn more about integrating our memory features. You can also reach out to us at founders@mem0.ai.