A distributed, high-performance hybrid search engine.
KhojEngine combines keyword matching with semantic search to deliver highly accurate results. By decoupling document ingestion from heavy machine learning workloads, the system remains fast and responsive under load.
To provide a search solution that understands both exact text matches and general meaning, without slowing down the API layer during heavy data ingestion.
- Internal Knowledge Bases: Search through thousands of company documents, wikis, and technical specs where terminology varies.
- E-commerce Product Search: Allow users to find items using natural descriptions ("warm winter jacket") instead of exact product names.
- Customer Support: Automatically suggest relevant help center articles based on the context of a user's support ticket.
- Hybrid Search: Merges keyword matching with semantic meaning to find the best results.
- Asynchronous Ingestion: Accepts documents instantly and queues them for background processing.
- Background Machine Learning: Uses dedicated workers to generate document embeddings.
- Cache Management: Uses a global versioning system to prevent stale search results.
- Pagination Support: Navigate through large sets of search results easily.
- API Framework: FastAPI
- Message Pipeline: Apache Kafka
- Semantic Database: PostgreSQL with pgvector
- Keyword Database: Elasticsearch
- Cache and Rate Limiting: Redis
- Machine Learning: sentence-transformers (all-MiniLM-L6-v2)
KhojEngine/
├── services/
│ ├── api-service/ # Handles search and recommendations
│ ├── ingestion-service/ # Accepts new documents
│ ├── processing-service/ # Validates and cleans raw text
│ └── embedding-service/ # Generates vectors and indexes data
├── tests/ # Integration and end-to-end tests
├── docker-compose.yml # Orchestrates the cluster
└── init-db.sql # PostgreSQL initialization script
Make sure you have Docker and Docker Compose installed.
-
Build the system images:
docker compose build
-
Start the cluster:
docker compose up -d
Wait 30-45 seconds for Kafka and Elasticsearch to initialize on the first run.
-
Copy the environment variables template:
cp .env.example .env
To quickly verify the system is running correctly:
- Install the testing dependency:
python3 -m pip install requests
- Run the integration test:
python3 tests/test_integration.py
External APIs (api-service :8000)
(Requires X-API-Key header)
POST /api/v1/search- Run a keyword, semantic, or hybrid search.POST /api/v1/recommend/item- Find documents similar to a specific document ID.POST /api/v1/recommend/context- Find documents similar to a provided block of text.
Internal APIs (ingestion-service :8001)
POST /internal/batch- Submit a batch of new documents for ingestion.GET /internal/jobs/{job_id}- Check the processing status of a document batch.
Health Checks & Metrics
GET /health/ready- Basic readiness probe.GET /metrics- Prometheus-compatible metrics export.
curl -X POST "http://localhost:8000/api/v1/search" \
-H "Content-Type: application/json" \
-H "X-API-Key: khoj_test_key_123" \
-d '{
"query": "What is quantum computing?",
"mode": "hybrid",
"top_k": 2,
"skip": 0
}'{
"query": "What is quantum computing?",
"mode": "hybrid",
"total_results": 2,
"results": [
{
"doc_id": "doc_101",
"title": "Introduction to Quantum Mechanics",
"score": 0.89,
"source": "wiki",
"tags": ["physics", "computing"]
},
{
"doc_id": "doc_245",
"title": "Quantum Supremacy Explained",
"score": 0.76,
"source": "blog",
"tags": ["tech"]
}
]
}401 Unauthorized (Invalid or missing API key)
{
"detail": "Invalid or missing API key"
}429 Too Many Requests (Rate limit exceeded)
{
"detail": "Rate limit exceeded. Try again later."
}404 Not Found (Checking a job ID that doesn't exist)
{
"detail": "Job not found"
}- Dead Letter Queue (DLQ): If a document fails processing, it is routed to a
dead-letter-queueKafka topic instead of blocking the pipeline. - Retries: Both Elasticsearch and PostgreSQL queries use automatic exponential backoff retries to handle temporary network hiccups.
- Idempotency: Documents use upsert logic based on their unique
doc_id. Reprocessing the same Kafka message safely overwrites the existing record without duplicating data.
- API Layer: The FastAPI instances (
api-service,ingestion-service) are stateless and can be scaled horizontally behind a load balancer. - Workers: The
processing-serviceandembedding-servicecan be scaled horizontally by adding more consumer instances to the Kafka consumer group. - Databases: Elasticsearch handles distributed clustering natively. PostgreSQL can be scaled using read replicas for heavy traffic.
- Model constraints: The
all-MiniLM-L6-v2model has a strict 256-token limit. Documents longer than this will have their text truncated during the embedding phase. - Memory usage: Storing dense 384-dimensional vectors in PostgreSQL consumes significantly more RAM than standard relational data.
- Latency: Searching via the
pgvectorHNSW index is fast, but combining and normalizing scores across millions of records in memory at the API layer adds overhead for broad queries.
The project includes a simple web interface for testing. Open your browser and navigate to:
http://localhost:8000/
When prompted, enter the test API Key: khoj_test_key_123
- Add support for larger embedding models to handle longer context windows.
- Implement soft-TTL cache invalidation to replace immediate global eviction.
- Add user-level document permissions.