搜索 API
本文档描述了 Trae 搜索功能的 API 接口。
概述
搜索 API 提供了代码搜索、文件搜索、全局搜索等功能,帮助开发者快速定位和查找项目中的内容。
端点
全局搜索
http
GET /api/search?q={query}&type={type}&limit={limit}&offset={offset}查询参数
| 参数 | 类型 | 必需 | 描述 |
|---|---|---|---|
q | string | 是 | 搜索查询 |
type | string | 否 | 搜索类型 (all/code/files/symbols/docs) |
limit | number | 否 | 返回数量限制 (默认: 20) |
offset | number | 否 | 偏移量 (默认: 0) |
project_id | string | 否 | 限制在特定项目中搜索 |
language | string | 否 | 编程语言过滤 |
case_sensitive | boolean | 否 | 是否区分大小写 |
regex | boolean | 否 | 是否使用正则表达式 |
响应
json
{
"query": "function getUserData",
"type": "code",
"total": 15,
"results": [
{
"type": "code",
"file_path": "src/utils/api.js",
"line_number": 42,
"content": "function getUserData(userId) {",
"context": {
"before": ["// 获取用户数据", "// @param {string} userId - 用户ID"],
"after": [" return fetch(`/api/users/${userId}`);"]
},
"highlights": [
{
"start": 0,
"end": 8,
"text": "function"
},
{
"start": 9,
"end": 20,
"text": "getUserData"
}
],
"score": 0.95
}
],
"facets": {
"languages": {
"javascript": 8,
"typescript": 5,
"python": 2
},
"file_types": {
".js": 8,
".ts": 5,
".py": 2
}
},
"suggestions": [
"getUserById",
"fetchUserData",
"loadUserInfo"
]
}代码搜索
http
GET /api/search/code?q={query}&project_id={project_id}查询参数
| 参数 | 类型 | 必需 | 描述 |
|---|---|---|---|
q | string | 是 | 代码搜索查询 |
project_id | string | 否 | 项目 ID |
language | string | 否 | 编程语言 |
file_extension | string | 否 | 文件扩展名 |
include_comments | boolean | 否 | 是否包含注释 |
include_strings | boolean | 否 | 是否包含字符串 |
响应
json
{
"query": "async function",
"total": 23,
"results": [
{
"file_path": "src/services/auth.js",
"line_number": 15,
"content": "async function authenticateUser(credentials) {",
"function_name": "authenticateUser",
"class_name": null,
"context": {
"function_signature": "async function authenticateUser(credentials)",
"parameters": ["credentials"],
"return_type": "Promise<User>"
},
"highlights": [
{
"start": 0,
"end": 14,
"text": "async function"
}
],
"score": 0.92
}
]
}文件搜索
http
GET /api/search/files?q={query}&project_id={project_id}查询参数
| 参数 | 类型 | 必需 | 描述 |
|---|---|---|---|
q | string | 是 | 文件名搜索查询 |
project_id | string | 否 | 项目 ID |
extension | string | 否 | 文件扩展名过滤 |
directory | string | 否 | 目录过滤 |
include_hidden | boolean | 否 | 是否包含隐藏文件 |
响应
json
{
"query": "user",
"total": 12,
"results": [
{
"file_path": "src/components/UserProfile.jsx",
"file_name": "UserProfile.jsx",
"directory": "src/components",
"size": 2048,
"modified_at": "2024-01-01T12:00:00Z",
"file_type": "javascript",
"highlights": [
{
"start": 0,
"end": 4,
"text": "User"
}
],
"score": 0.88
}
]
}符号搜索
http
GET /api/search/symbols?q={query}&project_id={project_id}查询参数
| 参数 | 类型 | 必需 | 描述 |
|---|---|---|---|
q | string | 是 | 符号搜索查询 |
project_id | string | 否 | 项目 ID |
symbol_type | string | 否 | 符号类型 (function/class/variable/constant) |
scope | string | 否 | 作用域 (global/local/exported) |
响应
json
{
"query": "User",
"total": 8,
"results": [
{
"symbol_name": "User",
"symbol_type": "class",
"file_path": "src/models/User.js",
"line_number": 5,
"scope": "exported",
"signature": "class User extends BaseModel",
"description": "用户模型类",
"methods": [
"constructor",
"save",
"delete",
"validate"
],
"properties": [
"id",
"username",
"email",
"createdAt"
],
"score": 0.95
}
]
}文档搜索
http
GET /api/search/docs?q={query}&project_id={project_id}查询参数
| 参数 | 类型 | 必需 | 描述 |
|---|---|---|---|
q | string | 是 | 文档搜索查询 |
project_id | string | 否 | 项目 ID |
doc_type | string | 否 | 文档类型 (readme/api/guide/comment) |
language | string | 否 | 文档语言 |
响应
json
{
"query": "authentication",
"total": 5,
"results": [
{
"doc_type": "api",
"title": "用户认证 API",
"file_path": "docs/api/authentication.md",
"section": "登录流程",
"content": "用户认证是应用安全的核心组件...",
"highlights": [
{
"start": 2,
"end": 16,
"text": "authentication"
}
],
"score": 0.91
}
]
}搜索建议
http
GET /api/search/suggestions?q={query}&type={type}查询参数
| 参数 | 类型 | 必需 | 描述 |
|---|---|---|---|
q | string | 是 | 部分查询文本 |
type | string | 否 | 建议类型 (all/code/files/symbols) |
limit | number | 否 | 建议数量限制 |
响应
json
{
"query": "user",
"suggestions": [
{
"text": "getUserData",
"type": "function",
"file_path": "src/utils/api.js",
"description": "获取用户数据的函数"
},
{
"text": "UserProfile",
"type": "component",
"file_path": "src/components/UserProfile.jsx",
"description": "用户资料组件"
},
{
"text": "user.model.js",
"type": "file",
"file_path": "src/models/user.model.js",
"description": "用户模型文件"
}
]
}高级搜索
http
POST /api/search/advanced请求参数
json
{
"query": {
"text": "function",
"type": "code",
"filters": {
"language": ["javascript", "typescript"],
"file_extension": [".js", ".ts"],
"directory": ["src/", "lib/"],
"exclude_directory": ["node_modules/", "dist/"],
"date_range": {
"from": "2024-01-01",
"to": "2024-01-31"
},
"file_size": {
"min": 100,
"max": 10000
}
},
"options": {
"case_sensitive": false,
"whole_word": true,
"regex": false,
"include_comments": true,
"include_strings": false
}
},
"sort": {
"field": "relevance",
"order": "desc"
},
"limit": 50,
"offset": 0
}响应
json
{
"query": {
"text": "function",
"processed_query": "function",
"filters_applied": {
"language": ["javascript", "typescript"],
"file_extension": [".js", ".ts"]
}
},
"total": 156,
"results": [
{
"type": "code",
"file_path": "src/utils/helpers.js",
"line_number": 25,
"content": "export function formatDate(date) {",
"context": {
"before": ["// 格式化日期", "// @param {Date} date - 日期对象"],
"after": [" return date.toLocaleDateString();"]
},
"highlights": [
{
"start": 7,
"end": 15,
"text": "function"
}
],
"metadata": {
"function_name": "formatDate",
"parameters": ["date"],
"exported": true,
"complexity": "low"
},
"score": 0.94
}
],
"aggregations": {
"languages": {
"javascript": 89,
"typescript": 67
},
"directories": {
"src/utils/": 45,
"src/components/": 32,
"src/services/": 28
},
"function_types": {
"arrow_function": 78,
"function_declaration": 56,
"method": 22
}
}
}搜索历史
http
GET /api/search/history?limit={limit}响应
json
{
"history": [
{
"query": "async function",
"type": "code",
"timestamp": "2024-01-01T12:00:00Z",
"results_count": 23,
"project_id": "proj_123"
},
{
"query": "UserProfile",
"type": "files",
"timestamp": "2024-01-01T11:30:00Z",
"results_count": 5,
"project_id": "proj_123"
}
]
}保存搜索
http
POST /api/search/saved请求参数
json
{
"name": "API 函数搜索",
"query": {
"text": "async function",
"type": "code",
"filters": {
"language": ["javascript"]
}
},
"project_id": "proj_123",
"notifications": true
}响应
json
{
"saved_search_id": "search_123",
"name": "API 函数搜索",
"created_at": "2024-01-01T12:00:00Z",
"last_run": "2024-01-01T12:00:00Z",
"results_count": 23
}搜索语法
基本语法
word- 搜索包含单词的内容"exact phrase"- 精确短语搜索word1 AND word2- 同时包含两个词word1 OR word2- 包含任一词NOT word- 不包含该词word*- 通配符搜索
高级语法
file:*.js- 搜索特定文件类型path:src/components- 搜索特定路径lang:javascript- 搜索特定语言type:function- 搜索特定符号类型author:username- 搜索特定作者的代码modified:>2024-01-01- 搜索修改日期后的文件
正则表达式
启用正则表达式模式时,支持标准正则表达式语法:
function\s+\w+- 匹配函数声明\b[A-Z]\w*\b- 匹配大写开头的单词\d{3}-\d{3}-\d{4}- 匹配电话号码格式
示例
基本代码搜索
javascript
// 搜索所有异步函数
const response = await fetch('/api/search/code?q=async function&language=javascript');
const results = await response.json();
console.log(`找到 ${results.total} 个异步函数`);
results.results.forEach(result => {
console.log(`${result.file_path}:${result.line_number} - ${result.content}`);
});文件搜索
javascript
// 搜索用户相关的组件文件
const response = await fetch('/api/search/files?q=user&extension=.jsx&directory=src/components');
const results = await response.json();
console.log('用户组件文件:');
results.results.forEach(file => {
console.log(`- ${file.file_name} (${file.size} bytes)`);
});符号搜索
javascript
// 搜索所有用户相关的类
const response = await fetch('/api/search/symbols?q=User&symbol_type=class');
const results = await response.json();
console.log('用户相关类:');
results.results.forEach(symbol => {
console.log(`- ${symbol.symbol_name} in ${symbol.file_path}`);
console.log(` 方法: ${symbol.methods.join(', ')}`);
console.log(` 属性: ${symbol.properties.join(', ')}`);
});高级搜索
javascript
// 复杂搜索查询
const searchQuery = {
query: {
text: 'function AND (user OR auth)',
type: 'code',
filters: {
language: ['javascript', 'typescript'],
directory: ['src/'],
exclude_directory: ['node_modules/', 'dist/'],
date_range: {
from: '2024-01-01',
to: '2024-01-31'
}
},
options: {
case_sensitive: false,
whole_word: true,
include_comments: false
}
},
sort: {
field: 'relevance',
order: 'desc'
},
limit: 20
};
const response = await fetch('/api/search/advanced', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your-token'
},
body: JSON.stringify(searchQuery)
});
const results = await response.json();
console.log(`高级搜索找到 ${results.total} 个结果`);
// 显示聚合信息
console.log('语言分布:');
Object.entries(results.aggregations.languages).forEach(([lang, count]) => {
console.log(` ${lang}: ${count}`);
});搜索建议
javascript
// 获取搜索建议
const getSuggestions = async (query) => {
const response = await fetch(`/api/search/suggestions?q=${encodeURIComponent(query)}&limit=5`);
const data = await response.json();
return data.suggestions.map(suggestion => ({
text: suggestion.text,
type: suggestion.type,
description: suggestion.description
}));
};
// 使用示例
const suggestions = await getSuggestions('user');
console.log('搜索建议:');
suggestions.forEach(suggestion => {
console.log(`- ${suggestion.text} (${suggestion.type}): ${suggestion.description}`);
});保存和管理搜索
javascript
// 保存常用搜索
const saveSearch = async (name, query) => {
const response = await fetch('/api/search/saved', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your-token'
},
body: JSON.stringify({
name,
query,
notifications: true
})
});
return response.json();
};
// 保存搜索
const savedSearch = await saveSearch('API 函数', {
text: 'async function',
type: 'code',
filters: {
language: ['javascript']
}
});
console.log(`搜索已保存: ${savedSearch.saved_search_id}`);实时搜索
javascript
// 实现实时搜索功能
class RealTimeSearch {
constructor() {
this.debounceTimer = null;
this.cache = new Map();
}
async search(query, callback) {
// 防抖处理
clearTimeout(this.debounceTimer);
this.debounceTimer = setTimeout(async () => {
// 检查缓存
if (this.cache.has(query)) {
callback(this.cache.get(query));
return;
}
try {
const response = await fetch(`/api/search?q=${encodeURIComponent(query)}&limit=10`);
const results = await response.json();
// 缓存结果
this.cache.set(query, results);
callback(results);
} catch (error) {
console.error('搜索失败:', error);
callback({ results: [], total: 0, error: error.message });
}
}, 300); // 300ms 防抖
}
}
// 使用实时搜索
const realTimeSearch = new RealTimeSearch();
// 绑定到搜索输入框
document.getElementById('search-input').addEventListener('input', (e) => {
const query = e.target.value.trim();
if (query.length >= 2) {
realTimeSearch.search(query, (results) => {
updateSearchResults(results);
});
}
});
function updateSearchResults(results) {
const container = document.getElementById('search-results');
if (results.error) {
container.innerHTML = `<div class="error">搜索错误: ${results.error}</div>`;
return;
}
if (results.total === 0) {
container.innerHTML = '<div class="no-results">未找到相关结果</div>';
return;
}
const html = results.results.map(result => `
<div class="search-result">
<div class="file-path">${result.file_path}</div>
<div class="content">${highlightMatches(result.content, result.highlights)}</div>
<div class="line-number">第 ${result.line_number} 行</div>
</div>
`).join('');
container.innerHTML = html;
}
function highlightMatches(content, highlights) {
let result = content;
// 从后往前处理高亮,避免位置偏移
highlights.reverse().forEach(highlight => {
const before = result.substring(0, highlight.start);
const match = result.substring(highlight.start, highlight.end);
const after = result.substring(highlight.end);
result = before + `<mark>${match}</mark>` + after;
});
return result;
}