# Simple Vector Database (`periwinkle_ballet/simple-vector-database`) Actor

- **URL**: https://securitybyobscurity.apify.com/periwinkle\_ballet/simple-vector-database.md
- **Developed by:** [Nishad Manerikar](https://securitybyobscurity.apify.com/periwinkle_ballet) (community)
- **Categories:** AI, Developer tools, Agents
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-usage

## What's an Apify Actor?

Actors are a software tools running on the Apify platform, for all kinds of web data extraction and automation use cases.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

In JavaScript/TypeScript projects, use official [JavaScript/TypeScript client](https://docs.apify.com/api/client/js.md):

```bash
npm install apify-client
```

In Python projects, use official [Python client library](https://docs.apify.com/api/client/python.md):

```bash
pip install apify-client
```

In shell scripts, use [Apify CLI](https://docs.apify.com/cli/docs.md):

````bash
# MacOS / Linux
curl -fsSL https://apify.com/install-cli.sh | bash
# Windows
irm https://apify.com/install-cli.ps1 | iex
```bash

In AI frameworks, you might use the [Apify MCP server](https://docs.apify.com/platform/integrations/mcp.md).

If your project is in a different language, use the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).


# README

## Simple Vector Database

A Standby Actor that gives you a vector database with zero setup. Send text, get semantic search — no API keys, no external services, no vector math. Everything runs inside the Actor.

### Why

Adding semantic search to an Apify Actor today means setting up Pinecone, Qdrant, or similar — managing accounts, API keys, billing, and network config. This Actor eliminates all of that. Send text in, get relevant results back.

### How it works

- **Local embedding** — Uses `all-MiniLM-L6-v2` (384 dimensions) running in-process. No external calls.
- **Automatic chunking** — Long documents are split on sentence boundaries (~200 words per chunk) so nothing is lost to the model's token limit. You never manage chunks — it's transparent.
- **HNSW index** — Approximate nearest neighbor search via `hnswlib-node`. Fast, in-memory.
- **Persistent** — Collections survive restarts. Data is stored in named Apify KV stores and rebuilt on startup.

### Limitations

- Best for **small-to-medium collections** (up to ~10k documents). The entire index lives in memory.
- **Eventual consistency** — Data written between the last checkpoint and a crash may need re-embedding on restart.
- **Single instance** — No sharding or replication.
- **Dense vector search only** — No keyword/BM25 fallback.

### Quick start

```bash
VECTOR_DB="https://your-vector-db.apify.actor"

## Create a collection
curl -X PUT "$VECTOR_DB/collections/products"

## Add documents (ID is optional — auto-generated if omitted)
curl -X POST "$VECTOR_DB/collections/products/upsert" \
  -H "Content-Type: application/json" \
  -d '{
    "documents": [
      {"text": "Lightweight running shoes with foam cushioning", "metadata": {"price": 89}},
      {"text": "Waterproof hiking boots with ankle support", "metadata": {"price": 149}},
      {"text": "Casual canvas sneakers in multiple colors", "metadata": {"price": 45}}
    ]
  }'

## Semantic search
curl -X POST "$VECTOR_DB/collections/products/query" \
  -H "Content-Type: application/json" \
  -d '{"query": "comfortable shoes for running", "topK": 2}'
````

### API

#### Collections

##### `PUT /collections/:name`

Create a new collection. Dimensions (384) and distance metric (cosine) are fixed.

**Response (201):**

```json
{
  "name": "products",
  "dimensions": 384,
  "distanceMetric": "cosine",
  "documentCount": 0
}
```

Returns `409` if the collection already exists.

##### `GET /collections`

List all collections.

**Response (200):**

```json
{
  "collections": [
    {"name": "products", "dimensions": 384, "distanceMetric": "cosine", "documentCount": 42}
  ]
}
```

##### `DELETE /collections/:name`

Delete a collection and all its data. Returns `204` on success, `404` if not found.

#### Documents

##### `POST /collections/:name/upsert`

Add or update documents. Text is embedded and chunked automatically.

**Request:**

```json
{
  "documents": [
    {
      "id": "doc-1",
      "text": "The Eiffel Tower is a wrought-iron lattice tower in Paris.",
      "metadata": {"source": "wikipedia"}
    },
    {
      "text": "Tokyo is the capital of Japan."
    }
  ]
}
```

- `text` (required) — The document content. Long texts are automatically chunked.
- `id` (optional) — Document identifier. Auto-generated UUID if omitted. If an existing ID is provided, the document is overwritten.
- `metadata` (optional) — Arbitrary JSON stored alongside the document.

Maximum 100 documents per request.

**Response (200):**

```json
{
  "upserted": 2,
  "ids": ["doc-1", "a1b2c3d4-e5f6-7890-abcd-ef1234567890"]
}
```

The `ids` array matches the input order. Use these to fetch or overwrite documents later.

##### `POST /collections/:name/query`

Semantic search. The query is embedded and matched against all document chunks.

**Request:**

```json
{
  "query": "famous landmarks in France",
  "topK": 5
}
```

- `query` (required) — Natural language search text.
- `topK` (optional) — Maximum results to return. Default 10, max 100.

Results are individual chunks, not deduplicated by document. If a long document has multiple relevant passages, they each appear as separate results with the same `id`. Use `GET /documents/:id` to fetch the full document.

**Response (200):**

```json
{
  "results": [
    {
      "id": "doc-1",
      "score": 0.92,
      "matchedChunk": "The Eiffel Tower is a wrought-iron lattice tower in Paris.",
      "metadata": {"source": "wikipedia"}
    },
    {
      "id": "doc-1",
      "score": 0.85,
      "matchedChunk": "The tower stands 330 meters tall and weighs 10,100 tonnes.",
      "metadata": {"source": "wikipedia"}
    }
  ]
}
```

- `id` — Parent document ID. Use it to fetch the full document or group results.
- `score` — Cosine similarity (0 to 1, higher is better).
- `matchedChunk` — The specific chunk that matched. For short documents this equals the full text.

##### `GET /collections/:name/documents/:id`

Fetch a single document by ID.

**Response (200):**

```json
{
  "id": "doc-1",
  "text": "The Eiffel Tower is a wrought-iron lattice tower in Paris.",
  "metadata": {"source": "wikipedia"}
}
```

Returns `404` if the collection or document doesn't exist.

### Usage from another Actor

```javascript
const VECTOR_DB = "https://your-vector-db.apify.actor";

// Create collection
await fetch(`${VECTOR_DB}/collections/articles`, { method: "PUT" });

// Upsert scraped data
const { ids } = await fetch(`${VECTOR_DB}/collections/articles/upsert`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    documents: scrapedPages.map((page) => ({
      text: page.content,
      metadata: { url: page.url, title: page.title },
    })),
  }),
}).then((r) => r.json());

// Query
const { results } = await fetch(`${VECTOR_DB}/collections/articles/query`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ query: "climate change policy", topK: 5 }),
}).then((r) => r.json());
```

### Persistence

Each collection uses two named KV stores:

- `svdb-{name}-index` — Serialized HNSW graph + label mapping.
- `svdb-{name}-meta` — One entry per document (full text, metadata, chunk texts).

A registry store (`svdb-registry`) tracks which collections exist.

The meta store is the source of truth. If the index is missing or stale on startup, the Actor re-chunks and re-embeds from meta automatically.

### Tech stack

| Component | Choice |
|---|---|
| Runtime | Node.js 22 (TypeScript) |
| HTTP | Express 4 |
| Vector index | `hnswlib-node` (HNSW) |
| Embedding | `@xenova/transformers` / `all-MiniLM-L6-v2` (384 dims, ONNX) |
| Persistence | Apify Named KV Stores |

# Actor input Schema

## Actor input object example

```json
{}
```

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {};

// Run the Actor and wait for it to finish
const run = await client.actor("periwinkle_ballet/simple-vector-database").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {}

# Run the Actor and wait for it to finish
run = client.actor("periwinkle_ballet/simple-vector-database").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{}' |
apify call periwinkle_ballet/simple-vector-database --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=periwinkle_ballet/simple-vector-database",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "Simple Vector Database",
        "description": null,
        "version": "0.0",
        "x-build-id": "5XQL500F3CeymgZzJ"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/periwinkle_ballet~simple-vector-database/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-periwinkle_ballet-simple-vector-database",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for its completion, and returns Actor's dataset items in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        },
        "/acts/periwinkle_ballet~simple-vector-database/runs": {
            "post": {
                "operationId": "runs-sync-periwinkle_ballet-simple-vector-database",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor and returns information about the initiated run in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/runsResponseSchema"
                                }
                            }
                        }
                    }
                }
            }
        },
        "/acts/periwinkle_ballet~simple-vector-database/run-sync": {
            "post": {
                "operationId": "run-sync-periwinkle_ballet-simple-vector-database",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for completion, and returns the OUTPUT from Key-value store in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        }
    },
    "components": {
        "schemas": {
            "inputSchema": {
                "type": "object",
                "properties": {}
            },
            "runsResponseSchema": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "object",
                        "properties": {
                            "id": {
                                "type": "string"
                            },
                            "actId": {
                                "type": "string"
                            },
                            "userId": {
                                "type": "string"
                            },
                            "startedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "finishedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "status": {
                                "type": "string",
                                "example": "READY"
                            },
                            "meta": {
                                "type": "object",
                                "properties": {
                                    "origin": {
                                        "type": "string",
                                        "example": "API"
                                    },
                                    "userAgent": {
                                        "type": "string"
                                    }
                                }
                            },
                            "stats": {
                                "type": "object",
                                "properties": {
                                    "inputBodyLen": {
                                        "type": "integer",
                                        "example": 2000
                                    },
                                    "rebootCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "restartCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "resurrectCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "computeUnits": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "options": {
                                "type": "object",
                                "properties": {
                                    "build": {
                                        "type": "string",
                                        "example": "latest"
                                    },
                                    "timeoutSecs": {
                                        "type": "integer",
                                        "example": 300
                                    },
                                    "memoryMbytes": {
                                        "type": "integer",
                                        "example": 1024
                                    },
                                    "diskMbytes": {
                                        "type": "integer",
                                        "example": 2048
                                    }
                                }
                            },
                            "buildId": {
                                "type": "string"
                            },
                            "defaultKeyValueStoreId": {
                                "type": "string"
                            },
                            "defaultDatasetId": {
                                "type": "string"
                            },
                            "defaultRequestQueueId": {
                                "type": "string"
                            },
                            "buildNumber": {
                                "type": "string",
                                "example": "1.0.0"
                            },
                            "containerUrl": {
                                "type": "string"
                            },
                            "usage": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "integer",
                                        "example": 1
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "usageTotalUsd": {
                                "type": "number",
                                "example": 0.00005
                            },
                            "usageUsd": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "number",
                                        "example": 0.00005
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
