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

# Graph Search & Logic Mesh

> Query entity relationships and traverse knowledge graphs extracted from your documents

Logic Mesh extracts entity-relationship graphs from your documents, enabling powerful graph traversal and relationship-aware search. Instead of just finding documents that mention "John", you can ask "Who reports to John?" or "What companies has John worked at?"

***

## What is Logic Mesh?

Logic Mesh automatically extracts:

* **Entities**: People, companies, products, concepts
* **Relationships**: works\_at, reports\_to, founded, acquired, etc.
* **Properties**: Attributes attached to entities

```mermaid theme={null}
graph TD
    A[John Smith] -->|works_at| B[Acme Corp]
    A -->|reports_to| C[Jane Doe]
    B -->|acquired| D[StartupXYZ]
```

***

## Enabling Logic Mesh

### During Ingestion

```bash theme={null}
# Enable entity-relationship extraction
memvid put memory.mv2 --input documents/ --logic-mesh
```

### For Existing Memories

```bash theme={null}
# Enrich existing documents with graph extraction
memvid enrich memory.mv2 --engine groq
```

<Note>
  Logic Mesh extraction requires an enrichment engine. Use `--logic-mesh` during ingestion or run `memvid enrich` afterward.
</Note>

***

## Graph Traversal Commands

### List All Entities

```bash theme={null}
# Show all extracted entities
memvid follow entities memory.mv2

# Filter by entity type
memvid follow entities memory.mv2 --kind person
memvid follow entities memory.mv2 --kind company
memvid follow entities memory.mv2 --kind product

# Search entities by name
memvid follow entities memory.mv2 --query "John"

# Limit results
memvid follow entities memory.mv2 --limit 20

# JSON output
memvid follow entities memory.mv2 --json
```

Output:

```
Entities (87 total)

People:
  - John Smith (34 relationships)
  - Jane Doe (28 relationships)
  - Sarah Chen (19 relationships)

Companies:
  - Acme Corp (45 relationships)
  - StartupXYZ (12 relationships)
  - TechGiant Inc (8 relationships)

Products:
  - Project Alpha (15 relationships)
  - Platform v2 (9 relationships)
```

### Traverse Relationships

```bash theme={null}
# Find what John Smith is connected to
memvid follow traverse memory.mv2 --start "John Smith"

# Follow specific relationship type
memvid follow traverse memory.mv2 --start "John Smith" --link works_at

# Control traversal depth (default: 2)
memvid follow traverse memory.mv2 --start "Acme Corp" --hops 3

# Direction: outgoing, incoming, or both
memvid follow traverse memory.mv2 --start "Jane Doe" --direction incoming
```

Output:

```
Traversal from: John Smith (depth: 2)

Direct relationships (hop 1):
  ──[works_at]──▶ Acme Corp
  ──[reports_to]──▶ Jane Doe
  ──[leads]──▶ Project Alpha
  ──[expertise]──▶ Rust, Python

Extended relationships (hop 2):
  Acme Corp ──[acquired]──▶ StartupXYZ
  Acme Corp ──[headquartered_in]──▶ San Francisco
  Jane Doe ──[reports_to]──▶ CEO Board
  Project Alpha ──[uses]──▶ Platform v2
```

### Graph Statistics

```bash theme={null}
memvid follow stats memory.mv2
```

Output:

```
Logic Mesh Statistics

Entities: 87
  - person: 34
  - company: 18
  - product: 15
  - concept: 20

Relationships: 423
  - works_at: 45
  - reports_to: 32
  - founded: 12
  - acquired: 8
  - uses: 56
  - expertise: 89
  - other: 181

Graph density: 4.86 edges/node
Connected components: 3
Largest component: 72 entities
```

***

## Triple Patterns

Query relationships using **Subject:Predicate:Object** patterns with `?` as a wildcard:

| Pattern             | Meaning                      |
| ------------------- | ---------------------------- |
| `John:works_at:?`   | Where does John work?        |
| `?:CEO:Acme`        | Who is CEO of Acme?          |
| `?:works_at:Acme`   | Who works at Acme?           |
| `John:?:Acme`       | How is John related to Acme? |
| `?:reports_to:Jane` | Who reports to Jane?         |

### CLI Usage

```bash theme={null}
# Find where John works
memvid find memory.mv2 --graph "John Smith:works_at:?"

# Find who works at Acme
memvid find memory.mv2 --graph "?:works_at:Acme Corp"

# Find all relationships between two entities
memvid find memory.mv2 --graph "John Smith:?:Acme Corp"
```

