Pular para conteúdo

NOTION_QUERY_DATABASE - Consultar Database no Notion

O que é este Node?

O NOTION_QUERY_DATABASE é o node responsável por buscar e filtrar páginas dentro de um database do Notion, permitindo queries complexas com filtros, ordenação e paginação.

Por que este Node existe?

Buscar dados no Notion programaticamente é essencial para automações inteligentes. O NOTION_QUERY_DATABASE existe para:

  1. Busca inteligente: Encontrar páginas específicas por propriedades (status, tags, datas, etc.)
  2. Listagem filtrada: Exibir apenas páginas que atendem critérios específicos
  3. Integração de dados: Puxar dados do Notion para usar em flows automatizados
  4. Relatórios automatizados: Contar tarefas pendentes, leads qualificados, artigos por categoria

Como funciona internamente?

Quando o NOTION_QUERY_DATABASE é executado, o sistema:

  1. Autentica na Notion API: Usa o apiKey fornecido com header Notion-Version 2022-06-28
  2. Monta query: Combina databaseId, filter (opcional), sorts (opcional) e pageSize
  3. Envia POST: Faz requisição para https://api.notion.com/v1/databases/{databaseId}/query
  4. Processa resposta: Recebe array de páginas que correspondem aos filtros
  5. Se erro: Retorna exceção (database não encontrado, filtro inválido, etc.)
  6. Se sucesso: Retorna results (array de páginas) e hasMore (boolean para paginação)

Código interno (productivity-executors.service.ts:390-405):

case 'queryDatabase':
  const queryResponse = await firstValueFrom(
    this.httpService.post(`${notionApiUrl}/databases/${data.databaseId}/query`,
      {
        filter: data.filter || undefined,
        sorts: data.sorts || undefined,
        page_size: data.pageSize || 100,
      },
      { headers }
    )
  );
  return {
    success: true,
    results: queryResponse.data.results,
    hasMore: queryResponse.data.has_more,
  };

Quando você DEVE usar este Node?

Use NOTION_QUERY_DATABASE sempre que precisar de buscar páginas no Notion com filtros:

Casos de uso

  1. Listar tarefas: "Mostrar minhas tarefas pendentes"
  2. Buscar por email: "Encontrar lead com email joao@exemplo.com"
  3. Filtrar por status: "Listar todos os pedidos 'Em Processamento'"
  4. Buscar por data: "Tarefas com prazo para hoje"
  5. Contar registros: "Quantos leads temos no status 'Qualificado'?"
  6. Relatórios: "Artigos publicados esta semana"

Quando NÃO usar NOTION_QUERY_DATABASE

  • Criar nova página: Use NOTION_CREATE_PAGE ao invés
  • Atualizar página existente: Use NOTION_UPDATE_PAGE ao invés
  • Buscar página por ID: Use NOTION_GET_PAGE ao invés (se precisar apenas de uma página conhecida)

Parâmetros Detalhados

apiKey (string, obrigatório)

O que é: Token de integração do Notion (obtido em notion.so/my-integrations).

Como obter: 1. Acesse https://www.notion.so/my-integrations 2. Clique em "New integration" 3. Dê um nome e selecione workspace 4. Copie o "Internal Integration Token" 5. IMPORTANTE: Compartilhe o database com a integração!

Flow completo para testar:

{
  "name": "Teste Notion Query - API Key",
  "nodes": [
    {
      "id": "start_1",
      "type": "start",
      "position": { "x": 100, "y": 100 },
      "data": { "label": "Início" }
    },
    {
      "id": "variable_1",
      "type": "variable",
      "position": { "x": 300, "y": 100 },
      "data": {
        "label": "Config",
        "parameters": {
          "assignments": [
            {
              "variable": "notion_api_key",
              "value": "secret_SEU_TOKEN_AQUI"
            },
            {
              "variable": "database_id",
              "value": "SEU_DATABASE_ID"
            }
          ]
        }
      }
    },
    {
      "id": "notion_1",
      "type": "notion",
      "position": { "x": 500, "y": 100 },
      "data": {
        "label": "Buscar Páginas",
        "parameters": {
          "operation": "queryDatabase",
          "apiKey": "{{notion_api_key}}",
          "databaseId": "{{database_id}}",
          "pageSize": 10
        }
      }
    },
    {
      "id": "message_1",
      "type": "message",
      "position": { "x": 700, "y": 100 },
      "data": {
        "label": "Mostrar Resultado",
        "parameters": {
          "message": "Encontradas {{notion_1.results.length}} páginas!"
        }
      }
    },
    {
      "id": "end_1",
      "type": "end",
      "position": { "x": 900, "y": 100 },
      "data": { "label": "Fim" }
    }
  ],
  "edges": [
    { "source": "start_1", "target": "variable_1" },
    { "source": "variable_1", "target": "notion_1" },
    { "source": "notion_1", "target": "message_1" },
    { "source": "message_1", "target": "end_1" }
  ]
}

