Skip to content

Commit a80e84a

Browse files
committed
initial commit
0 parents  commit a80e84a

21 files changed

+2313
-0
lines changed

CHANGELOG.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Release Notes for Elasticsearch Plugin
2+
3+
## 1.0.0 - 2022-4-08
4+
5+
### Added
6+
7+
- Initial release

LICENSE.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
Copyright © Codemonauts
2+
3+
Permission is hereby granted to any person obtaining a copy of this software (the “Software”) to use, copy, modify, merge, publish and/or distribute copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4+
5+
Don’t plagiarize. The above copyright notice and this license shall be included in all copies or substantial portions of the Software.
6+
7+
Don’t use the same license on more than one project. Each licensed copy of the Software shall be actively installed in no more than one production environment at a time.
8+
9+
Don’t mess with the licensing features. Software features related to licensing shall not be altered or circumvented in any way, including (but not limited to) license validation, payment prompts, feature restrictions, and update eligibility.
10+
11+
Pay up. Payment shall be made immediately upon receipt of any notice, prompt, reminder, or other message indicating that a payment is owed.
12+
13+
Follow the law. All use of the Software shall not violate any applicable law or regulation, nor infringe the rights of any other person or entity.
14+
15+
Failure to comply with the foregoing conditions will automatically and immediately result in termination of the permission granted hereby. This license does not include any right to receive updates to the Software or technical support. Licensees bear all risk related to the quality and performance of the Software and any modifications made or obtained to it, including liability for actual and consequential harm, such as loss or corruption of data, and any necessary service, repair, or correction.
16+
17+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, INCLUDING SPECIAL, INCIDENTAL AND CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Craft's search powered by Elasticsearch
2+
3+
![Icon](resources/search.png)
4+
5+
## Background
6+
7+
Replace Craft's database full-text search with Elasticsearch.
8+
9+
## Requirements
10+
11+
* Craft CMS >= 3.6.18
12+
13+
## Installation
14+
15+
Open your terminal and go to your Craft project:
16+
17+
``` shell
18+
cd /path/to/project
19+
composer require codemonauts/craft-elasticsearch
20+
./craft install/plugin elastic
21+
```
22+
23+
## Usage
24+
25+
For detailed usage information, [visit the docs](https://plugins.codemonauts.com/plugins/elasticsearch/Introduction.html).
26+
27+
With ❤ by [codemonauts](https://codemonauts.com)

composer.json

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
{
2+
"name": "codemonauts/craft-elasticsearch",
3+
"description": "Replace Craft's database full-text search with Elasticsearch.",
4+
"version": "1.0.0",
5+
"type": "craft-plugin",
6+
"keywords": [
7+
"craft",
8+
"cms",
9+
"craftcms",
10+
"craft-plugin",
11+
"Elasticsearch"
12+
],
13+
"license": "proprietary",
14+
"authors": [
15+
{
16+
"name": "codemonauts",
17+
"homepage": "https://codemonauts.com"
18+
}
19+
],
20+
"support": {
21+
"source": "https://github.com/codemonauts/craft-elasticsearch",
22+
"docs": "https://plugins.codemonauts.com/plugins/elasticsearch/Introduction.html",
23+
"issues": "https://github.com/codemonauts/craft-elasticsearch/issues"
24+
},
25+
"require": {
26+
"craftcms/cms": "^3.6.18",
27+
"elasticsearch/elasticsearch": "^7.0",
28+
"jsq/amazon-es-php": "^0.3.0"
29+
},
30+
"autoload": {
31+
"psr-4": {
32+
"codemonauts\\elastic\\": "src/"
33+
}
34+
},
35+
"extra": {
36+
"handle": "elastic",
37+
"class": "codemonauts\\elastic\\Elastic",
38+
"name": "Search powered by Elasticsearch",
39+
"description": "Replace Craft's database full-text search with Elasticsearch.",
40+
"changelogUrl": "https://raw.githubusercontent.com/codemonauts/craft-elasticsearch/blob/main/CHANGELOG.md",
41+
"documentationUrl": "https://plugins.codemonauts.com/plugins/elasticsearch/Introduction.html"
42+
}
43+
}

resources/search.png

5.2 KB
Loading

src/Elastic.php

Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,207 @@
1+
<?php
2+
3+
namespace codemonauts\elastic;
4+
5+
use codemonauts\elastic\jobs\UpdateMapping;
6+
use codemonauts\elastic\jobs\UpdateSearchIndex;
7+
use codemonauts\elastic\models\Settings;
8+
use codemonauts\elastic\services\Elasticsearch;
9+
use codemonauts\elastic\services\Indexes;
10+
use codemonauts\elastic\services\Search;
11+
use codemonauts\elastic\utilities\IndexUtility;
12+
use Craft;
13+
use craft\base\ElementInterface;
14+
use craft\base\Plugin;
15+
use craft\events\ElementEvent;
16+
use craft\events\RegisterComponentTypesEvent;
17+
use craft\helpers\App;
18+
use craft\helpers\ElementHelper;
19+
use craft\helpers\UrlHelper;
20+
use craft\services\Elements;
21+
use craft\services\Fields;
22+
use craft\services\Utilities;
23+
24+
/**
25+
* @property Elasticsearch $elasticsearch
26+
* @property Indexes $indexes
27+
* @property Search $search
28+
*/
29+
class Elastic extends Plugin
30+
{
31+
/**
32+
* @var Elastic
33+
*/
34+
public static $plugin;
35+
36+
/**
37+
* @var Settings
38+
*/
39+
public static $settings;
40+
41+
/**
42+
* @inheritDoc
43+
*/
44+
public $hasCpSettings = true;
45+
46+
/**
47+
* @inheritDoc
48+
*/
49+
public function init(): void
50+
{
51+
parent::init();
52+
53+
self::$plugin = $this;
54+
55+
self::$settings = self::$plugin->getSettings();
56+
57+
// If no endpoint is set, do nothing.
58+
if (Elastic::env(self::$settings->endpoint) === '') {
59+
return;
60+
}
61+
62+
// If not in transition mode, replace the Craft internal search component
63+
if (!self::$settings->transition) {
64+
$componentConfig = [
65+
'search' => Search::class,
66+
];
67+
Craft::$app->setComponents($componentConfig);
68+
}
69+
70+
// Add the plugin search components
71+
$componentConfig = [
72+
'elasticsearch' => [
73+
'class' => Elasticsearch::class,
74+
'hosts' => [
75+
Elastic::env(self::$settings->endpoint),
76+
],
77+
'authentication' => self::$settings->authentication,
78+
'username' => Elastic::env(self::$settings->username),
79+
'password' => Elastic::env(self::$settings->password),
80+
'region' => Elastic::env(self::$settings->region),
81+
],
82+
'indexes' => [
83+
'class' => Indexes::class,
84+
'indexName' => Elastic::env(self::$settings->indexName),
85+
],
86+
'elements' => services\Elements::class,
87+
'search' => Search::class,
88+
];
89+
$this->setComponents($componentConfig);
90+
91+
// When in transition mode, add event to update Elasticsearch indexes as well.
92+
if (self::$settings->transition) {
93+
Craft::$app->elements->on(Elements::EVENT_AFTER_SAVE_ELEMENT, function(ElementEvent $event) {
94+
/**
95+
* @var ElementInterface $element
96+
*/
97+
$element = $event->element;
98+
$elementType = get_class($element);
99+
100+
if (ElementHelper::isDraftOrRevision($element)) {
101+
return;
102+
}
103+
104+
if (count($element::searchableAttributes()) === 0) {
105+
return;
106+
}
107+
108+
Craft::$app->getQueue()->push(new UpdateSearchIndex([
109+
'elementType' => $elementType,
110+
'elementId' => $element->id,
111+
]));
112+
});
113+
}
114+
115+
// Register event when changing field definitions
116+
Craft::$app->fields->on(Fields::EVENT_AFTER_SAVE_FIELD, function() {
117+
Craft::$app->queue->push(new UpdateMapping());
118+
});
119+
120+
// Register utilities
121+
Craft::$app->getUtilities()->on(Utilities::EVENT_REGISTER_UTILITY_TYPES, function(RegisterComponentTypesEvent $event) {
122+
$event->types[] = IndexUtility::class;
123+
});
124+
}
125+
126+
/**
127+
* @inheritDoc
128+
*/
129+
public function afterInstall()
130+
{
131+
parent::afterInstall();
132+
133+
if (Craft::$app->getRequest()->getIsConsoleRequest()) {
134+
return;
135+
}
136+
137+
Craft::$app->getResponse()->redirect(
138+
UrlHelper::cpUrl('settings/plugins/elastic')
139+
)->send();
140+
}
141+
142+
/**
143+
* @inheritDoc
144+
*/
145+
protected function createSettingsModel()
146+
{
147+
return new Settings();
148+
}
149+
150+
/**
151+
* @inheritDoc
152+
*/
153+
protected function settingsHtml(): ?string
154+
{
155+
return Craft::$app->getView()->renderTemplate('elastic/settings', [
156+
'settings' => $this->getSettings(),
157+
'authenticationOptions' => [
158+
'aws' => 'AWS',
159+
'basicauth' => 'BasicAuth'
160+
]
161+
]
162+
);
163+
}
164+
165+
/**
166+
* Parse environment string. Should be replaced with Craft's App::parseEnv after dropping 3.6 support.
167+
*
168+
* @param string|null $str The string to parse.
169+
*
170+
* @return array|string|null
171+
*/
172+
public static function env(string $str = null)
173+
{
174+
if ($str === null) {
175+
return null;
176+
}
177+
178+
if (preg_match('/^\$(\w+)$/', $str, $matches)) {
179+
$value = App::env($matches[1]);
180+
if ($value !== false) {
181+
$str = $value;
182+
}
183+
}
184+
185+
return $str;
186+
}
187+
188+
public function getElasticsearch(): Elasticsearch
189+
{
190+
return $this->get('elasticsearch');
191+
}
192+
193+
public function getIndexes(): Indexes
194+
{
195+
return $this->get('indexes');
196+
}
197+
198+
public function getSearch(): Search
199+
{
200+
return $this->get('search');
201+
}
202+
203+
public function getElements(): services\Elements
204+
{
205+
return $this->get('elements');
206+
}
207+
}
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
<?php
2+
3+
namespace codemonauts\elastic\console\controllers;
4+
5+
use codemonauts\elastic\jobs\UpdateSearchIndex;
6+
use Craft;
7+
use craft\base\ElementInterface;
8+
use craft\db\Query;
9+
use craft\db\Table;
10+
use craft\helpers\Console;
11+
use yii\base\NotSupportedException;
12+
use yii\console\Controller;
13+
14+
class ElementsController extends Controller
15+
{
16+
/**
17+
* Reindex elements to current index.
18+
*
19+
* @param string $siteHandle The site to index. Default '*' to reindex elements of all sites.
20+
* @param string $channel The queue channel to use.
21+
* @param int $priority The queue priority to use.
22+
*/
23+
public function actionReindex(string $siteHandle = '*', string $channel = 'queue', int $priority = 2048)
24+
{
25+
$queue = Craft::$app->$channel;
26+
$elementsTable = Table::ELEMENTS;
27+
28+
/**
29+
* @var ElementInterface $elementType
30+
*/
31+
$elementTypesToIndex = [];
32+
$elementTypes = Craft::$app->elements->getAllElementTypes();
33+
foreach ($elementTypes as $elementType) {
34+
$attributes = $elementType::searchableAttributes();
35+
if (!$elementType::hasTitles() && count($attributes) === 0) {
36+
continue;
37+
}
38+
$count = (new Query())->from($elementsTable)->where([
39+
'dateDeleted' => null,
40+
'revisionId' => null,
41+
'type' => $elementType,
42+
])->count();
43+
44+
if ($this->confirm("Reindex all $count elements of type '$elementType'? ")) {
45+
$elementTypesToIndex[] = $elementType;
46+
}
47+
}
48+
49+
foreach ($elementTypesToIndex as $type) {
50+
$query = (new Query())->select(['id', 'type'])
51+
->from($elementsTable)
52+
->where([
53+
'dateDeleted' => null,
54+
'revisionId' => null,
55+
'type' => $type,
56+
])
57+
->orderBy('dateCreated desc');
58+
59+
$total = $query->count();
60+
$counter = 0;
61+
62+
$this->stdout("Reindex $total elements of type '$type' ..." . PHP_EOL);
63+
64+
Console::startProgress(0, $total);
65+
foreach ($query->batch() as $rows) {
66+
foreach ($rows as $element) {
67+
$job = new UpdateSearchIndex([
68+
'elementType' => $element['type'],
69+
'elementId' => $element['id'],
70+
'siteId' => $siteHandle,
71+
]);
72+
try {
73+
$queue->priority($priority)->push($job);
74+
} catch (NotSupportedException $e) {
75+
$queue->push($job);
76+
}
77+
Console::updateProgress(++$counter, $total);
78+
}
79+
}
80+
Console::endProgress();
81+
}
82+
}
83+
}

0 commit comments

Comments
 (0)