> ## Documentation Index
> Fetch the complete documentation index at: https://honcho.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Using Filters

> Learn how to filter workspaces, peers, sessions, and messages using Honcho's powerful filtering system

Honcho provides a sophisticated filtering system that allows you to query workspaces, peers, sessions, and messages with precise control. The filtering system supports logical operators, comparison operators, metadata filtering, and wildcards to help you find exactly what you need.

## Basic Filtering Concepts

Filters in Honcho are expressed as dictionaries that define conditions for matching resources. The system supports both simple equality filters and complex queries with multiple conditions.

### Simple Filters

The most basic filters check for exact matches:

<CodeGroup>
  ```python Python theme={null}
  from honcho import Honcho

  # Initialize client
  honcho = Honcho()

  # Simple peer filter
  peers = honcho.peers(filters={"peer_id": "alice"})

  # Simple session filter with metadata
  sessions = honcho.sessions(filters={
      "metadata": {"type": "support"}
  })

  # Simple message filter
  messages = honcho.messages(filters={
      "session_id": "support-chat-1",
      "peer_id": "alice"
  })
  ```

  ```typescript TypeScript theme={null}
  import { Honcho } from "@honcho-ai/sdk";

  (async () => {
      // Initialize client
      const honcho = new Honcho({});

      // Simple peer filter
      const peers = await honcho.peers({
        filters: { peer_id: "alice" }
      });

      // Simple session filter with metadata
      const sessions = await honcho.sessions({
        filters: {
          metadata: { type: "support" }
        }
      });

      // Simple message filter
      const messages = await honcho.messages({
        filters: {
          session_id: "support-chat-1",
          peer_id: "alice"
        }
      });
  })();
  ```
</CodeGroup>

## Logical Operators

Combine multiple conditions using logical operators for complex queries:

### AND Operator

Use AND to require all conditions to be true:

<CodeGroup>
  ```python Python theme={null}
  messages = honcho.messages(filters={
      "AND": [
          {"session_id": "chat-1"},
          {"created_at": {"gte": "2024-01-01"}}
      ]
  })
  ```

  ```typescript TypeScript theme={null}
  (async () => {
      const messages = await honcho.messages({
        filters: {
          AND: [
            { session_id: "chat-1" },
            { created_at: { gte: "2024-01-01" } }
          ]
        }
      });
  })();
  ```
</CodeGroup>

### OR Operator

Use OR to match any of the specified conditions:

<CodeGroup>
  ```python Python theme={null}
  # Find messages from either alice or bob
  messages = session.messages(filters={
      "OR": [
          {"peer_id": "alice"},
          {"peer_id": "bob"}
      ]
  })

  # Complex OR with metadata conditions
  sessions = honcho.sessions(filters={
      "OR": [
          {"metadata": {"priority": "high"}},
          {"metadata": {"urgent": True}},
          {"metadata": {"escalated": True}}
      ]
  })
  ```

  ```typescript TypeScript theme={null}
  (async () => {
      // Find messages from either alice or bob
      const messages = await session.messages({
        filters: {
          OR: [
            { peer_id: "alice" },
            { peer_id: "bob" }
          ]
        }
      });

      // Complex OR with metadata conditions
      const sessions = await honcho.sessions({
        filters: {
          OR: [
            { metadata: { priority: "high" } },
            { metadata: { urgent: true } },
            { metadata: { escalated: true } }
          ]
        }
      });
  })();
  ```
</CodeGroup>

### NOT Operator

Use NOT to exclude specific conditions:

<CodeGroup>
  ```python Python theme={null}
  # Find all peers except alice
  peers = honcho.peers(filters={
      "NOT": [
          {"peer_id": "alice"}
      ]
  })

  # Find sessions that are NOT completed
  sessions = honcho.sessions(filters={
      "NOT": [
          {"metadata": {"status": "completed"}}
      ]
  })
  ```

  ```typescript TypeScript theme={null}
  (async () => {
      // Find all peers except alice
      const peers = await honcho.peers({
        filters: {
          NOT: [
            { peer_id: "alice" }
          ]
        }
      });

      // Find sessions that are NOT completed
      const sessions = await honcho.sessions({
        filters: {
          NOT: [
            { metadata: { status: "completed" } }
          ]
        }
      });
  })();
  ```
</CodeGroup>

### Combining Logical Operators

Create sophisticated queries by combining different logical operators:

<CodeGroup>
  ```python Python theme={null}
  # Find messages from alice OR bob, but NOT where message has archived set to true in metadata
  messages = session.messages(filters={
      "AND": [
          {
              "OR": [
                  {"peer_id": "alice"},
                  {"peer_id": "bob"}
              ]
          },
          {
              "NOT": [
                  {"metadata": {"archived": True}}
              ]
          }
      ]
  })
  ```

  ```typescript TypeScript theme={null}
  (async () => {
      // Find messages from alice OR bob, but NOT where message has archived set to true in metadata
      const messages = await session.messages({
        filters: {
          AND: [
            {
              OR: [
                { peer_id: "alice" },
                { peer_id: "bob" }
              ]
            },
            {
              NOT: [
                { metadata: { archived: true } }
              ]
            }
          ]
        }
      });
  })();
  ```
