Skip to main content
DELETE
/
api
/
delete-document
Delete Document
curl --request DELETE \
  --url https://api.example.com/api/delete-document
{
  "success": true,
  "message": "<string>",
  "error": "<string>"
}

Overview

This endpoint permanently deletes a document from the system, including:
  1. The physical file from storage
  2. The document record from the database
  3. All associated vector embeddings and chunks (via cascade delete)
This ensures complete cleanup and prevents orphaned data in the RAG system.

Request

id
integer
required
The unique identifier of the document to delete

Response

success
boolean
required
Indicates whether the deletion succeeded
message
string
Success message confirming deletion
error
string
Error message if the deletion failed

Example

curl -X DELETE "https://your-domain.com/api/delete-document?id=42"

Success Response

{
  "success": true,
  "message": "Document deleted successfully"
}

Error Responses

Missing ID Parameter

{
  "success": false,
  "error": "Error al eliminar documento"
}

Document Not Found

{
  "success": false,
  "error": "Error al eliminar documento"
}

Implementation Details

Deletion Process

The endpoint follows a multi-step deletion process (DocumentService.php:105-120):
public function deleteDocument($id)
{
    // 1. Fetch document to get file path
    $document = $this->getDocument($id);
    
    if (!$document) {
        throw new \RuntimeException('Document not found');
    }

    // 2. Delete physical file
    $filepath = $this->uploadPath . '/' . $document['filename'];
    if (file_exists($filepath)) {
        unlink($filepath);
    }

    // 3. Delete database record (cascades to vectors)
    return $this->db->delete('documents', 'id = :id', [':id' => $id]);
}

Cascade Deletion

When the document record is deleted from the documents table, the database automatically deletes all related records in the vectors table through foreign key constraints. This ensures:
  • All text chunks are removed
  • All vector embeddings are removed
  • No orphaned data remains in the system

File System Cleanup

The physical file is deleted from the uploads directory (DocumentService.php:113-117):
$filepath = $this->uploadPath . '/' . $document['filename'];

if (file_exists($filepath)) {
    unlink($filepath);
}
If the file doesn’t exist (e.g., manually deleted), the operation continues without error.

Error Handling

The endpoint validates the document ID and throws appropriate errors (api/delete-document.php:12-16):
$id = $_GET['id'] ?? null;

if (!$id) {
    throw new \InvalidArgumentException('Document ID required');
}

Data Cleanup Summary

ResourceActionLocation
Physical FileDeleted from filesystem{uploadPath}/{filename}
Document RecordDeleted from databasedocuments table
Text ChunksCascade deletedvectors table
Vector EmbeddingsCascade deletedvectors table

Use Cases

Bulk Deletion

Delete multiple documents:
const documentIds = [42, 43, 44];

const deletions = documentIds.map(id =>
  fetch(`/api/delete-document?id=${id}`, { method: 'DELETE' })
    .then(r => r.json())
);

const results = await Promise.all(deletions);
const successful = results.filter(r => r.success).length;

console.log(`Deleted ${successful}/${documentIds.length} documents`);

Cleanup Old Documents

Delete documents older than a certain date:
// First, get all documents
const { documents } = await fetch('/api/get-documents').then(r => r.json());

// Filter documents older than 90 days
const cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - 90);

const oldDocs = documents.filter(doc => 
  new Date(doc.created_at) < cutoffDate
);

// Delete each old document
for (const doc of oldDocs) {
  await fetch(`/api/delete-document?id=${doc.id}`, { method: 'DELETE' });
}

console.log(`Cleaned up ${oldDocs.length} old documents`);

Storage Management

Free up space by removing large documents:
const { documents } = await fetch('/api/get-documents').then(r => r.json());

// Find documents larger than 10MB
const largeDocs = documents.filter(doc => doc.file_size > 10 * 1024 * 1024);

console.log(`Found ${largeDocs.length} documents larger than 10MB`);

// Delete after user confirmation
for (const doc of largeDocs) {
  await fetch(`/api/delete-document?id=${doc.id}`, { method: 'DELETE' });
}

Important Notes

Deletion is permanent and irreversible. The document file, database record, and all vector embeddings are completely removed from the system.
If the document has been referenced in WhatsApp conversation history, those references will remain but the document content will no longer be retrievable for future RAG queries.

Build docs developers (and LLMs) love