Teste: Substitua pelos valores reais e veja quantas páginas existem no database.

databaseId (string, obrigatório)

O que é: ID do database do Notion onde a busca será realizada.

Como obter: 1. Abra o database no Notion 2. Copie a URL: https://notion.so/workspace/DATABASE_ID?v=... 3. O DATABASE_ID é o código entre / e ?v= 4. Exemplo: a8aec43c6f004f5789c9e2e4aa3e8d9f

Flow completo para testar:

{
  "name": "Teste Notion - Database ID",
  "nodes": [
    {
      "id": "start_1",
      "type": "start",
      "position": { "x": 100, "y": 100 },
      "data": { "label": "Início" }
    },
    {
      "id": "notion_1",
      "type": "notion",
      "position": { "x": 300, "y": 100 },
      "data": {
        "label": "Listar Todas",
        "parameters": {
          "operation": "queryDatabase",
          "apiKey": "secret_SEU_TOKEN",
          "databaseId": "a8aec43c6f004f5789c9e2e4aa3e8d9f"
        }
      }
    },
    {
      "id": "message_1",
      "type": "message",
      "position": { "x": 500, "y": 100 },
      "data": {
        "label": "Resultado",
        "parameters": {
          "message": "Total de páginas: {{notion_1.results.length}}"
        }
      }
    },
    {
      "id": "end_1",
      "type": "end",
      "position": { "x": 700, "y": 100 },
      "data": { "label": "Fim" }
    }
  ],
  "edges": [
    { "source": "start_1", "target": "notion_1" },
    { "source": "notion_1", "target": "message_1" },
    { "source": "message_1", "target": "end_1" }
  ]
}

Teste: Veja todas as páginas do database (limitado por pageSize).

filter (object, opcional)

O que é: Objeto de filtro para buscar apenas páginas que atendem critérios específicos.

Padrão: undefined (retorna todas as páginas)

Estrutura de filtros por tipo:

Select:

{
  "property": "Status",
  "select": {
    "equals": "Em Progresso"
  }
}

Multi-select:

{
  "property": "Tags",
  "multi_select": {
    "contains": "Urgente"
  }
}

Checkbox:

{
  "property": "Concluída",
  "checkbox": {
    "equals": true
  }
}

Number:

{
  "property": "Prioridade",
  "number": {
    "greater_than": 5
  }
}

Date:

{
  "property": "Prazo",
  "date": {
    "on_or_before": "2025-01-20"
  }
}

Rich text / Title:

{
  "property": "Nome",
  "rich_text": {
    "contains": "urgente"
  }
}

Email:

{
  "property": "Email",
  "email": {
    "equals": "joao@exemplo.com"
  }
}

Filtros compostos (AND/OR):

{
  "and": [
    {
      "property": "Status",
      "select": {
        "equals": "A Fazer"
      }
    },
    {
      "property": "Prioridade",
      "select": {
        "equals": "Alta"
      }
    }
  ]
}

Flow completo para testar:

{
  "name": "Teste Notion - Filter",
  "nodes": [
    {
      "id": "start_1",
      "type": "start",
      "position": { "x": 100, "y": 100 },
      "data": { "label": "Início" }
    },
    {
      "id": "notion_1",
      "type": "notion",
      "position": { "x": 300, "y": 100 },
      "data": {
        "label": "Buscar Tarefas Pendentes",
        "parameters": {
          "operation": "queryDatabase",
          "apiKey": "secret_SEU_TOKEN",
          "databaseId": "SEU_DATABASE_ID",
          "filter": {
            "and": [
              {
                "property": "Status",
                "select": {
                  "equals": "A Fazer"
                }
              },
              {
                "property": "Prioridade",
                "select": {
                  "equals": "Alta"
                }
              }
            ]
          }
        }
      }
    },
    {
      "id": "message_1",
      "type": "message",
      "position": { "x": 500, "y": 100 },
      "data": {
        "label": "Resultado",
        "parameters": {
          "message": "Você tem {{notion_1.results.length}} tarefas de alta prioridade pendentes!"
        }
      }
    },
    {
      "id": "end_1",
      "type": "end",
      "position": { "x": 700, "y": 100 },
      "data": { "label": "Fim" }
    }
  ],
  "edges": [
    { "source": "start_1", "target": "notion_1" },
    { "source": "notion_1", "target": "message_1" },
    { "source": "message_1", "target": "end_1" }
  ]
}