</CodeGroup>

## Comparison Operators

Use comparison operators for range queries and advanced matching:

### Numeric Comparisons

<CodeGroup>
  ```python Python theme={null}
  # Find sessions created after a specific date
  sessions = honcho.sessions(filters={
      "created_at": {"gte": "2024-01-01"}
  })

  # Find messages within a date range
  messages = session.messages(filters={
      "created_at": {
          "gte": "2024-01-01",
          "lte": "2024-12-31"
      }
  })

  # Metadata numeric comparisons
  sessions = honcho.sessions(filters={
      "metadata": {
          "score": {"gt": 8.5},
          "duration": {"lte": 3600}
      }
  })
  ```

  ```typescript TypeScript theme={null}
  (async () => {
      // Find sessions created after a specific date
      const sessions = await honcho.sessions({
        filters: {
          created_at: { gte: "2024-01-01" }
        }
      });

      // Find messages within a date range
      const messages = await session.messages({
        filters: {
          created_at: {
            gte: "2024-01-01",
            lte: "2024-12-31"
          }
        }
      });

      // Metadata numeric comparisons
      const filteredSessions = await honcho.sessions({
        filters: {
          metadata: {
            score: { gt: 8.5 },
            duration: { lte: 3600 }
          }
        }
      });
  })();
  ```
</CodeGroup>

### List Membership

<CodeGroup>
  ```python Python theme={null}
  # Find messages from specific peers in a session
  messages = session.messages(filters={
      "peer_id": {"in": ["alice", "bob", "charlie"]}
  })

  # Find sessions with specific tags
  sessions = honcho.sessions(filters={
      "metadata": {
          "tag": {"in": ["important", "urgent", "follow-up"]}
      }
  })

  # Not equal comparisons
  peers = honcho.peers(filters={
      "metadata": {
          "status": {"ne": "inactive"}
      }
  })
  ```

  ```typescript TypeScript theme={null}
  (async () => {
      // Find messages from specific peers in a session
      const messages = await session.messages({
        filters: {
          peer_id: { in: ["alice", "bob", "charlie"] }
        }
      });

      // Find sessions with specific tags
      const sessions = await honcho.sessions({
        filters: {
          metadata: {
            tag: { in: ["important", "urgent", "follow-up"] }
          }
        }
      });

      // Not equal comparisons
      const peers = await honcho.peers({
        filters: {
          metadata: {
            status: { ne: "inactive" }
          }
        }
      });
  })();
  ```
</CodeGroup>

## Metadata Filtering

Metadata filtering is particularly powerful in Honcho, supporting nested conditions and complex queries:

### Basic Metadata Filtering

<CodeGroup>
  ```python Python theme={null}
  # Simple metadata equality
  sessions = honcho.sessions(filters={
      "metadata": {
          "type": "customer_support",
          "priority": "high"
      }
  })

  # Nested metadata objects
  peers = honcho.peers(filters={
      "metadata": {
          "profile": {
              "role": "admin",
              "department": "engineering"
          }
      }
  })
  ```

  ```typescript TypeScript theme={null}
  (async () => {
      // Simple metadata equality
      const sessions = await honcho.sessions({
        filters: {
          metadata: {
            type: "customer_support",
            priority: "high"
          }
        }
      });

      // Nested metadata objects
      const peers = await honcho.peers({
        filters: {
          metadata: {
            profile: {
              role: "admin",
              department: "engineering"
            }
          }
        }
      });
  })();
  ```
</CodeGroup>

### Advanced Metadata Queries

<Info>
  If you want to do advanced queries like these, make sure not to create metadata fields that use the same names as the included comparison operators! For example, if you have a metadata field called `contains`, it will conflict with the `contains` operator.
</Info>

<CodeGroup>
  ```python Python theme={null}
  # Metadata with comparison operators
  sessions = honcho.sessions(filters={
      "metadata": {
          "score": {"gte": 4.0, "lte": 5.0},
          "created_by": {"ne": "system"},
          "tags": {"contains": "important"}
      }
  })

  # Complex metadata conditions
  messages = session.messages(filters={
      "AND": [
          {"metadata": {"sentiment": {"in": ["positive", "neutral"]}}},
          {"metadata": {"confidence": {"gt": 0.8}}},
          {"content": {"icontains": "thank"}}
      ]
  })
  ```

  ```typescript TypeScript theme={null}
  (async () => {
      // Metadata with comparison operators
      const sessions = await honcho.sessions({
        filters: {
          metadata: {
            score: { gte: 4.0, lte: 5.0 },
            created_by: { ne: "system" },
            tags: { contains: "important" }
          }
        }
      });

      // Complex metadata conditions
      const messages = await session.messages({
        filters: {
          AND: [
            { metadata: { sentiment: { in: ["positive", "neutral"] } } },
            { metadata: { confidence: { gt: 0.8 } } },
            { content: { icontains: "thank" } }
          ]
        }
      });
  })();
  ```
</CodeGroup>

## Wildcards

Use wildcards (\*) to match any value for a field:

<CodeGroup>
  ```python Python theme={null}
  # Find all sessions with any peer_id (essentially all sessions)
  sessions = honcho.sessions(filters={
      "peer_id": "*"
  })

  # Wildcard in lists - matches everything
  messages = session.messages(filters={
      "peer_id": {"in": ["alice", "bob", "*"]}
  })

  # Metadata wildcards
  sessions = honcho.sessions(filters={
      "metadata": {
          "type": "*",  # Any type
          "status": "active"  # But status must be active
      }
  })
  ```

  ```typescript TypeScript theme={null}
  (async () => {
      // Find all sessions with any peer_id (essentially all sessions)
      const sessions = await honcho.sessions({
        filters: {
          peer_id: "*"
        }
      });

      // Wildcard in lists - matches everything
      const messages = await session.messages({
        filters: {
          peer_id: { in: ["alice", "bob", "*"] }
        }
      });

      // Metadata wildcards
      const filteredSessions = await honcho.sessions({
        filters: {
          metadata: {
            type: "*",  // Any type
            status: "active"  // But status must be active
          }
        }
      });
  })();
  ```
</CodeGroup>

## Resource-Specific Examples

### Filtering Workspaces

<CodeGroup>
  ```python Python theme={null}
  # Find workspaces by name pattern
  workspaces = honcho.workspaces(filters={
      "name": {"contains": "prod"}
  })

  # Filter by metadata
  workspaces = honcho.workspaces(filters={
      "metadata": {
          "environment": "production",
          "team": {"in": ["backend", "frontend", "devops"]}
      }
  })
  ```

  ```typescript TypeScript theme={null}
  (async () => {
      // Find workspaces by name pattern
      const workspaces = await honcho.workspaces({
        filters: {
          name: { contains: "prod" }
        }
      });

      // Filter by metadata
      const workspaces = await honcho.workspaces({
        filters: {
          metadata: {
            environment: "production",
            team: { in: ["backend", "frontend", "devops"] }
          }
        }
      });
  })();
  ```
</CodeGroup>

### Filtering Messages

<CodeGroup>
  ```python Python theme={null}
  # Find error messages from the last week
  from datetime import datetime, timedelta

  week_ago = (datetime.now() - timedelta(days=7)).isoformat()
  messages = session.messages(filters={
      "AND": [
          {"content": {"icontains": "error"}},
          {"created_at": {"gte": week_ago}},
          {"metadata": {"level": {"in": ["error", "critical"]}}}
      ]
  })

  # Find messages in specific sessions with sentiment analysis
  messages = session.messages(filters={
      "AND": [
          {"session_id": {"in": ["support-1", "support-2", "support-3"]}},
          {"metadata": {"sentiment": "negative"}},
          {"metadata": {"confidence": {"gte": 0.7}}}
      ]
  })
  ```

  ```typescript TypeScript theme={null}
  (async () => {
      // Find error messages from the last week
      const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString();
      const messages = await session.messages({
        filters: {
          AND: [
            { content: { icontains: "error" } },
            { created_at: { gte: weekAgo } },
            { metadata: { level: { in: ["error", "critical"] } } }
          ]
        }
      });

      // Find messages in specific sessions with sentiment analysis
      const sentimentMessages = await session.messages({
        filters: {
          AND: [
            { session_id: { in: ["support-1", "support-2", "support-3"] } },
            { metadata: { sentiment: "negative" } },
            { metadata: { confidence: { gte: 0.7 } } }
          ]
        }
      });
  })();
  ```
</CodeGroup>

## Error Handling

Handle filter errors gracefully:

<CodeGroup>
  ```python Python theme={null}
  from honcho.exceptions import FilterError

  try:
      # Invalid filter - unsupported operator
      messages = session.messages(filters={
          "created_at": {"invalid_operator": "2024-01-01"}
      })
  except FilterError as e:
      print(f"Filter error: {e}")
      # Handle the error appropriately

  try:
      # Invalid column name
      sessions = honcho.sessions(filters={
          "nonexistent_field": "value"
      })
  except FilterError as e:
      print(f"Invalid field: {e}")
  ```

  ```typescript TypeScript theme={null}
  (async () => {
      try {
        // Invalid filter - unsupported operator
        const messages = await session.messages({
          filters: {
            created_at: { invalid_operator: "2024-01-01" }
          }
        });
      } catch (error) {
        if (error.message.includes("filters")) {
          console.error(`Filter error: ${error.message}`);
          // Handle the error appropriately
        }
      }

      try {
        // Invalid column name
        const sessions = await honcho.sessions({
          filters: {
            nonexistent_field: "value"
          }
        });
      } catch (error) {
        console.error(`Invalid field: ${error.message}`);
      }
  })();
  ```
</CodeGroup>

## Conclusion

Honcho's filtering system provides powerful capabilities for querying your conversational data. By understanding how to:

* Use simple equality filters and complex logical operators
* Apply comparison operators for range and pattern matching
* Filter metadata with nested conditions
* Handle wildcards and dynamic filter construction
* Follow best practices for performance and validation

You can build sophisticated applications that efficiently find and process exactly the conversations, messages, and insights you need from your Honcho data.
