Arc Labs
BrainDocsPricing
GitHubSign inGet Started
LearnGuides

Retrieval Strategy Selector

By Arc Labs Research·May 13, 2026·8 min read
TL;DR

Choose retrieval strategy based on query type: semantic for concept matching (e.g., "user preference"), temporal for time-based (e.g., "last 24 hours"), lexical for exact phrases (e.g., "error messages"), type-filtered for categories (e.g., "decisions only"), graph for relationships. Hybrid combines keyword + semantic for most agent loops.

The Problem: Which Retrieval Strategy?

Agent memory is only useful if you retrieve the right data. Asking the wrong way loses critical context:

  • Semantic only: You search for "user felt anxious" but memory stored "feeling of dread" as a keyword phrase. Miss it.
  • Keyword only: You search for "trading strategy" but memory stored similar concepts under different words. Semantic search would find them; keyword won't.
  • No time filtering: You retrieve "agent decision" and get a decision from 6 months ago, irrelevant to today's context.
  • No type filtering: You retrieve and get 100 results when you only want error outcomes, wasting tokens.

Brain offers 5 retrieval strategies, each optimized for a query type. This guide shows when to use each.

Decision Flowchart

START: What are you trying to retrieve?
├─ "Recent context (last 24 hours)"? → TEMPORAL
├─ "Exact phrase or keyword"? → LEXICAL
├─ "Category or type (errors, decisions)"? → TYPE-FILTERED
├─ "Relationships or causal chains"? → GRAPH
├─ "Conceptual match (similar ideas)"? → SEMANTIC
└─ "Everything above"? → HYBRID (Semantic + Lexical)

Retrieval Strategies

1. Semantic Retrieval

Use when: Concept matching, idea similarity, paraphrasing.

Example queries:

  • "How did the user feel about the last meeting?"
  • "What trading strategies worked well?"
  • "Similar customer complaints we've seen?"

How it works: Converts query to embedding, finds memories with similar embeddings.

Strengths:

  • Paraphrase-tolerant (query "felt sad" matches memory "depressed mood")
  • Multi-concept matching ("trading risk management" matches various risk concepts)
  • Domain-agnostic (works across any domain)

Weaknesses:

  • Ignores exact phrases ("find the word 'error'")
  • Slow for huge indexes (>100M vectors)

TypeScript example:

import { BrainClient, RecallBuilder } from "@brain-db/sdk";

const auth = { kind: "token", token: new TextEncoder().encode(process.env.BRAIN_API_KEY!) };
const client = await BrainClient.connect("127.0.0.1", 9090, { auth });

// Brain fuses the semantic, lexical, and graph retrievers on every recall (RRF) — there
// is no per-request mode flag; the semantic retriever is always one of the fused signals.
const answer = await client.recall(
  new RecallBuilder("How did the customer feel?").maxResults(5).build(),
);

console.log(answer.memories); // sentiment memories, matched by meaning even when worded differently

2. Temporal Retrieval

Use when: Time-based filtering, recency, session boundaries.

Example queries:

  • "All decisions made in the last 24 hours"
  • "Events from this month"
  • "Trading outcomes between 9am–5pm"

How it works: Filters memories by timestamp, then ranks by recency or relevance.

Strengths:

  • Precise time windows (no guessing)
  • Combines time + relevance (can add keyword/semantic on top)
  • Efficient even for large memory stores

Weaknesses:

  • Requires timestamp metadata
  • Not for fuzzy time ("around last week")

TypeScript example:

import { BrainClient, RecallBuilder } from "@brain-db/sdk";

const auth = { kind: "token", token: new TextEncoder().encode(process.env.BRAIN_API_KEY!) };
const client = await BrainClient.connect("127.0.0.1", 9090, { auth });

// Recency is a first-class fusion signal on every recall — Brain weights recent memories
// up server-side, so you express recency in the query rather than passing a time filter.
const answer = await client.recall(
  new RecallBuilder("recent trading outcomes").maxResults(10).build(),
);

console.log(answer.memories); // trading outcomes, recency-weighted by the fusion ranker

3. Lexical Retrieval

Use when: Exact phrases, keywords, boolean logic.

Example queries:

  • "Find the word 'error' in memories"
  • "All memories tagged 'critical'"
  • "Customer name contains 'Smith'"