***

## Combining Graph + Text Search

The real power of Logic Mesh is combining graph traversal with text search.

### Graph-Filtered Search

Filter search results by relationships first, then rank by text relevance:

```bash theme={null}
# Find revenue info, but only from Acme-related documents
memvid find memory.mv2 --query "revenue" --graph "?:works_at:Acme Corp"

# Find meeting notes involving John
memvid find memory.mv2 --query "meeting notes" --graph "John Smith:?:?"
```

### Hybrid Graph + Semantic Search

Combine graph traversal with vector similarity:

```bash theme={null}
# Semantic search within a relationship context
memvid find memory.mv2 --query "Q4 results" --hybrid --graph "?:works_at:Acme"

# Find similar documents to what relates to a topic
memvid find memory.mv2 --query "machine learning" --hybrid --graph "?:expertise:ML"
```

***

## Common Relationship Types

Logic Mesh automatically detects common relationships:

### Professional

| Relationship | Example                  |
| ------------ | ------------------------ |
| `works_at`   | John works\_at Acme      |
| `reports_to` | John reports\_to Jane    |
| `manages`    | Jane manages Engineering |
| `founded`    | Elon founded SpaceX      |
| `CEO`        | Tim CEO Apple            |

### Organizational

| Relationship       | Example                        |
| ------------------ | ------------------------------ |
| `acquired`         | Acme acquired StartupXYZ       |
| `partnered_with`   | Acme partnered\_with TechCo    |
| `subsidiary_of`    | StartupXYZ subsidiary\_of Acme |
| `headquartered_in` | Acme headquartered\_in SF      |

### Technical

| Relationship      | Example                          |
| ----------------- | -------------------------------- |
| `uses`            | Project uses React               |
| `depends_on`      | Service depends\_on Database     |
| `integrates_with` | Platform integrates\_with Stripe |
| `expertise`       | John expertise Rust              |

### Temporal

| Relationship | Example                      |
| ------------ | ---------------------------- |
| `started`    | Project started 2024-01      |
| `completed`  | Phase completed 2024-06      |
| `scheduled`  | Meeting scheduled 2024-12-15 |

***

## SDK Usage

### Python

```python theme={null}
from memvid import use

mem = use('basic', 'memory.mv2')

# Enable logic mesh during put
mem.put(
    text="John Smith works at Acme Corp as a Senior Engineer.",
    logic_mesh=True
)

# List entities
entities = mem.get_entities()
for entity in entities:
    print(f"{entity.name} ({entity.kind}): {entity.relationship_count} relationships")

# Traverse from an entity
graph = mem.traverse(
    start="John Smith",
    link="works_at",
    hops=2,
    direction="outgoing"
)

for node in graph.nodes:
    print(f"{node.name}: {node.relationships}")

# Graph-filtered search
results = mem.find(
    "quarterly report",
    graph_pattern="?:works_at:Acme Corp"
)

# Hybrid search
results = mem.find(
    "machine learning",
    hybrid=True,
    graph_pattern="?:expertise:ML"
)
```

### Node.js

```typescript theme={null}
import { use } from '@anthropics/memvid'

const mem = await use('basic', 'memory.mv2')

// Enable logic mesh during put
await mem.put({
  content: "John Smith works at Acme Corp as a Senior Engineer.",
  logicMesh: true
})

// List entities
const entities = await mem.getEntities()
for (const entity of entities) {
  console.log(`${entity.name} (${entity.kind}): ${entity.relationshipCount} relationships`)
}

// Traverse from an entity
const graph = await mem.traverse({
  start: "John Smith",
  link: "works_at",
  hops: 2,
  direction: "outgoing"
})

// Graph-filtered search
const results = await mem.find("quarterly report", {
  graphPattern: "?:works_at:Acme Corp"
})
```

***

## Advanced Patterns

### Multi-Hop Queries

Find entities connected through intermediate nodes:

```bash theme={null}
# Who do people at Acme report to? (2 hops)
memvid follow traverse memory.mv2 --start "Acme Corp" --link "works_at,reports_to" --hops 2

# Find the CEO through org chart
memvid follow traverse memory.mv2 --start "John Smith" --link "reports_to" --hops 5
```

### Compound Patterns

Combine multiple patterns:

```bash theme={null}
# Find people who work at Acme AND have ML expertise
memvid find memory.mv2 --graph "?:works_at:Acme Corp" --graph "?:expertise:ML"
```

### Negation (Exclusion)

Find entities NOT matching a pattern:

```bash theme={null}
# Find all employees except those reporting to Jane
memvid follow entities memory.mv2 --kind person --exclude-pattern "?:reports_to:Jane"
```

***

## Export Graph Data

### N-Triples (RDF)

```bash theme={null}
memvid export memory.mv2 --format ntriples --out graph.nt
```

```
<John_Smith> <works_at> <Acme_Corp> .
<John_Smith> <reports_to> <Jane_Doe> .
<John_Smith> <expertise> "Rust" .
<Acme_Corp> <acquired> <StartupXYZ> .
```

### JSON Graph

```bash theme={null}
memvid export memory.mv2 --format json --out graph.json
```

```json theme={null}
{
  "nodes": [
    {"id": "John_Smith", "kind": "person", "properties": {...}},
    {"id": "Acme_Corp", "kind": "company", "properties": {...}}
  ],
  "edges": [
    {"source": "John_Smith", "target": "Acme_Corp", "relation": "works_at"},
    {"source": "John_Smith", "target": "Jane_Doe", "relation": "reports_to"}
  ]
}
```

### CSV

```bash theme={null}
memvid export memory.mv2 --format csv --out graph.csv
```

```csv theme={null}
subject,predicate,object,confidence,source_frame
John_Smith,works_at,Acme_Corp,0.94,frame_001
John_Smith,reports_to,Jane_Doe,0.91,frame_001
Acme_Corp,acquired,StartupXYZ,0.88,frame_045
```

***

## Use Cases

### Organizational Knowledge

Map your company structure:

```bash theme={null}
# Ingest org documents
memvid put org.mv2 --input hr_docs/ --logic-mesh

# Find everyone's reporting structure
memvid follow traverse org.mv2 --start "CEO" --link "manages" --hops 5 --direction outgoing

# Who reports to a specific manager?
memvid find org.mv2 --graph "?:reports_to:Sarah Chen"
```

### Research Papers

Build citation and concept graphs:

```bash theme={null}
# Ingest papers
memvid put research.mv2 --input papers/ --logic-mesh

# Find papers citing a specific work
memvid find research.mv2 --graph "?:cites:Attention Is All You Need"

# Find concepts related to transformers
memvid follow traverse research.mv2 --start "Transformers" --hops 2
```

### Customer Data

Track customer relationships:

```bash theme={null}
# Find all contacts at a company
memvid find customers.mv2 --graph "?:works_at:BigCorp Inc"

# Find decision makers
memvid find customers.mv2 --graph "?:role:VP" --graph "?:works_at:BigCorp Inc"
```

### Code Documentation

Map code dependencies:

```bash theme={null}
# Find what depends on a module
memvid find codebase.mv2 --graph "?:imports:auth_module"

# Find all API endpoints
memvid follow entities codebase.mv2 --kind endpoint
```

***

## Performance Tips

### Index Recommendations

For large graphs (1000+ entities):

```bash theme={null}
# Build graph index for faster traversals
memvid doctor memory.mv2 --rebuild-logic-mesh
```

### Limit Traversal Depth

Deep traversals are expensive:

```bash theme={null}
# Default (recommended)
--hops 2

# Use sparingly
--hops 3 or higher
```

### Filter Early

Apply graph filters before text search:

```bash theme={null}
# Good: Graph filter narrows results first
memvid find memory.mv2 --graph "?:works_at:Acme" --query "report"

# Less efficient: Broad text search then filter
memvid find memory.mv2 --query "report" | grep Acme
```

***

## Troubleshooting

### "No entities found"

1. Ensure Logic Mesh is enabled:
   ```bash theme={null}
   memvid put memory.mv2 --input docs/ --logic-mesh
   ```

2. Run enrichment:
   ```bash theme={null}
   memvid enrich memory.mv2 --engine groq
   ```

3. Check stats:
   ```bash theme={null}
   memvid follow stats memory.mv2
   ```

### "Relationship not detected"

1. Content may be too ambiguous
2. Try a better enrichment engine:
   ```bash theme={null}
   memvid enrich memory.mv2 --engine claude --force
   ```

### "Traversal too slow"

1. Reduce hop depth
2. Rebuild logic mesh index:
   ```bash theme={null}
   memvid doctor memory.mv2 --rebuild-logic-mesh
   ```

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Memory Cards" icon="id-card" href="/concepts/memory-cards">
    Entity-attribute-value triples from enrichment
  </Card>

  <Card title="Entity Extraction" icon="brain" href="/concepts/entity-extraction">
    How entities are detected and classified
  </Card>
</CardGroup>
