Deployment
Deployment Overview
Section titled “Deployment Overview”This guide covers the complete deployment of the Elasticsearch integration system, including prerequisites, installation steps, configuration, and verification.
Prerequisites
Section titled “Prerequisites”System Requirements
Section titled “System Requirements”Server Requirements
Section titled “Server Requirements”- OS: Linux (Ubuntu 20.04+ / Debian 11+)
- PHP: 8.0+ with required extensions
- Memory: 4GB RAM minimum, 8GB recommended
- Storage: 50GB minimum (grows with product data)
- Network: Stable internet connection
Required PHP Extensions
Section titled “Required PHP Extensions”# Check PHP extensionsphp -m | grep -E "(pgsql|curl|json|mbstring|xml|zip|gd)"
# Install missing extensionssudo apt install php8.1-pgsql php8.1-curl php8.1-json php8.1-mbstring php8.1-xml php8.1-zip php8.1-gdDatabase Requirements
Section titled “Database Requirements”- PostgreSQL: 13.0+ with read/write access
- Database Storage: 20GB minimum for 60K products
- Connection: Network access from web server
Elasticsearch Requirements
Section titled “Elasticsearch Requirements”- Elasticsearch: 7.x (7.10+ recommended)
- Java: OpenJDK 11 or 17
- Memory: 4GB+ for Elasticsearch heap
- Storage: 10GB+ for index data
Network Requirements
Section titled “Network Requirements”Service Connectivity
Section titled “Service Connectivity”- Elasticsearch Server:
91.99.113.45:9200 - Database Server:
162.55.174.116:5432 - Web Server: HTTP/HTTPS access for WordPress
Firewall Configuration
Section titled “Firewall Configuration”# Allow required portssudo ufw allow 22/tcp # SSHsudo ufw allow 80/tcp # HTTPsudo ufw allow 443/tcp # HTTPS
# For Elasticsearch (if remote)sudo ufw allow from <trusted-ip> to any port 9200
# For PostgreSQL (if remote)sudo ufw allow from <trusted-ip> to any port 5432Installation Steps
Section titled “Installation Steps”Step 1: File Deployment
Section titled “Step 1: File Deployment”Deploy Core Files
Section titled “Deploy Core Files”# Navigate to theme directorycd /var/www/html/wp-content/themes/products/
# Deploy Elasticsearch filescp inc/elasticsearch.php inc/cp inc/elasticsearch-console-manager.php inc/cp scripts/elasticsearch-auto-sync.php scripts/cp page-search.php .cp page-elasticsearch-console.php .
# Set permissionssudo chown -R www-data:www-data inc/ scripts/ page-*.phpsudo chmod -R 755 inc/ scripts/ page-*.phpFile Structure Verification
Section titled “File Structure Verification”wp-content/themes/products/├── inc/│ ├── elasticsearch.php ✅ Core ES client│ └── elasticsearch-console-manager.php ✅ Console manager├── scripts/│ └── elasticsearch-auto-sync.php ✅ Sync engine├── page-search.php ✅ Search template├── page-elasticsearch-console.php ✅ Console template└── functions.php ✅ WordPress integrationStep 2: Database Setup
Section titled “Step 2: Database Setup”Add Required Column
Section titled “Add Required Column”-- Connect to databasepsql -h 162.55.174.116 -U website -d categories_db
-- Add sync tracking columnALTER TABLE product ADD COLUMN added_search BOOLEAN DEFAULT FALSE;
-- Create performance indexesCREATE INDEX idx_product_added_search ON product(added_search);CREATE INDEX idx_product_composite ON product(added_search, id) WHERE title IS NOT NULL;CREATE INDEX idx_product_updated ON product(updated_at DESC) WHERE added_search = FALSE;
-- Verify column exists\d productDatabase Connection Test
Section titled “Database Connection Test”# Test database connectionphp -r "\$conn = pg_connect('host=162.55.174.116 dbname=categories_db user=website password=*** port=5432');if (\$conn) { echo 'Database connection successful\n'; \$result = pg_query(\$conn, 'SELECT COUNT(*) FROM product WHERE title IS NOT NULL'); \$row = pg_fetch_row(\$result); echo 'Total products: ' . \$row[0] . '\n';} else { echo 'Database connection failed\n';}"Step 3: Elasticsearch Configuration
Section titled “Step 3: Elasticsearch Configuration”Test Elasticsearch Connection
Section titled “Test Elasticsearch Connection”# Test Elasticsearch connectivitycurl -X GET "http://91.99.113.45:9200/"
# Expected response:# {# "name" : "node-1",# "cluster_name" : "balerina",# "version" : {# "number" : "7.17.0"# }# }Create Index with Lithuanian Mapping
Section titled “Create Index with Lithuanian Mapping”# Create index with proper mappingcurl -X PUT "http://91.99.113.45:9200/products" -H 'Content-Type: application/json' -d'{ "settings": { "number_of_shards": 3, "number_of_replicas": 1, "analysis": { "analyzer": { "lithuanian_analyzer": { "tokenizer": "standard", "filter": [ "lowercase", "asciifolding", "lithuanian_snowball" ] } }, "filter": { "lithuanian_snowball": { "type": "snowball", "language": "Lithuanian" } } } }, "mappings": { "properties": { "id": {"type": "integer"}, "title": { "type": "text", "analyzer": "lithuanian_analyzer" }, "brand": {"type": "keyword"}, "price": {"type": "float"}, "category": {"type": "keyword"}, "availability": {"type": "keyword"} } }}'Step 4: WordPress Configuration
Section titled “Step 4: WordPress Configuration”Create WordPress Pages
Section titled “Create WordPress Pages”# Create search pagewp post create --post_type=page --post_title="Product Search" --post_name="search" --post_status=publish --meta_input='{"_wp_page_template":"page-search.php"}'
# Create console pagewp post create --post_type=page --post_title="Elasticsearch Console" --post_name="elasticsearch-console" --post_status=publish --meta_input='{"_wp_page_template":"page-elasticsearch-console.php"}'Verify Template Assignment
Section titled “Verify Template Assignment”# Check page templateswp post list --post_type=page --fields=ID,post_title,post_name,meta_value --meta_key=_wp_page_templateStep 5: Cron Job Setup
Section titled “Step 5: Cron Job Setup”Add Cron Jobs
Section titled “Add Cron Jobs”# Edit crontabsudo crontab -e
# Add Elasticsearch sync job*/15 * * * * /usr/bin/php /var/www/html/wp-content/themes/products/scripts/elasticsearch-auto-sync.php >> /var/log/dealai/elasticsearch-sync.log 2>&1Create Log Directory
Section titled “Create Log Directory”# Create log directorysudo mkdir -p /var/log/dealaisudo chown www-data:www-data /var/log/dealaisudo chmod 755 /var/log/dealaiVerify Cron Service
Section titled “Verify Cron Service”# Check cron service statussudo systemctl status cron
# Test cron job manuallysudo -u www-data php /var/www/html/wp-content/themes/products/scripts/elasticsearch-auto-sync.phpStep 6: Initial Data Sync
Section titled “Step 6: Initial Data Sync”Run Initial Sync
Section titled “Run Initial Sync”# Run initial synchronizationcd /var/www/html/wp-content/themes/products/scriptsphp elasticsearch-auto-sync.php
# Monitor progresstail -f elasticsearch-auto-sync.logVerify Sync Progress
Section titled “Verify Sync Progress”# Check sync statecat elasticsearch-sync-state.json
# Check Elasticsearch document countcurl -X GET "http://91.99.113.45:9200/products/_count"
# Check database sync statuspsql -h 162.55.174.116 -U website -d categories_db -c "SELECT COUNT(*) as total, COUNT(CASE WHEN added_search = true THEN 1 END) as indexed, ROUND(COUNT(CASE WHEN added_search = true THEN 1 END)::numeric / COUNT(*) * 100, 1) as progress_pctFROM product WHERE title IS NOT NULL;"Configuration
Section titled “Configuration”Environment Configuration
Section titled “Environment Configuration”Create Environment File
Section titled “Create Environment File”# Create .env filecat > /var/www/html/wp-content/themes/products/.env << EOF# Elasticsearch ConfigurationELASTICSEARCH_HOST=91.99.113.45ELASTICSEARCH_PORT=9200ELASTICSEARCH_INDEX=products
# Database ConfigurationDB_HOST=162.55.174.116DB_PORT=5432DB_NAME=categories_dbDB_USER=websiteDB_PASSWORD=your_secure_password
# Sync ConfigurationSYNC_BATCH_SIZE=500SYNC_MAX_TIME=240SYNC_MEMORY_LIMIT=256MEOFSet File Permissions
Section titled “Set File Permissions”# Secure environment filesudo chown www-data:www-data /var/www/html/wp-content/themes/products/.envsudo chmod 600 /var/www/html/wp-content/themes/products/.envWordPress Configuration
Section titled “WordPress Configuration”Update functions.php
Section titled “Update functions.php”// Add to functions.phprequire_once get_template_directory() . '/inc/elasticsearch.php';require_once get_template_directory() . '/inc/elasticsearch-console-manager.php';
// Add AJAX handlersadd_action('wp_ajax_get_elasticsearch_stats', 'ajax_get_elasticsearch_stats');add_action('wp_ajax_search_products', 'ajax_search_products');// ... other AJAX handlersEnqueue Scripts and Styles
Section titled “Enqueue Scripts and Styles”// Add to functions.phpadd_action('wp_enqueue_scripts', 'enqueue_elasticsearch_assets');
function enqueue_elasticsearch_assets() { if (is_page_template('page-search.php') || is_page_template('page-elasticsearch-console.php')) { wp_enqueue_script('jquery'); wp_localize_script('jquery', 'ajax_object', [ 'ajax_url' => admin_url('admin-ajax.php'), 'ajax_nonce' => wp_create_nonce('elasticsearch_nonce'), 'search_nonce' => wp_create_nonce('search_nonce') ]); }}Verification
Section titled “Verification”System Health Checks
Section titled “System Health Checks”1. Database Connection
Section titled “1. Database Connection”# Test database connectionphp -r "require_once '/var/www/html/wp-content/themes/products/inc/elasticsearch.php';\$elasticsearch = new ProductElasticsearch();echo 'Database connection: ' . (\$elasticsearch->testDatabaseConnection() ? 'OK' : 'FAILED') . '\n';"2. Elasticsearch Connection
Section titled “2. Elasticsearch Connection”# Test Elasticsearch connectionphp -r "require_once '/var/www/html/wp-content/themes/products/inc/elasticsearch.php';\$elasticsearch = new ProductElasticsearch();echo 'Elasticsearch connection: ' . (\$elasticsearch->isAvailable() ? 'OK' : 'FAILED') . '\n';echo 'Document count: ' . \$elasticsearch->getDocumentCount() . '\n';"3. WordPress Integration
Section titled “3. WordPress Integration”# Test WordPress pagescurl -I http://your-domain.com/search/curl -I http://your-domain.com/elasticsearch-console/Functional Testing
Section titled “Functional Testing”1. Search Functionality
Section titled “1. Search Functionality”# Test search via AJAXcurl -X POST "http://your-domain.com/wp-admin/admin-ajax.php" \ -d "action=search_products&nonce=test_nonce&query=test" \ -H "Content-Type: application/x-www-form-urlencoded"2. Console Functionality
Section titled “2. Console Functionality”# Test console statscurl -X POST "http://your-domain.com/wp-admin/admin-ajax.php" \ -d "action=get_elasticsearch_stats&nonce=test_nonce" \ -H "Content-Type: application/x-www-form-urlencoded"3. Sync Process
Section titled “3. Sync Process”# Test sync processcd /var/www/html/wp-content/themes/products/scriptsphp elasticsearch-auto-sync.php statsPerformance Optimization
Section titled “Performance Optimization”PHP Configuration
Section titled “PHP Configuration”Optimize PHP Settings
Section titled “Optimize PHP Settings”# Edit php.inisudo nano /etc/php/8.1/fpm/php.ini
# Update settingsmemory_limit = 512Mmax_execution_time = 300upload_max_filesize = 64Mpost_max_size = 64MEnable OPcache
Section titled “Enable OPcache”# Install OPcachesudo apt install php8.1-opcache
# Configure OPcachesudo nano /etc/php/8.1/mods-available/opcache.ini
# Add configurationopcache.enable=1opcache.memory_consumption=256opcache.max_accelerated_files=10000Database Optimization
Section titled “Database Optimization”PostgreSQL Configuration
Section titled “PostgreSQL Configuration”# Edit postgresql.confsudo nano /etc/postgresql/13/main/postgresql.conf
# Update settingsmax_connections = 200shared_buffers = 4GBwork_mem = 50MBmaintenance_work_mem = 1GBDatabase Maintenance
Section titled “Database Maintenance”-- Run maintenanceVACUUM ANALYZE product;VACUUM ANALYZE core_category;
-- Update statisticsANALYZE product;ANALYZE core_category;Elasticsearch Optimization
Section titled “Elasticsearch Optimization”Index Optimization
Section titled “Index Optimization”# Optimize indexcurl -X POST "http://91.99.113.45:9200/products/_optimize?max_num_segments=1"
# Check index healthcurl -X GET "http://91.99.113.45:9200/_cluster/health?pretty"Monitoring Setup
Section titled “Monitoring Setup”Log Monitoring
Section titled “Log Monitoring”Set Up Log Rotation
Section titled “Set Up Log Rotation”# Create logrotate configurationsudo nano /etc/logrotate.d/dealai
# Add configuration/var/log/dealai/*.log { daily missingok rotate 14 compress delaycompress notifempty create 0640 www-data www-data}Monitor Logs
Section titled “Monitor Logs”# Monitor sync logstail -f /var/log/dealai/elasticsearch-sync.log
# Monitor error logstail -f /var/log/apache2/error.log | grep elasticsearchHealth Monitoring
Section titled “Health Monitoring”Set Up Health Checks
Section titled “Set Up Health Checks”# Create health check scriptcat > /usr/local/bin/elasticsearch-health-check.sh << 'EOF'#!/bin/bash
# Check Elasticsearchcurl -s http://91.99.113.45:9200/_cluster/health | grep -q '"status":"green"'if [ $? -ne 0 ]; then echo "Elasticsearch health check failed" exit 1fi
# Check databasepsql -h 162.55.174.116 -U website -d categories_db -c "SELECT 1" > /dev/nullif [ $? -ne 0 ]; then echo "Database health check failed" exit 1fi
echo "All health checks passed"EOF
chmod +x /usr/local/bin/elasticsearch-health-check.shTroubleshooting
Section titled “Troubleshooting”Common Issues
Section titled “Common Issues”1. Database Connection Failed
Section titled “1. Database Connection Failed”# Check PostgreSQL statussudo systemctl status postgresql
# Test connectionpsql -h 162.55.174.116 -U website -d categories_db
# Check firewallsudo ufw status2. Elasticsearch Connection Failed
Section titled “2. Elasticsearch Connection Failed”# Check Elasticsearch statuscurl -X GET "http://91.99.113.45:9200/"
# Check network connectivityping 91.99.113.45telnet 91.99.113.45 92003. Sync Process Not Running
Section titled “3. Sync Process Not Running”# Check cron servicesudo systemctl status cron
# Check cron jobssudo crontab -l
# Test manual syncphp /var/www/html/wp-content/themes/products/scripts/elasticsearch-auto-sync.php4. WordPress Pages Not Loading
Section titled “4. WordPress Pages Not Loading”# Check file permissionsls -la /var/www/html/wp-content/themes/products/page-*.php
# Check WordPress error logstail -f /var/www/html/wp-content/debug.log
# Check Apache error logstail -f /var/log/apache2/error.logRecovery Procedures
Section titled “Recovery Procedures”Reset Sync Process
Section titled “Reset Sync Process”# Reset sync staterm /var/www/html/wp-content/themes/products/scripts/elasticsearch-sync-state.json
# Reset database flagspsql -h 162.55.174.116 -U website -d categories_db -c "UPDATE product SET added_search = FALSE;"
# Delete Elasticsearch indexcurl -X DELETE "http://91.99.113.45:9200/products"
# Restart syncphp /var/www/html/wp-content/themes/products/scripts/elasticsearch-auto-sync.phpNext Steps
Section titled “Next Steps”- Troubleshooting - Common issues and solutions
- Performance Optimization - Performance tuning
- Monitoring & Management - Console and monitoring
- API Endpoints - API reference