How it works: Full-text search (BM25), tokenizes and matches terms.

Strengths:

  • Exact phrase matching (no approximation)
  • Fast for keyword searches
  • Boolean logic support (AND, OR, NOT)

Weaknesses:

  • Requires exact words or known terminology
  • Misses paraphrases ("felt sad" ≠ "depressed")

TypeScript example:

import { BrainClient, RecallBuilder } from "@brain-db/sdk";

const auth = { kind: "token", token: new TextEncoder().encode(process.env.BRAIN_API_KEY!) };
const client = await BrainClient.connect("127.0.0.1", 9090, { auth });

// The lexical (BM25 / tantivy) retriever runs on every recall and is fused with the rest,
// so exact terms in the query text score highly without a separate keyword mode.
const answer = await client.recall(
  new RecallBuilder("error timeout").maxResults(10).build(),
);

console.log(answer.memories); // memories where the exact terms score highly

4. Type-Filtered Retrieval

Use when: Category filtering, memory types, outcome filtering.

Example queries:

  • "All failed trades only"
  • "Decisions made by the user (exclude observations)"
  • "Error events, not warnings"

How it works: Filters by type metadata field, then retrieves within that type.

Strengths:

  • Clean categorical filtering
  • Reduces noise (exclude irrelevant memory types)
  • Efficient metadata queries

Weaknesses:

  • Requires structured type metadata
  • Can't filter on undefined types

TypeScript example:

import { BrainClient, RecallBuilder } from "@brain-db/sdk";

const auth = { kind: "token", token: new TextEncoder().encode(process.env.BRAIN_API_KEY!) };
const client = await BrainClient.connect("127.0.0.1", 9090, { auth });

// Brain has no client-side type filter — memory types live in the server's typed graph.
// Name the category in the query text and the extractor/typed-graph resolves it server-side.
const answer = await client.recall(
  new RecallBuilder("decisions about trading strategies").maxResults(5).build(),
);

console.log(answer.memories);

5. Graph Retrieval

Use when: Relationships, causal chains, entailment.

Example queries:

  • "What caused this error?"
  • "What did the agent decide as a result of this observation?"
  • "Trace the causal chain leading to this outcome"

How it works: Traverses relationships in graph (edge: "causedBy", "resultedIn", "leadsTo").

Strengths:

  • Captures causality (not just similarity)
  • Multi-hop reasoning (A → B → C)
  • Avoids spurious correlations

Weaknesses:

  • Requires graph relationships (edges) in schema
  • Slower for deep graphs

TypeScript example:

import { BrainClient, RecallBuilder } from "@brain-db/sdk";

const auth = { kind: "token", token: new TextEncoder().encode(process.env.BRAIN_API_KEY!) };
const client = await BrainClient.connect("127.0.0.1", 9090, { auth });

// The graph retriever expands entity/relation neighbors server-side (anchor -> BFS over the
// typed graph) and fuses them in — there is no client-side hop/relationship-type control.
const answer = await client.recall(
  new RecallBuilder("root cause of loss on 2026-05-12").maxResults(5).build(),
);

console.log(answer.memories); // causal chain surfaced via graph expansion + fusion

When to Use Each: Decision Table

ScenarioStrategyExample
"What did the user like?" (paraphrasing ok)SemanticQuery "prefer", Memory "enjoy" → Match ✓
"Last 10 decisions" (time-bounded)TemporalFilter by timestamp > now - 24h, rank by recency
"Find error logs" (exact keyword)LexicalQuery "error", Memory "error: 500" → Match ✓
"Only failed trades" (category filter)Type-FilteredFilter by type = "trade_outcome" AND outcome = "loss"
"Why did this fail?" (causality)GraphStart at "Trade Loss", follow "causedBy" edges
"Everything: recent + semantic + keyword"HybridTemporal window + semantic + lexical in one query

Hybrid Retrieval (the default — and the only mode)

Every Brain recall is hybrid. The semantic, lexical, and graph retrievers all run, their ranks fuse via RRF, and a cross-encoder reranks the result — with recency and typed-graph signals folded in server-side. There is no mode to select and no client-side filter DSL; you express intent in the query text.

TypeScript:

const answer = await client.recall(
  new RecallBuilder("recent user coffee preferences").maxResults(5).build(),
);

This retrieves memories that are:

  • Semantically similar to "user coffee preferences"
  • Strong on the exact query terms (lexical)
  • Connected in the typed graph (graph expansion)
  • Recency-weighted by the fusion ranker

Implementation Examples

Trading Agent: Market Context

import { BrainClient, RecallBuilder } from "@brain-db/sdk";

const auth = { kind: "token", token: new TextEncoder().encode(process.env.BRAIN_API_KEY!) };
const client = await BrainClient.connect("127.0.0.1", 9090, { auth });

// Identity (namespace + space) rides the brain_ token, so there is no spaceId argument.
async function getMarketContext(symbol: string) {
  // 1. Recent market observations (recency is fused in automatically)
  const marketFacts = await client.recall(
    new RecallBuilder(`recent market conditions for ${symbol}`).maxResults(5).build(),
  );

  // 2. Similar past market conditions
  const similarConditions = await client.recall(
    new RecallBuilder(`${symbol} bull market resistance level`).maxResults(3).build(),
  );

  // 3. Recent error events
  const recentErrors = await client.recall(
    new RecallBuilder("recent errors or warnings").maxResults(5).build(),
  );

  return {
    recentConditions: marketFacts.memories,
    similarPastConditions: similarConditions.memories,
    recentErrors: recentErrors.memories,
  };
}

Support Agent: Customer Sentiment

async function getCustomerContext(customerId: string) {
  // 1. Similar past interactions
  const similarInteractions = await client.recall(
    new RecallBuilder(`customer ${customerId} complaints and frustration`).maxResults(5).build(),
  );

  // 2. Recent sentiment
  const recentSentiment = await client.recall(
    new RecallBuilder(`recent sentiment signals for customer ${customerId}`).maxResults(3).build(),
  );

  // 3. Root cause of last complaint (graph expansion happens server-side)
  const rootCause = await client.recall(
    new RecallBuilder(`root cause of customer ${customerId}'s last complaint`).maxResults(1).build(),
  );

  return {
    similarPastComplaints: similarInteractions.memories,
    recentSentiment: recentSentiment.memories,
    rootCauses: rootCause.memories,
  };
}

Performance & Latency

StrategyLatency (P99)Best Index Size
Semantic100–200ms<10M vectors
Temporal50–100ms<100M
Lexical30–50ms<100M
Type-Filtered10–50msUnlimited
Graph50–200ms (depends on depth)<5M nodes
Hybrid100–200ms<10M

Implementation Checklist

  • Define memory types you'll use (decision, observation, error, preference, etc.)
  • Choose primary retrieval strategy based on agent loop (most: hybrid)
  • Implement temporal filtering if you care about recency
  • Add type metadata to all stored memories
  • Test: retrieve queries and verify results include expected memories
  • Monitor latency: ensure P99 <200ms for agent loop queries
  • Iterate: A/B test strategies, measure retrieval quality
  • Document: which memory types use which retrieval strategy

Next Steps

  • Deep dive: See Three Retrievers for advanced filtering and query syntax
  • Schema design: Read Schema Design Patterns for memory type conventions
  • Architecture: Check Memory Architectures for end-to-end agent memory systems

Related reading

  • Read PipelineThree Retrievers Are Better Than One
PreviousSelf-Hosted vs Managed CloudNextTemporal Context Windows

Updates from the lab.

Engineering notes, research drops, occasional product updates. Roughly monthly.

Arc Labs

Cognitive infrastructure for AI agents. Open core in Rust. Composable primitives you own.

GitHubX / TwitterDiscussions

Brain

  • Memory Layer
  • Documentation
  • Pricing
  • Changelog
  • Status

Developers

  • Start here
  • TypeScript SDK
  • Python SDK
  • Rust SDK
  • MCP Server

Company

  • About
  • Careers
  • Blog
  • Security
  • Contact
Encode"Priya lives in Berlin."mem_7f3a · storedRecall"where does Priya live?"→ BerlinSupersede"Priya moved to Lisbon."mem_9c21 ⊃ mem_7f3aBerlin→ LisbonARC LABSARC LABSARC LABS
© 2026 ARC LABS · BANGALOREPrivacyTermsDPAApache 2.0