# Memory.query()
[EN] Source: https://mastra.ai/reference/memory/query

the `.query()` method retrieves messages from a specific thread, with support for pagination, filtering options, and semantic search.

## Usage Example

```typescript copy
await memory?.query({ threadId: "user-123" });
```

## Parameters

<PropertiesTable
  content={[
    {
      name: "threadId",
      type: "string",
      description:
        "The unique identifier of the thread to retrieve messages from",
      isOptional: false,
    },
    {
      name: "resourceId",
      type: "string",
      description:
        "Optional ID of the resource that owns the thread. If provided, validates thread ownership",
      isOptional: true,
    },
    {
      name: "selectBy",
      type: "object",
      description: "Options for filtering and selecting messages",
      isOptional: true,
    },
    {
      name: "threadConfig",
      type: "MemoryConfig",
      description:
        "Configuration options for message retrieval and semantic search",
      isOptional: true,
    },
    {
      name: "format",
      type: "'v1' | 'v2'",
      description:
        "Message format to return. Defaults to 'v2' for current format, 'v1' for backwards compatibility",
      isOptional: true,
    },
  ]}
/>

### selectBy parameters

<PropertiesTable
  content={[
    {
      name: "vectorSearchString",
      type: "string",
      description:
        "Search string for finding semantically similar messages. Requires semantic recall to be enabled in threadConfig.",
      isOptional: true,
    },
    {
      name: "last",
      type: "number | false",
      description:
        "Number of most recent messages to retrieve. Set to false to disable limit. Note: threadConfig.lastMessages (default: 10) will override this if smaller.",
      isOptional: true,
    },
    {
      name: "include",
      type: "{ id: string; threadId?: string; withPreviousMessages?: number; withNextMessages?: number }[]",
      description:
        "Array of specific message IDs to include with optional context messages. Each item has an `id` (required), optional `threadId` (defaults to main threadId), `withPreviousMessages` (number of messages before, defaults to 2 for vector search, 0 otherwise), and `withNextMessages` (number of messages after, defaults to 2 for vector search, 0 otherwise).",
      isOptional: true,
    },
    {
      name: "pagination",
      type: "{ dateRange?: { start?: Date; end?: Date }; page?: number; perPage?: number }",
      description:
        "Pagination options for retrieving messages in batches. Includes `dateRange` (filter by date range), `page` (0-based page number), and `perPage` (messages per page).",
      isOptional: true,
    },
  ]}
/>

### threadConfig parameters

<PropertiesTable
  content={[
    {
      name: "lastMessages",
      type: "number | false",
      description:
        "Number of most recent messages to retrieve. Set to false to disable.",
      isOptional: true,
      defaultValue: "10",
    },
    {
      name: "semanticRecall",
      type: "boolean | { topK: number; messageRange: number | { before: number; after: number }; scope?: 'thread' | 'resource' }",
      description:
        "Enable semantic search in message history. Can be a boolean or an object with configuration options. When enabled, requires both vector store and embedder to be configured.",
      isOptional: true,
      defaultValue: "false",
    },
    {
      name: "workingMemory",
      type: "WorkingMemory",
      description:
        "Configuration for working memory feature. Can be `{ enabled: boolean; template?: string; schema?: ZodObject<any> | JSONSchema7; scope?: 'thread' | 'resource' }` or `{ enabled: boolean }` to disable.",
      isOptional: true,
      defaultValue:
        "{ enabled: false, template: '# User Information\\n- **First Name**:\\n- **Last Name**:\\n...' }",
    },
    {
      name: "threads",
      type: "{ generateTitle?: boolean | { model: DynamicArgument<MastraLanguageModel>; instructions?: DynamicArgument<string> } }",
      description:
        "Settings related to memory thread creation. `generateTitle` controls automatic thread title generation from the user's first message. Can be a boolean or an object with custom model and instructions.",
      isOptional: true,
      defaultValue: "{ generateTitle: false }",
    },
  ]}
/>

## Returns

<PropertiesTable
  content={[
    {
      name: "messages",
      type: "CoreMessage[]",
      description: "Array of retrieved messages in their core format",
    },
    {
      name: "uiMessages",
      type: "UIMessageWithMetadata[]",
      description:
        "Array of messages formatted for UI display, including proper threading of tool calls and results",
    },
  ]}
/>

## Extended usage example

```typescript title="src/test-memory.ts" showLineNumbers copy
import { mastra } from "./mastra";

const agent = mastra.getAgent("agent");
const memory = await agent.getMemory();

const { messages, uiMessages } = await memory!.query({
  threadId: "thread-123",
  selectBy: {
    last: 50,
    vectorSearchString: "What messages are there?",
    include: [
      {
        id: "msg-123",
      },
      {
        id: "msg-456",
        withPreviousMessages: 3,
        withNextMessages: 1,
      },
    ],
  },
  threadConfig: {
    semanticRecall: true,
  },
});

console.log(messages);
console.log(uiMessages);
```

### Related

- [Memory Class Reference](/reference/memory/memory-class)
- [Getting Started with Memory](/docs/memory/overview)
- [Semantic Recall](/docs/memory/semantic-recall)
- [createThread](/reference/memory/createThread)


---
title: "Reference: AITracing | Observability"
description: Core AI Tracing classes and methods
---

import PropertiesTable from "@site/src/components/PropertiesTable";