Teste: Retorna apenas tarefas com Status="A Fazer" E Prioridade="Alta".

sorts (array, opcional)

O que é: Array de ordenação para organizar os resultados retornados.

Padrão: undefined (ordem padrão do Notion)

Estrutura:

[
  {
    "property": "Prazo",
    "direction": "ascending"
  },
  {
    "property": "Prioridade",
    "direction": "descending"
  }
]

Direções: - ascending: Crescente (A-Z, 0-9, mais antigo primeiro) - descending: Decrescente (Z-A, 9-0, mais recente primeiro)

Flow completo para testar:

{
  "name": "Teste Notion - Sorts",
  "nodes": [
    {
      "id": "start_1",
      "type": "start",
      "position": { "x": 100, "y": 100 },
      "data": { "label": "Início" }
    },
    {
      "id": "notion_1",
      "type": "notion",
      "position": { "x": 300, "y": 100 },
      "data": {
        "label": "Buscar Ordenado",
        "parameters": {
          "operation": "queryDatabase",
          "apiKey": "secret_SEU_TOKEN",
          "databaseId": "SEU_DATABASE_ID",
          "sorts": [
            {
              "property": "Prazo",
              "direction": "ascending"
            }
          ],
          "pageSize": 5
        }
      }
    },
    {
      "id": "message_1",
      "type": "message",
      "position": { "x": 500, "y": 100 },
      "data": {
        "label": "Primeira Tarefa",
        "parameters": {
          "message": "Próxima tarefa urgente: {{notion_1.results[0].properties.Nome.title[0].text.content}}"
        }
      }
    },
    {
      "id": "end_1",
      "type": "end",
      "position": { "x": 700, "y": 100 },
      "data": { "label": "Fim" }
    }
  ],
  "edges": [
    { "source": "start_1", "target": "notion_1" },
    { "source": "notion_1", "target": "message_1" },
    { "source": "message_1", "target": "end_1" }
  ]
}

Teste: Retorna as 5 próximas tarefas ordenadas por prazo mais próximo.

pageSize (number, opcional)

O que é: Número máximo de páginas a retornar por query.

Padrão: 100 (máximo permitido pela Notion API)

Mínimo: 1 Máximo: 100

Flow completo para testar:

{
  "name": "Teste Notion - Page Size",
  "nodes": [
    {
      "id": "start_1",
      "type": "start",
      "position": { "x": 100, "y": 100 },
      "data": { "label": "Início" }
    },
    {
      "id": "notion_1",
      "type": "notion",
      "position": { "x": 300, "y": 100 },
      "data": {
        "label": "Top 3 Tarefas",
        "parameters": {
          "operation": "queryDatabase",
          "apiKey": "secret_SEU_TOKEN",
          "databaseId": "SEU_DATABASE_ID",
          "filter": {
            "property": "Status",
            "select": {
              "equals": "A Fazer"
            }
          },
          "sorts": [
            {
              "property": "Prioridade",
              "direction": "descending"
            }
          ],
          "pageSize": 3
        }
      }
    },
    {
      "id": "message_1",
      "type": "message",
      "position": { "x": 500, "y": 100 },
      "data": {
        "label": "Listar Top 3",
        "parameters": {
          "message": "🔥 Top 3 tarefas prioritárias:\n1. {{notion_1.results[0].properties.Nome.title[0].text.content}}\n2. {{notion_1.results[1].properties.Nome.title[0].text.content}}\n3. {{notion_1.results[2].properties.Nome.title[0].text.content}}"
        }
      }
    },
    {
      "id": "end_1",
      "type": "end",
      "position": { "x": 700, "y": 100 },
      "data": { "label": "Fim" }
    }
  ],
  "edges": [
    { "source": "start_1", "target": "notion_1" },
    { "source": "notion_1", "target": "message_1" },
    { "source": "message_1", "target": "end_1" }
  ]
}

Teste: Retorna apenas as 3 tarefas de maior prioridade.

Parâmetros

Campo Tipo Obrigatório Descrição
operation string Sim Deve ser "queryDatabase"
apiKey string Sim Token de integração do Notion
databaseId string Sim ID do database a consultar
filter object Não Filtros para busca (padrão: retorna tudo)
sorts array Não Ordenação dos resultados (padrão: ordem do Notion)
pageSize number Não Máximo de resultados (padrão: 100, máx: 100)

Exemplo 1: Task Management - Minhas Tarefas Pendentes

Objetivo: Listar tarefas do usuário que estão pendentes

