Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions src/modules/elasticsearch/classes/Common/ElasticSearchEngine.class.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
<?php
namespace Quanta\Common;

/**
* Class ElasticSearchEngine
* Provides ElasticSearch node indexing on cron, full-text querying, and field facet aggregation (#58).
*/
class ElasticSearchEngine {
/** @var Environment */
protected $env;

/** @var string */
protected $endpoint;

/** @var string */
protected $indexName;

public function __construct($env, string $endpoint = 'http://localhost:9200', string $indexName = 'quanta_nodes') {
$this->env = $env;
$this->endpoint = rtrim(getenv('QUANTA_ELASTICSEARCH_URL') ?: $endpoint, '/');
$this->indexName = getenv('QUANTA_ELASTICSEARCH_INDEX') ?: $indexName;
}

/**
* Indexes a single Quanta Node into ElasticSearch.
*/
public function indexNode(Node $node): bool {
if (!$node->exists) {
return FALSE;
}
$doc = [
'name' => $node->getName(),
'title' => $node->getTitle(),
'teaser' => $node->getTeaser(),
'body' => strip_tags((string) $node->getBody()),
'father' => $node->getFather() ? $node->getFather()->getName() : '',
'status' => $node->getStatus(),
'language' => $node->getLanguage(),
'timestamp' => $node->getTimestamp(),
'attributes' => $node->json ?? [],
];
$url = $this->endpoint . '/' . urlencode($this->indexName) . '/_doc/' . urlencode($node->getName());
return $this->request('PUT', $url, $doc) !== NULL;
}

/**
* Executes a search query with optional facet filters and returns matching hits + aggregations.
*/
public function search(string $queryText = '', array $filters = [], array $facetFields = [], int $size = 20): array {
$must = [];
if (!empty($queryText)) {
$must[] = [
'multi_match' => [
'query' => $queryText,
'fields' => ['title^3', 'teaser^2', 'body'],
],
];
}

$filterClauses = [];
foreach ($filters as $field => $val) {
if ($val !== '' && $val !== NULL) {
$filterClauses[] = ['term' => [$field . '.keyword' => $val]];
}
}

$aggs = [];
foreach ($facetFields as $field) {
$aggs[$field] = [
'terms' => [
'field' => $field . '.keyword',
'size' => 25,
],
];
}

$payload = [
'size' => $size,
'query' => [
'bool' => [
'must' => !empty($must) ? $must : [['match_all' => (object) []]],
'filter' => $filterClauses,
],
],
];
if (!empty($aggs)) {
$payload['aggs'] = $aggs;
}

$url = $this->endpoint . '/' . urlencode($this->indexName) . '/_search';
return $this->request('POST', $url, $payload) ?: ['hits' => ['hits' => []], 'aggregations' => []];
}

protected function request(string $method, string $url, array $payload): ?array {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_TIMEOUT => 5,
]);
$raw = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($raw === FALSE || $code >= 400) {
return NULL;
}
return json_decode($raw, TRUE);
}
}
34 changes: 34 additions & 0 deletions src/modules/elasticsearch/classes/Qtags/Facets.qtag.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php
namespace Quanta\Qtags;
use Quanta\Common\ElasticSearchEngine;

/**
* Class Facets
* Renders faceted search filters as [FACETS:fieldname] qtag (#58).
*/
class Facets extends Qtag {
public function render() {
$field = $this->getTarget();
if (empty($field)) {
return '';
}
$engine = new ElasticSearchEngine($this->env);
$query = isset($_GET['q']) ? (string) $_GET['q'] : '';
$res = $engine->search($query, [], [$field], 0);
$buckets = $res['aggregations'][$field]['buckets'] ?? [];

$selected = isset($_GET['facet_' . $field]) ? (string) $_GET['facet_' . $field] : '';
$html = '<div class="quanta-es-facets" data-field="' . htmlspecialchars($field, ENT_QUOTES) . '">';
$html .= '<ul class="facet-list">';
foreach ($buckets as $bucket) {
$key = (string) ($bucket['key'] ?? '');
$count = (int) ($bucket['doc_count'] ?? 0);
$activeClass = ($selected === $key) ? ' class="active"' : '';
$url = '?q=' . urlencode($query) . '&facet_' . urlencode($field) . '=' . urlencode($key);
$html .= '<li' . $activeClass . '><a href="' . htmlspecialchars($url, ENT_QUOTES) . '">'
. htmlspecialchars($key) . ' <span class="facet-count">(' . $count . ')</span></a></li>';
}
$html .= '</ul></div>';
return $html;
}
}
45 changes: 45 additions & 0 deletions src/modules/elasticsearch/classes/Qtags/Results.qtag.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php
namespace Quanta\Qtags;
use Quanta\Common\ElasticSearchEngine;

/**
* Class Results
* Renders ElasticSearch query results as [RESULTS] qtag (#58).
*/
class Results extends Qtag {
public function render() {
$engine = new ElasticSearchEngine($this->env);
$query = isset($_GET['q']) ? (string) $_GET['q'] : (string) $this->getTarget();
$limit = (int) ($this->getAttribute('limit') ?: 20);

$filters = [];
foreach ($_GET as $k => $v) {
if (strpos($k, 'facet_') === 0 && $v !== '') {
$filters[substr($k, 6)] = (string) $v;
}
}

$res = $engine->search($query, $filters, [], $limit);
$hits = $res['hits']['hits'] ?? [];

if (empty($hits)) {
return '<div class="quanta-es-results empty">No matching results found.</div>';
}

$html = '<div class="quanta-es-results">';
foreach ($hits as $hit) {
$src = $hit['_source'] ?? [];
$name = htmlspecialchars((string) ($src['name'] ?? ''), ENT_QUOTES);
$title = htmlspecialchars((string) ($src['title'] ?? $name));
$teaser = htmlspecialchars((string) ($src['teaser'] ?? ''));
$html .= '<article class="es-result-item">';
$html .= '<h3><a href="/' . $name . '/">' . $title . '</a></h3>';
if (!empty($teaser)) {
$html .= '<p class="es-teaser">' . $teaser . '</p>';
}
$html .= '</article>';
}
$html .= '</div>';
return $html;
}
}
20 changes: 20 additions & 0 deletions src/modules/elasticsearch/hooks/elasticsearch.hook.inc
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php
namespace Quanta\Common;

/**
* Hook implementation for cron-based ElasticSearch node indexing (#58).
*/
function elasticsearch_cron(Environment $env, array $vars = []) {
$engine = new ElasticSearchEngine($env);
$dirs = $env->scanDirectoryDeep($env->dir['docroot'], '', [], FileObject::DIR_SUBDIRS);
foreach ($dirs as $dirPath) {
$nodeName = basename($dirPath);
if (strpos($nodeName, '_') === 0 || strpos($nodeName, '.') === 0) {
continue;
}
$node = NodeFactory::load($env, $nodeName);
if ($node && $node->exists) {
$engine->indexNode($node);
}
}
}