JSON para Importar

{
  "name": "Minhas Tarefas Pendentes",
  "nodes": [
    {
      "id": "start_1",
      "type": "start",
      "position": { "x": 100, "y": 100 },
      "data": { "label": "Início" }
    },
    {
      "id": "message_1",
      "type": "message",
      "position": { "x": 300, "y": 100 },
      "data": {
        "label": "Intro",
        "parameters": {
          "message": "Vou buscar suas tarefas pendentes..."
        }
      }
    },
    {
      "id": "notion_1",
      "type": "notion",
      "position": { "x": 500, "y": 100 },
      "data": {
        "label": "Query Tarefas",
        "parameters": {
          "operation": "queryDatabase",
          "apiKey": "secret_SEU_TOKEN",
          "databaseId": "SEU_DATABASE_TASKS",
          "filter": {
            "property": "Status",
            "select": {
              "equals": "A Fazer"
            }
          },
          "sorts": [
            {
              "property": "Prazo",
              "direction": "ascending"
            }
          ],
          "pageSize": 10
        }
      }
    },
    {
      "id": "condition_1",
      "type": "condition",
      "position": { "x": 700, "y": 100 },
      "data": {
        "label": "Tem Tarefas?",
        "parameters": {
          "condition": "{{notion_1.results.length}} > 0"
        }
      }
    },
    {
      "id": "message_2",
      "type": "message",
      "position": { "x": 900, "y": 50 },
      "data": {
        "label": "Listar Tarefas",
        "parameters": {
          "message": "📋 Você tem {{notion_1.results.length}} tarefas pendentes. Primeira: {{notion_1.results[0].properties.Tarefa.title[0].text.content}}"
        }
      }
    },
    {
      "id": "message_3",
      "type": "message",
      "position": { "x": 900, "y": 150 },
      "data": {
        "label": "Sem Tarefas",
        "parameters": {
          "message": "🎉 Parabéns! Você não tem tarefas pendentes!"
        }
      }
    },
    {
      "id": "end_1",
      "type": "end",
      "position": { "x": 1100, "y": 100 },
      "data": { "label": "Fim" }
    }
  ],
  "edges": [
    { "source": "start_1", "target": "message_1" },
    { "source": "message_1", "target": "notion_1" },
    { "source": "notion_1", "target": "condition_1" },
    { "source": "condition_1", "target": "message_2", "label": "true" },
    { "source": "condition_1", "target": "message_3", "label": "false" },
    { "source": "message_2", "target": "end_1" },
    { "source": "message_3", "target": "end_1" }
  ]
}

Saída esperada (com tarefas):

Sistema: Vou buscar suas tarefas pendentes...
Sistema: 📋 Você tem 3 tarefas pendentes. Primeira: Revisar documentação

Saída esperada (sem tarefas):

Sistema: Vou buscar suas tarefas pendentes...
Sistema: 🎉 Parabéns! Você não tem tarefas pendentes!

Exemplo 2: CRM - Buscar Lead por Email

Objetivo: Encontrar lead específico para atualizar

JSON para Importar

{
  "name": "CRM - Buscar Lead",
  "nodes": [
    {
      "id": "start_1",
      "type": "start",
      "position": { "x": 100, "y": 100 },
      "data": { "label": "Início" }
    },
    {
      "id": "email_1",
      "type": "email",
      "position": { "x": 300, "y": 100 },
      "data": {
        "label": "Email do Lead",
        "parameters": {
          "message": "Qual o email do lead?",
          "variable": "email_busca"
        }
      }
    },
    {
      "id": "notion_1",
      "type": "notion",
      "position": { "x": 500, "y": 100 },
      "data": {
        "label": "Buscar Lead",
        "parameters": {
          "operation": "queryDatabase",
          "apiKey": "secret_SEU_TOKEN",
          "databaseId": "SEU_DATABASE_CRM",
          "filter": {
            "property": "Email",
            "email": {
              "equals": "{{email_busca}}"
            }
          }
        }
      }
    },
    {
      "id": "condition_1",
      "type": "condition",
      "position": { "x": 700, "y": 100 },
      "data": {
        "label": "Lead Encontrado?",
        "parameters": {
          "condition": "{{notion_1.results.length}} > 0"
        }
      }
    },
    {
      "id": "message_2",
      "type": "message",
      "position": { "x": 900, "y": 50 },
      "data": {
        "label": "Lead Encontrado",
        "parameters": {
          "message": "✅ Lead encontrado!\nNome: {{notion_1.results[0].properties.Nome.title[0].text.content}}\nStatus: {{notion_1.results[0].properties.Status.select.name}}"
        }
      }
    },
    {
      "id": "message_3",
      "type": "message",
      "position": { "x": 900, "y": 150 },
      "data": {
        "label": "Não Encontrado",
        "parameters": {
          "message": "❌ Lead com email {{email_busca}} não encontrado no CRM."
        }
      }
    },
    {
      "id": "end_1",
      "type": "end",
      "position": { "x": 1100, "y": 100 },
      "data": { "label": "Fim" }
    }
  ],
  "edges": [
    { "source": "start_1", "target": "email_1" },
    { "source": "email_1", "target": "notion_1" },
    { "source": "notion_1", "target": "condition_1" },
    { "source": "condition_1", "target": "message_2", "label": "true" },
    { "source": "condition_1", "target": "message_3", "label": "false" },
    { "source": "message_2", "target": "end_1" },
    { "source": "message_3", "target": "end_1" }
  ]
}

Saída esperada (encontrado):

Sistema: Qual o email do lead?
Usuário: joao@exemplo.com
Sistema: ✅ Lead encontrado!
Nome: João Silva
Status: Qualificado

Exemplo 3: Relatório - Tarefas Vencendo Hoje

Objetivo: Listar tarefas com prazo para hoje

JSON para Importar

{
  "name": "Relatório - Tarefas Hoje",
  "nodes": [
    {
      "id": "start_1",
      "type": "start",
      "position": { "x": 100, "y": 100 },
      "data": { "label": "Início" }
    },
    {
      "id": "notion_1",
      "type": "notion",
      "position": { "x": 300, "y": 100 },
      "data": {
        "label": "Buscar Tarefas Hoje",
        "parameters": {
          "operation": "queryDatabase",
          "apiKey": "secret_SEU_TOKEN",
          "databaseId": "SEU_DATABASE_TASKS",
          "filter": {
            "and": [
              {
                "property": "Prazo",
                "date": {
                  "equals": "{{current_date}}"
                }
              },
              {
                "property": "Status",
                "select": {
                  "does_not_equal": "Concluído"
                }
              }
            ]
          },
          "sorts": [
            {
              "property": "Prioridade",
              "direction": "descending"
            }
          ]
        }
      }
    },
    {
      "id": "message_1",
      "type": "message",
      "position": { "x": 500, "y": 100 },
      "data": {
        "label": "Relatório",
        "parameters": {
          "message": "📅 TAREFAS PARA HOJE: {{notion_1.results.length}}\n\n⚠️ Foque nas prioridades!"
        }
      }
    },
    {
      "id": "end_1",
      "type": "end",
      "position": { "x": 700, "y": 100 },
      "data": { "label": "Fim" }
    }
  ],
  "edges": [
    { "source": "start_1", "target": "notion_1" },
    { "source": "notion_1", "target": "message_1" },
    { "source": "message_1", "target": "end_1" }
  ]
}

Saída esperada:

Sistema: 📅 TAREFAS PARA HOJE: 5

⚠️ Foque nas prioridades!

Resposta do Node

{
  "success": true,
  "results": [
    {
      "id": "a8aec43c-6f00-4f57-89c9-e2e4aa3e8d9f",
      "properties": {
        "Nome": {
          "title": [
            {
              "text": {
                "content": "Revisar documentação"
              }
            }
          ]
        },
        "Status": {
          "select": {
            "name": "A Fazer"
          }
        }
      }
    }
  ],
  "hasMore": false
}

Boas Práticas

SIM:

  • Use filtros para reduzir o número de páginas retornadas
  • Combine com CONDITION para validar se encontrou resultados
  • Use sorts para ordenar por relevância (prazo, prioridade)
  • Limite pageSize para melhor performance
  • Salve results em variáveis para usar em nodes seguintes

NÃO:

  • Não busque todos os dados sem filtro se o database é grande
  • Não acesse índices de array sem validar se existem
  • Não esqueça de checar notion_1.results.length > 0 antes de acessar results[0]
  • Não use query quando você já tem o pageId (use GET ao invés)

Dicas

Filtros compostos: Use and e or para filtros complexos Paginação: Se hasMore: true, você precisa fazer nova query com cursor Acessar propriedades: {{notion_1.results[0].properties.Nome.title[0].text.content}} Contar resultados: {{notion_1.results.length}} Combinar com UPDATE: Query + Condition + Update = workflow completo Properties names: Case-sensitive! "Status" ≠ "status"

Próximo Node

NOTION_CREATE_PAGE - Criar nova página → NOTION_UPDATE_PAGE - Atualizar página encontrada → NOTION_GET_PAGE - Obter página por ID